How to draw multiple lines in chart.js?

by dalton_moen , in category: Javascript , 3 months ago

How to draw multiple lines in chart.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by lindsey.homenick , 3 months ago

@dalton_moen 

To draw multiple lines in Chart.js, you can follow these steps:


Step 1: Include Chart.js library in your HTML page.

1
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>


Step 2: Create a canvas element in your HTML where you want to render the chart.

1
<canvas id="myChart"></canvas>


Step 3: Create a JavaScript script to define the chart data and options.

 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 chart = new Chart(ctx, {
    type: 'line',
    data: {
        labels: ['January', 'February', 'March', 'April', 'May', 'June'],
        datasets: [
            {
                label: 'Line 1',
                data: [10, 20, 15, 25, 30, 35],
                borderColor: 'red',
                fill: false
            },
            {
                label: 'Line 2',
                data: [5, 10, 20, 15, 25, 12],
                borderColor: 'blue',
                fill: false
            }
        ]
    },
    options: {
        responsive: true,
        title: {
            display: true,
            text: 'Multiple Lines Chart'
        }
    }
});


In the above example, the data array consists of two datasets representing two lines. Each dataset has a label to define the line name, data array to specify the data points for the line, borderColor to set the line color, and fill set to false to disable filling the area below the line.


The options object is used to configure the chart. You can customize various options such as responsive layout, chart title, axis labels, etc.