0👍
✅
If you have the actual times of the two datasets, you can just use those to place the points on to the x axis. So you could:
- keep the times in each dataset
- don’t define labels
- set the type of the x axis as "time" instead of the default "category" (include the required adapter and set other relevant properties)
- define parsing keys for convenience.
Then every point is placed at the correct time, where it was defined, and everything falls in place. Here’s a simplified version of your code with those changes:
let date = new Date();
date.setDate(date.getDate() - 10);
const tenDays = [];
for (let i = 0; i < 10; i++) {
const dateToDisplay = date.setDate(date.getDate() + 1);
//array of 10 days in history from now
tenDays.push({
time: dateToDisplay,
value: Math.floor(Math.random() * 10)
})
}
date = new Date();
date.setDate(date.getDate() - 10);
//array of only three days, in tenDays array that is 1st, 5th and 10th day
const threeDays = [{
time: date.setDate(date.getDate() + 1),
value: 6
},
{
time: date.setDate(date.getDate() + 4),
value: 4
},
{
time: date.setDate(date.getDate() + 5),
value: 5
},
];
//create Chart
new Chart(document.querySelector('#chart'), {
type: 'line',
data: {
datasets: [{
data: tenDays,
label: "many"
},
{
data: threeDays,
label: "few"
}
]
},
options: {
responsive: true,
maintainAspectRatio: false,
parsing: {
xAxisKey: "time",
yAxisKey: "value",
},
scales: {
x: {
type: "time",
time: {
unit: "day"
}
}
}
},
});
<div style="min-height:300px">
<canvas id="chart"></canvas>
</div>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns@3.0.0/dist/chartjs-adapter-date-fns.bundle.min.js"></script>
I’m not sure if that was what you were after, whether you have the actual times for both datasets/
Source:stackexchange.com