How to change x-axis interval on chart.js?

by mallory_cormier , in category: Javascript , 9 months ago

How to change x-axis interval on chart.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by jerad , 9 months ago

@mallory_cormier 

To change the x-axis interval on a Chart.js chart, you can use the 'stepSize' property in the scale configuration of the x-axis. Here's an example on how to do this:

 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
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, 20, 30, 40, 50, 60, 70]
        }]
    },
    options: {
        scales: {
            x: [{
                type: 'category',
                labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
                scaleLabel: {
                    display: true,
                    labelString: 'Month'
                },
                ticks: {
                    stepSize: 2 // Change the x-axis interval to 2
                }
            }]
        }
    }
});


In this example, the 'stepSize' property is set to 2 in the 'ticks' configuration of the x-axis scale. This will change the x-axis interval to 2, meaning that every other label will be displayed on the x-axis. You can adjust the 'stepSize' value to change the interval as needed.