To create a chart with multiple lines, we can just create a line chart that display multiple data sets.
To do that, we first start with including the Chart.js library.
Also, we add the moment.js library for formatting dates, and a canvas element for Chart.js to render the chart in.
We do that by writing:
<script src='https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js'></script>
<canvas id="multipleLineChart" width="400" height="400"></canvas>
Next, we create our chart with multiple lines by writing the following:
const ctx = document.getElementById('multipleLineChart').getContext('2d');
const chart = new Chart(ctx, {
type: 'line',
data: {
labels: [
moment(new Date(2020, 2, 1)).format('YYYY-MM-DD'),
moment(new Date(2020, 2, 2)).format('YYYY-MM-DD'),
moment(new Date(2020, 2, 3)).format('YYYY-MM-DD')
],
datasets: [{
label: '# of Red Votes',
data: [12, 18, 22],
borderWidth: 1,
fill: false,
borderColor: 'red'
},
{
label: '# of Green Votes',
data: [12, 2, 13],
borderWidth: 1,
fill: false,
borderColor: 'green'
}
]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
We set the type
property to 'line'
to display line charts.
Then we have the labels
property to display the labels for the x-axis.
In the datasets
property, we set the value to an array.
The array has the data
property to set the y-axis value for where the dot is displayed.
We set the fill
property to false
so that we don’t get any filling between the line and the x-axis.
borderColor
has the color value of the line. We set one to 'red'
and the other to 'green'
.
In the options
property, we set the beginAtZero
property to true
so that the y-axis begins at zero.
Once we write that code, we get a chart with multiple lines with one being red and the other being green.
It looks like: