2👍
✅
LeeLenalee‘s perfectly shows how Chart.js is instructed to correctly parse your data. In order to obtain a time line, you’ll also need to define the x-axis as a time cartesian axis.
Please take a look at below runnable code and see how it works.
new Chart('myChart', {
type: 'line',
data: {
datasets: [{
label: 'Purchases per day',
data: [
{ 'date': '15/06', 'bought': 2 },
{ 'date': '17/06', 'bought': 5 },
{ 'date': '20/06', 'bought': 3 }
],
borderColor: 'rgb(0, 0, 255)',
backgroundColor: 'rgba(0, 0, 255, 0.5)'
}]
},
options: {
parsing: {
xAxisKey: 'date',
yAxisKey: 'bought'
},
scales: {
y: {
ticks: {
stepSize: 1
}
},
x: {
type: 'time',
time: {
parser: 'DD/MM',
unit: 'day',
tooltipFormat:'MMM DD'
}
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.3.2/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/moment@2.27.0"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-moment@0.1.1"></script>
<canvas id="myChart" height="90"></canvas>
👍:2
You can just provide that array as is to chart.js, you only need to specify which field should be mapped to the x Axis and which field to the yAxis in the parsing block of the options object.
Live example:
var options = {
type: 'line',
data: {
datasets: [
{
label: '# of Votes',
data: [{'date': '15/06', 'bought': 2}, {'date': '17/06', 'bought': 5}, {'date': '20/06', 'bought': 3}],
borderWidth: 1
}
]
},
options: {
parsing: {
xAxisKey: 'date',
yAxisKey: 'bought'
}
}
}
var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.3.2/chart.js"></script>
</body>