2👍
✅
This can be done by defining datasets.data
as an array of objects having an x
and y
property each.
data: [
{ 'x': 1, 'y': 2 },
{ 'x': 2, 'y': 4 },
{ 'x': 3, 'y': 6 },
{ 'x': 4, 'y': 8 },
{ 'x': 5, 'y': 10 }
]
You can use Array.map()
to easily convert your data. Please take a look at below runnable code and see how it works.
const y = [2, 4, 6, 8, 10];
const x1 = [1, 2, 3, 4, 5];
const x2 = [5, 6, 7, 8, 9];
const x3 = [8, 9, 10, 12, 14];
new Chart('myChart', {
type: 'line',
data: {
datasets: [{
label: 'A',
data: y.map((v, i) => ({ x: x1[i], y: v })),
borderColor: 'rgb(255, 0, 0)',
backgroundColor: 'rgba(255, 0, 0, 0.2)'
},
{
label: 'B',
data: y.map((v, i) => ({ x: x2[i], y: v })),
borderColor: 'rgb(0, 255, 0)',
backgroundColor: 'rgba(0, 255, 0, 0.2)'
},
{
label: 'C',
data: y.map((v, i) => ({ x: x3[i], y: v })),
borderColor: 'rgb(0, 0, 255)',
backgroundColor: 'rgba(0, 0, 255, 0.2)'
}]
},
options: {
scales: {
x: {
type: 'linear',
suggestedMin: 1,
suggestedMax: 14,
ticks: {
stepSize: 1
}
},
y: {
beginAtZero: true
}
}
},
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.8.0/chart.js"></script>
<canvas id="myChart" height="80"></canvas>
Source:stackexchange.com