1 回答

TA貢獻1833條經驗 獲得超4個贊
這可以通過以某種方式實現您自己的 ticks.maxTicksLimit
來解決。您必須按以下步驟操作。xAxis
從數據中包含的年份中生成一個數組。此數組應包含起始年份和結束年份以及兩者之間平均分布的年份(請參閱下面代碼段中的函數)。
labels
createLabels
告訴圖表.js通過定義
tick.sources:“標簽”
來生成給定標簽。ticks
xAxis
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>
添加回答
舉報