背景
我试图使用 highchart 显示与小时动态相关的平均流量。就是说我想让它像这样反复显示流量,下次到23:00的时候我想让它回到0:00。
我通过设置 24 个类别 ['0:00', '1:00'...,'23:00'] 来做到这一点,并在 ajax 更新数据时添加点,比如每 1 秒。
var chart = new Highcharts.Chart({
...//some options
xAxis: {
categories:['0:00','1:00','2:00',...,'23:00']
},
load: function() {setInterval(updateData,1000)}
series: [] //empty series here, adding dynamically by ajax
})
updateData 被定义为一个函数
function updateData(){
var data = $.ajax(...)// get the data
var series = chart.series[0];
if(series.data.length < 24){ //when data.length is < 24 add directly
chart.series[0].addPoint(data,true,false);
}else{
chart.series[0].addPoint(data,true,true);//set the 3rd option to true to remove the first data point, actually here this data is equal to the first one since this is a circle, when it comes to 24:00 it is actually 0:00, and I should update the xAxis.
//code updating the axis categories to [1:00, 2:00...23:00,0:00]
xAxis.setCategories(categories);
}
}
x轴原来是[ 2:00 , 3:00, ...23:00, 0:00, 24 ],也就是说我这次添加的点不对应类别[24 ]:0:00,其实对应的是不存在的categories[25],所以默认设置为24。
解决方案(快速而肮脏)
不要环转移类别,而是将一个新的圈推到它上面,例如:
categories.push("time");//time is 0:00-23:00
xAxis.setCategories(categories);
但这会使类别越来越大……这很糟糕。我怎样才能解决这个问题。
另一个解决方案(也有一些问题)
通过使用 datetime 作为 x 轴的类型,还有另一个问题。我的数据格式如下
time count
8:00 23
9:00 56
... ...
我可以构造像 [time, count] 这样的点,问题是我只有时间。即使我通过手动添加日期来构建数据
time = (new Date("2012-11-17 "+time)).getTime()
似乎可行。但是当它经过 24 小时后,样条曲线又回到了图表的左侧,因为这里的 x 轴值等于第一个值。
BTW:如何让x轴只显示时间,上图左侧显示日期,自动显示时间间隔如何让它全部显示?感谢您的关注!!!
我听从了@Ruchit Rami 的建议并修改了我的代码:
/*update part*/
var time = series.points.length > 0 ? series.points[series.points.length-1].category+3600 : 0;
//from 1970-1-1 0:00 And **add 1 hour everytime**
if (series.data.length < 24) {
series.addPoint([time, sum],true,false);
} else {
series.addPoint([time, sum],true,true);
}
/*chart part*/
xAxis: {
type: 'datetime',
dateTimeLabelFormat: {
second: '%H:%M',
minute: '%H:%M',
hour: '%H:%M',
day: '%H:%M',
week: '%H:%M',
month: '%H:%M',
year: '%H:%M'
}
tickInterval: 3600
}
结果
尽管我指定了日期标签格式,但似乎没有受到影响
而且时间不正确。为什么?谢谢!
仍然没有正确显示