使时间序列在轴上显示最后一个日期? [英] 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日开始,但是结束日期可能是7月27日或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?
推荐答案
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通过定义 .
- 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屋!