当使用Highcharts 时,若x轴为时间,同时需要设置plotBands情节带。
假设有这样的数据,x轴为日期,data是数据,当Mark标记为1的时候设置plotBands。当设置x轴数据时,将时间进行Date.UTC处理,UTC() 方法可根据世界时间返回 1970 年 1 月 1 日 到指定日期的毫秒数。则半天的时间就是1000*60*60*12;为了使plotBands中一天的数据居中,可以将form属性设置为当天日期减去半天,to属性设置为当天的日期加上半天。
[
{
"日期":"2015-10-18",
"mark":0,
"data":"1.23"
},
{
"日期":"2015-10-19",
"mark":1,
"data":"1.85"
},
{
"日期":"2015-10-20",
"mark":0,
"data":"0.31"
}............
代码:
var jsonstr='[{"日期":"2015-10-18","mark":0,"data":"1.23"},{"日期":"2015-10-19","mark":1,"data":"1.85"},' +
'{"日期":"2015-10-20","mark":0,"data":"0.31"},{"日期":"2015-10-21","mark":0,"data":"1.39"},' +
'{"日期":"2015-10-22","mark":0,"data":"3.54"},{"日期":"2015-10-23","mark":0,"data":""},' +
'{"日期":"2015-10-24","mark":1,"data":""},{"日期":"2015-10-25","mark":1,"data":""},' +
'{"日期":"2015-10-26","mark":1,"data":""},{"日期":"2015-10-27","mark":0,"data":""},' +
'{"日期":"2015-10-28","mark":0,"data":"1.54"},{"日期":"2015-10-29","mark":0,"data":"0.46"},' +
'{"日期":"2015-10-30","mark":0,"data":"1.08"},{"日期":"2015-10-31","mark":0,"data":"1.23"}]';
var json=JSON.parse(jsonstr);
var data=[];
var plotbandArray=[];
var halfDay=1000*60*60*12;
json.forEach(function(item,index)
{
var someDate = new Date(Date.parse(item["日期"]));
//进行Date.UTC处理
var tms=Date.UTC(someDate.getFullYear(), someDate.getMonth(), someDate.getDate());
data.push([tms,Number(item.data)]);
if(item.mark==1)
{
var plotItem={};
plotItem['from']=tms-halfDay;
plotItem['to']=tms+halfDay;
plotItem['color']='rgba(23,232,156,0.2)';
plotbandArray.push(plotItem);
}
})
var options={
chart: {
zoomType: 'xy'
},
title: {
text: 'test',
},
xAxis: [{
type: 'datetime',
dateTimeLabelFormats: {
/* millisecond: '%H:%M:%S.%L',
second: '%H:%M:%S',
minute: '%H:%M',
hour: '%H:%M', */
day: '%m-%d',
week: '%m-%d',
month: '%Y-%m',
year: '%Y'
},
// reversed : true,
plotBands: plotbandArray
}],
yAxis: [
{
lineColor: '#E8E8E8',
lineWidth: 1,
labels: {
style: {
color: Highcharts.getOptions().colors[1]
}
},
title: {
text: 'data',
style: {
color: Highcharts.getOptions().colors[1]
}
}
},
],
tooltip: {
dateTimeLabelFormats: {
/* millisecond: '%H:%M:%S.%L',
second: '%H:%M:%S',
minute: '%H:%M',
hour: '%H:%M', */
day: '%Y-%m-%d',
week: '%m-%d',
month: '%Y-%m',
year: '%Y'
},
shared: true
},
credits:false,
legend: {
layout: 'horizontal',
align: 'left',
x: 50,
verticalAlign: 'top',
y: 10,
floating: true,
backgroundColor: (Highcharts.theme && Highcharts.theme.legendBackgroundColor) || '#FFFFFF'
},
series: [{
name: 'data',
yAxis:0,
type: 'spline',
data: data,
}
]};
$('#container').highcharts(options);
效果: