0👍
✅
This could be solved by implementing your own ticks.maxTicksLimit
on the xAxis
. You would have to proceed as follows.
- Define the
xAxis
as a time cartesian axis that accepts thedata
as an array of data points using objects containingx
andy
properties each. - Generate a
labels
array out of the dates contained in your data. This array should contain the starting day and end day together with a number of equally spread days between both (see functioncreateLabels
in the code snippet below). - Tell Chart.js to generate
ticks
on thexAxis
from given labels by definingtick.sources: 'labels'
.
const data = [];
let date = Date.parse('2020-01-01');
for (let day = 1; day <= 31; day++) {
date = new Date(date);
date.setDate(day);
data.push({
x: date,
y: Math.floor((Math.random() * 6) + 1)
})
};
const maxTicksLimit = 8;
function createLabels() {
const days = data.map(o => o.x);
const startTime = days[0];
const endTime = days[days.length - 1];
const tickGap = data.length / (maxTicksLimit - 1);
const labels = [startTime];
for (let i = 1; i < maxTicksLimit - 1; i++) {
labels.push(days[Math.floor(i * tickGap)]);
}
labels.push(endTime);
return labels;
}
new Chart('myChart', {
type: 'line',
data: {
labels: createLabels(),
datasets: [{
label: 'My Dataset',
fill: false,
data: data,
borderColor: 'blue'
}]
},
options: {
scales: {
xAxes: [{
type: 'time',
time: {
unit: 'day'
},
ticks: {
source: 'labels'
}
}],
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
<canvas id="myChart" height="90"></canvas>
Source:stackexchange.com