jQuery在x轴上绘制月份,年份的折线图

时间:2014-03-20 16:41:30

标签: javascript jquery ajax json flot

我试图在x轴上生成月,年的图表。请在下面查看以下内容:

enter image description here

图表的数据是通过ajax获得的。请查看以下样本json:

{"total":[[2013,4,0],[2013,5,0],[2013,6,0],[2013,7,0],[2013,8,0],[2013,9,0],[2013,10,475],[2013,11,0],[2013,12,0],[2014,1,367],[2014,2,0],[2014,3,0]],"critical":[[2013,4,0],[2013,5,0],[2013,6,0],[2013,7,0],[2013,8,0],[2013,9,0],[2013,10,0],[2013,11,0],[2013,12,0],[2014,1,1],[2014,2,0],[2014,3,0]],"high":[[2013,4,0],[2013,5,0],[2013,6,0],[2013,7,0],[2013,8,0],[2013,9,0],[2013,10,20],[2013,11,0],[2013,12,0],[2014,1,20],[2014,2,0],[2014,3,0]],"medium":[[2013,4,0],[2013,5,0],[2013,6,0],[2013,7,0],[2013,8,0],[2013,9,0],[2013,10,24],[2013,11,0],[2013,12,0],[2014,1,135],[2014,2,0],[2014,3,0]],"low":[[2013,4,0],[2013,5,0],[2013,6,0],[2013,7,0],[2013,8,0],[2013,9,0],[2013,10,42],[2013,11,0],[2013,12,0],[2014,1,26],[2014,2,0],[2014,3,0]]}

在上面的例子中[2013,4,0]应转换为x轴:2013年4月,y轴:0。

请告诉我如何实现这一目标?

感谢。

2 个答案:

答案 0 :(得分:6)

我是这样做的:

// your JSON
obj = {"total":[[2013,4,0],[2013,5,0],[2013,6,0],[2013,7,0],[2013,8,0],[2013,9,0],[2013,10,475],[2013,11,0],[2013,12,0],[2014,1,367],[2014,2,0],[2014,3,0]],"critical":[[2013,4,0],[2013,5,0],[2013,6,0],[2013,7,0],[2013,8,0],[2013,9,0],[2013,10,0],[2013,11,0],[2013,12,0],[2014,1,1],[2014,2,0],[2014,3,0]],"high":[[2013,4,0],[2013,5,0],[2013,6,0],[2013,7,0],[2013,8,0],[2013,9,0],[2013,10,20],[2013,11,0],[2013,12,0],[2014,1,20],[2014,2,0],[2014,3,0]],"medium":[[2013,4,0],[2013,5,0],[2013,6,0],[2013,7,0],[2013,8,0],[2013,9,0],[2013,10,24],[2013,11,0],[2013,12,0],[2014,1,135],[2014,2,0],[2014,3,0]],"low":[[2013,4,0],[2013,5,0],[2013,6,0],[2013,7,0],[2013,8,0],[2013,9,0],[2013,10,42],[2013,11,0],[2013,12,0],[2014,1,26],[2014,2,0],[2014,3,0]]};

// reformat into the format flot likes
seriesData = [];    
for (var prop in obj) {
    // push in the series, the "property" is the label
    // use $.map to produce an array of [date, y-value]
    // the new Date(i[0],i[1]-1).getTime(), 
    // will give you the epoch time for the first day of that month/year
    seriesData.push({label: prop, data:$.map(obj[prop], function(i,j){
         return [[new Date(i[0],i[1]-1).getTime(), i[2]]];
    })});    
}

// plot it!
$.plot("#placeholder", seriesData, {
    xaxis: { mode: "time", timeformat: "%b %Y" }
});

小提琴here

修改:ji[2]更改,以显示正确绘制的数据。

答案 1 :(得分:2)

在选项中:

xaxis: {mode: "time", timeformat: "%b %m"}

使用time plugin

必须将数据转换为时间戳,如链接中所述。因为你当天有0,可能是这样的:

tstamp = new Date(dat[0]*1000*3600*24*30*12+dat[1]*1000*3600*24*30)
相关问题