使时间序列在轴上显示最后日期? [英] Make time series show last date in axis?
问题描述
所以在 Chart.js 中,我有一个基于日期范围的时间序列.该图表无法将所有日期显示为轴标签,因此它显示了合理的选择.它总是在左侧显示第一个日期,但并不总是在轴的右端显示最后一个日期.
So in Chart.js i have a time series based on a range of dates. The chart can't show all the dates as axis label so it shows a reasonable selection. It always shows the first date on the left but not always the last date at the right end of the axis.
例如,我的日期范围可能是从 1 月 1 日到 7 月 30 日的每一天.该轴将从 1 月 1 日开始,但结束日期可能是 27 月 28 日或 7 月 29 日.
For example my date range could be every day from 01-jan to 30-jul. The axis will start at 01-jan but the end date might be 27 28 or 29 jul.
对我来说,结束日期比开始日期更重要.有没有办法可靠地显示最后日期并让开始日期成为变化的日期?
To me the end date is more important than the start date. Is there a way to show the last date reliably and let the start date be the one that varies?
推荐答案
这可以通过实现你自己的 ticks.maxTicksLimit
.您必须按以下步骤进行.
This could be solved by implementing your own ticks.maxTicksLimit
on the xAxis
. You would have to proceed as follows.
- 将
xAxis
定义为 时间接受data
作为 "nofollow noreferrer">数据点 使用包含x
和y
属性的对象. - 根据数据中包含的日期生成
labels
数组.此数组应包含开始日期和结束日期以及两者之间平均分布的天数(请参阅下面代码片段中的函数createLabels
). - 告诉 Chart.js 通过定义
tick.sources: 'labels'
.
- 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>
这篇关于使时间序列在轴上显示最后日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!