How to create a dynamic multi-line chart in chart.js?

by edmond_brakus , in category: Javascript , 10 months ago

How to create a dynamic multi-line chart in chart.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by scotty_walker , 5 months ago

@edmond_brakus 

To create a dynamic multi-line chart in Chart.js, you will need to follow these steps:

  1. Include the Chart.js library in your HTML file. You can either download the library and include it locally or use a CDN link to include it from a remote server.
1
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>


  1. Create a canvas element in your HTML where the chart will be rendered.
1
<canvas id="myChart"></canvas>


  1. Create a JavaScript file and define your 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
var ctx = document.getElementById('myChart').getContext('2d');

var chartData = {
    labels: ['January', 'February', 'March', 'April', 'May', 'June'],
    datasets: [
        {
            label: 'Dataset 1',
            data: [10, 20, 15, 30, 25, 40],
            borderColor: 'red'
        },
        {
            label: 'Dataset 2',
            data: [5, 15, 10, 25, 20, 35],
            borderColor: 'blue'
        }
    ]
};

var chartOptions = {
    responsive: true,
    maintainAspectRatio: false
};

var myChart = new Chart(ctx, {
    type: 'line',
    data: chartData,
    options: chartOptions
});


  1. Update the chart data dynamically using JavaScript.
1
2
3
4
5
6
7
8
// Add a new data point to Dataset 1
myChart.data.datasets[0].data.push(50);

// Update the labels
myChart.data.labels.push('July');

// Update the chart
myChart.update();


  1. You can also remove data points, datasets, or labels dynamically using JavaScript.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
// Remove the last data point from Dataset 1
myChart.data.datasets[0].data.pop();

// Remove the last label
myChart.data.labels.pop();

// Remove Dataset 2
myChart.data.datasets.pop();

// Update the chart
myChart.update();


By following these steps, you can create a dynamic multi-line chart in Chart.js that can be updated and modified dynamically using JavaScript.