How to create a custom logarithmic axis in chart.js?

Member

by deron , in category: Javascript , 10 months ago

How to create a custom logarithmic axis in chart.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by gilbert , 10 months ago

@deron 

To create a custom logarithmic axis in Chart.js, you can use the linear scale type along with a custom ticks callback function in the configuration options of your chart. Here's an example of how you can create a logarithmic y-axis:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
var ctx = document.getElementById('myChart').getContext('2d');

var myChart = new Chart(ctx, {
    type: 'line',
    data: {
        labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
        datasets: [{
            label: 'My Dataset',
            data: [10, 100, 1000, 10000, 100000, 1000000, 10000000],
            backgroundColor: 'rgba(255, 99, 132, 0.2)',
            borderColor: 'rgba(255, 99, 132, 1)',
            borderWidth: 1
        }]
    },
    options: {
        scales: {
            y: {
                type: 'linear',
                ticks: {
                    callback: function (value, index, values) {
                        return value.toString().replace(/B(?=(d{3})+(?!d))/g, ",");
                    }
                }
            }
        }
    }
});


In the above example, we set the type of the y-axis scale to linear and provide a custom callback function for the ticks configuration. The callback function formats the y-axis labels with commas for better readability when displaying large numbers.


You can customize the callback function based on your specific requirements for the logarithmic scale. Additionally, you can adjust the data and labels in the datasets array to fit your data for the chart.


By using a custom ticks callback function, you can create a logarithmic scale effect for your y-axis in Chart.js.