Reputation: 4033
I have an API that returns plot points for a jqplot chart, i was wondering if there is any way to change them so they will plug into a chart.js chart?
The string of points returned by the API is similar to the following:
[[[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]]]
Any help would be awesome
Upvotes: 1
Views: 148
Reputation: 14187
With a small workaround, it is possible to achieve what you want.
You need to use Chart.js plugins, which let you handle events which occur through all the chart creation (beforeInit
, afterUpdate
, afterDraw
...) and are easy to implement :
Chart.pluginService.register({
beforeInit: function(chart) {
// This will be triggered before the chart initalization
}
});
labels
and the data
arrays using plugins :
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];
}
}
}
});
You can see in this jsFiddle the full code, and here is its result :
Upvotes: 1