我希望图表的最终 X 轴上始终有一个值,
我不能将它用作“distribution: 'series'”,因为它超出了规模,
我不能总是猜测将哪个值作为“时间:{min/max}”以使其超过最后一个值,而且我也无法手动定义Y轴上将显示哪些数据。
是否可以像下面的示例一样定义数据?
X 轴值:
1 - 2020-04-01
2 - 2020-04-03
3 - 2020-04-08
4 - 2020-04-10
5 - 2020-04-15
Y轴如:
x x x x x
|_____________|____________|__
04-01 04-07 04-15
现在,我在轴 04-01/04-07/04-15
上手动定义了这三个值,即使没有数据包含 04-07
> 作为日期。
最佳答案
从您的代码中我看到您尝试了不同的方法,包括 ticks.autoskip
和 ticks.maxTicksLimit
。如果需要,这两个选项都会限制刻度标签的数量,但不保证最后一个标签对应于最后一个数据点。
要以干净的方式解决此问题,您必须实现自己的 ticks.maxTicksLimit
在xAxis
上。这可以通过以下方式完成。
- 根据数据中包含的时间生成一个
labels
数组。该数组应包含数据开始和结束时间以及两者之间指定的平均分布时间数(请参阅下面修改后的代码中的函数createLabels
)。 - 告诉 Chart.js 通过定义
tick.sources: 'labels'
在给定标签的xAxis
上生成刻度.
const data = [
{ t: new Date("2015-3-15 13:30"), y: 12 },
{ t: new Date("2015-3-25 13:20"), y: 21 },
{ t: new Date("2015-3-26 13:20"), y: 21 },
{ t: new Date("2015-3-27 13:20"), y: 21 },
{ t: new Date("2015-5-14 13:20"), y: 21 },
{ t: new Date("2015-7-25 14:12"), y: 32 },
{ t: new Date("2015-08-01 14:12"), y: 40 },
{ t: new Date("2015-08-10 14:12"), y: 40 },
{ t: new Date("2015-08-11 14:12"), y: 40 },
{ t: new Date("2015-09-20 14:12"), y: 40 }
];
function createLabels(maxTicksLimit) {
const times = data.map(o => o.t.getTime());
const startTime = times[0];
const endTime = times[times.length -1];
const tickGap = ( endTime - startTime) / (maxTicksLimit - 1);
const labels = [startTime];
for (let i = 1; i < maxTicksLimit - 1; i++) {
labels.push(startTime + i * tickGap);
}
labels.push(endTime);
return labels;
}
var myChart = new Chart(document.getElementById("examChart"), {
type: 'line',
data: {
labels: createLabels(12),
datasets: [{
label: 'Demo',
fill: false,
data: data,
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
xAxes: [{
type: 'time',
ticks: {
source: 'labels',
minRotation: 45
},
time: {
unit: 'day',
displayFormats: {
day: 'DD/MM/YYYY'
},
tooltipFormat: 'DD/MM/YYYY'
}
}],
yAxes: [{
ticks: {
suggestedMin: 0
},
gridLines: {
zeroLineColor: "rgba(0,255,0,1)"
},
scaleLabel: {
display: true,
labelString: 'y axis'
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.js"></script>
<div class="container" style="width:50%;">
<canvas id="examChart"></canvas>
</div>
关于javascript - 即使没有相关的 Y 轴值,如何使用 Chart.js 的日期作为 X 轴,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61257815/