有没有办法在 highcharts 中创建图表,以便显示每个相关月份的第一天?例如在这个 chart ,如何设置选项,使其显示 10 月 1 日、11 月 1 日、12 月 1 日、1 月 1 日等。如果也显示其他日期也可以,但需要每月的第一天。
最佳答案
这绝对是可能的,尽管需要一些工作。
首先,您需要将要在图表中使用的数据设为全局数据。您可以通过在使用 .highcharts()
函数之前定义它来实现此目的。我们暂时将此全局数据称为 var DATA
。
我们想使用 highchart 的 xAxis.tickPositions
得到你想要的格式。所以我们需要定义这些精确的刻度。我编写了一些代码来完成此任务(给定全局 DATA
):
var globalMin = Date.UTC(5000, 1, 1);
var globalMax = 0;
for (i = 0; i < DATA.length; i++) {
var temp = DATA[i].slice();
var sorted = temp.sort(function(d1, d2){
return d2[0]-d1[0];
});
var max_date = sorted[0];
var min_date = sorted[sorted.length-1];
if (max_date[0] > globalMax)
globalMax = max_date[0];
if (min_date[0] < globalMin)
globalMin = min_date[0];
}
function monthDiff(d1, d2) {
return d2.getMonth()-d1.getMonth() + (12 * (d2.getFullYear()-d1.getFullYear())) + 2;
}
var ticks = [];
var mind = new Date(globalMin);
var maxd = new Date(globalMax);
for (i = 0; i < monthDiff(mind, maxd); i++) {
var tempDate = new Date(new Date(mind).setMonth(mind.getMonth()+i));
ticks.push(tempDate.setDate(1));
}
此代码创建数组 ticks
,其中包含 highcharts 定义中的 tickPositions
。
所以剩下的就是在 xAxis
定义中使用这个数组:
xAxis: {
type: 'datetime',
tickPositions: ticks,
min: ticks[0], // Remove this if you want an automatic range
max: ticks[ticks.length - 1], // Remove this if you want an automatic range
dateTimeLabelFormats: {
month: '%e. %b',
year: '%b'
},
title: {
text: 'Date'
},
labels: {
formatter: function () {
return Highcharts.dateFormat('%e. %B', this.value);
}
},
}, ...
请注意,我在这里使用了修复来解决 known bug并使 tickPositions
显示正确。
DEMO
关于javascript - 在 Highcharts 上显示每月 1 号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31978660/