How to plot date/month/year range in chart.js?

Member

by lottie , in category: Javascript , 5 months ago

How to plot date/month/year range in chart.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by daisha , a month ago

@lottie 

To plot a date/month/year range in Chart.js, you will need to use the built-in time scale in the library. Here's a step-by-step guide on how to do it:

  1. First, make sure you have Chart.js included in your project. You can add it to your HTML file using a CDN or by downloading it and linking it in your project.
1
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>


  1. Create a canvas element in your HTML where you want to display the chart.
1
<canvas id="myChart"></canvas>


  1. Now, you can create a new Chart object in your JavaScript file and specify the type of chart you want to create (e.g., line chart), along with the data and options for the chart.
 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
28
29
30
31
32
33
34
35
36
37
38
39
var ctx = document.getElementById('myChart').getContext('2d');

var myChart = new Chart(ctx, {
    type: 'line',
    data: {
        labels: ['01/01/2022', '02/01/2022', '03/01/2022', '04/01/2022', '05/01/2022'],
        datasets: [{
            label: 'Date Range',
            data: [10, 20, 30, 40, 50],
            borderColor: 'blue',
            borderWidth: 1
        }]
    },
    options: {
        scales: {
            x: {
                type: 'time',
                time: {
                    parser: 'MM/DD/YYYY',
                    tooltipFormat: 'll',
                    unit: 'month',
                    displayFormats: {
                        month: 'MMM YYYY'
                    }
                },
                title: {
                    display: true,
                    text: 'Date'
                }
            },
            y: {
                title: {
                    display: true,
                    text: 'Value'
                }
            }
        }
    }
});


  1. In the above code snippet, we are using the 'time' type for the x-axis scale and specifying the format of the date labels. You can customize the format and appearance of the chart by modifying the data and options objects as needed.
  2. Finally, after setting up the Chart object, the line chart with the specified date range should be displayed in the canvas element on the webpage.


Note: Make sure to replace the sample data and options with your actual data and chart configurations.