1👍
✅
This could be solved by somehow implement 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 an object containingx
andy
properties. - Generate a
labels
array out of the years contained in your data. This array should contain the starting year and end year together with a number of equally spread years 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 = [];
for (let year = new Date().getFullYear() - 29; year <= new Date().getFullYear(); year++) {
data.push({
x: year.toString(),
y: Math.floor((Math.random() * 6) + 1)
})
}
const maxTicksLimit = 6;
function createLabels() {
const years = data.map(o => Number(o.x));
const startTime = years[0];
const endTime = years[years.length - 1];
const tickGap = (endTime - startTime) / (maxTicksLimit - 1);
const labels = [startTime];
for (let i = 1; i < maxTicksLimit - 1; i++) {
labels.push(Math.round(startTime + i * tickGap));
}
labels.push(endTime);
return labels.map(l => l.toString());
}
new Chart('myChart', {
type: 'line',
data: {
labels: createLabels(),
datasets: [{
label: 'Demo',
fill: false,
data: data,
borderColor: 'blue'
}]
},
options: {
scales: {
xAxes: [{
type: 'time',
time: {
parser: 'YYYY',
unit: 'year'
},
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="80"></canvas>
Source:stackexchange.com