How to use type: 'time' for line chart in chart.js?

Member

by ryleigh , in category: Javascript , 7 months ago

How to use type: 'time' for line chart in chart.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by arnoldo.moen , 7 months ago

@ryleigh 

To use the type 'time' for a line chart in Chart.js, you need to specify the type as 'time' in the x-axis configuration of your chart options. Here is an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
    type: 'line',
    data: {
        labels: ["2022-01-01", "2022-02-01", "2022-03-01", "2022-04-01", "2022-05-01"],
        datasets: [{
            label: 'My Dataset',
            data: [10, 20, 15, 25, 30],
            borderColor: 'blue',
            fill: false
        }]
    },
    options: {
        scales: {
            x: {
                type: 'time',
                time: {
                    unit: 'month'
                }
            }
        }
    }
});


In this example, we have set the x-axis configuration to be of type 'time' and specified the time unit as 'month'. This will display the x-axis labels as time units and format the chart accordingly.


You can customize the time unit or format according to your requirements using the options available in the Chart.js documentation.