javascript - jQuery Flot 折线图,x 轴为月份、年份

标签 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。

您能告诉我如何实现这一目标吗?

谢谢。

最佳答案

我的做法是这样的:

// 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" }
});

fiddle here .

编辑:已将 j 更改为 i[2],以便正确显示绘制的数据。

关于javascript - jQuery Flot 折线图,x 轴为月份、年份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22539603/

相关文章:

javascript - 将任意 JavaScript 代码存储到字符串变量中

Javascript toString 对我来说毫无意义

jquery - 使用 AJAX 初始化数据表后使用 .row.add()

javascript - 为什么这个 URL 数据传递有效而另一个无效?

javascript - Material-UI 和 React - 将 &lt;input&gt; 更改为 <TextField> 会阻止表单提交工作?

javascript - 使用 Firefox 访问 Restdb.io API 时收到错误

显示空白的 Jquery 内容选项卡

javascript - 图表 Js 单击按钮即可显示更多数据集

javascript - 使用 jquery-validate 使用 ajax 验证表单

javascript - 函数不会停止运行