我有一个API返回jqplot图表的绘图点,我想知道是否有任何方法可以更改它们以便插入chart.js图表?
API返回的点字符串类似于以下内容:
[[[1473396905000,1.925],[1473402008000,3.8978],[1473402311000,1.3657],[1473402605000,1.3194],[1473402905000,1.4289],[1473403206000,1.5782],[1473403505000,1.1818],[1473403807000,1.5151],[1473404105000,1.3052],[1473404406000,1.9036],[1473404706000,2.4173],[1473405006000,2.6117],[1473405305000,1.3249],[1473405605000,1.2773],[1473405905000,1.8293],[1473406206000,1.4242],[1473406505000,1.1342],[1473406806000,1.7527],[1473407106000,1.3627],[1473407406000,1.6494],[1473407705000,1.7232],[1473408006000,1.446],[1473408305000,1.5607],[1473408606000,1.5104],[1473408906000,1.4078],[1473409205000,1.5034],[1473409506000,1.8224],[1473409806000,2.2752],[1473410104000,1.0881],[1473410404000,1.509],[1473410705000,1.0817],[1473411005000,1.3751],[1473411305000,1.1361],[1473411606000,1.33],[1473411906000,1.5136],[1473412206000,1.6084],[1473412506000,1.0594],[1473412806000,1.544],[1473413106000,1.7347],[1473413406000,1.3446],[1473413705000,1.4276],[1473414006000,1.6119],[1473414306000,1.1018]]]
任何帮助都很棒
答案 0 :(得分:1)
通过一个小的解决方法,可以实现您想要的目标。
您需要使用Chart.js plugins,这样您就可以处理在创建所有图表时发生的事件(beforeInit
,afterUpdate
,afterDraw
...)并且很容易实施:
Chart.pluginService.register({
beforeInit: function(chart) {
// This will be triggered before the chart initalization
}
});
<小时/> 现在,您只需使用插件填充
labels
和data
数组:
var fromAPI = [[[1473396905000,1.925],[1473402008000,3.8978],[1473402311000,1.3657]]];
Chart.pluginService.register({
beforeInit: function(chart) {
// We store the data -- Making it more readable
var data = chart.config.data;
// For each dataset in your array ..
for (var i = 0; i < fromAPI.length; i++) {
// For each data in your dataset ..
for (var j = 0; j < fromAPI[i].length; j++) {
// Populate the `labels` array with the first element
data.labels[j] = fromAPI[i][j][0];
// Populate the `data` array of this specific dataset with the 2nd element
data.datasets[i].data[j] = fromAPI[i][j][1];
}
}
}
});
您可以看到in this jsFiddle完整代码,结果如下: