问题
Is it possible to use a the pair X and Y in the data
option in Chart.js to create the bar char?
data: [
['08/09/2016', 12],
['09/09/2016', 19]
],
Being in the form of [X, Y]
I didn't find any reference about it in the docs. The closer I got was this found in the line charts example:
data: [{
x: -10,
y: 0
}, {
x: 0,
y: 10
}, {
x: 10,
y: 5
}]
回答1:
There is no built-in way to create your chart using an array straight into the data.
But you can create a small work around using Chart.js plugins. They let you handle events triggered during the whole creation of the chart, such as before it is initialized, after a resize, etc.
Follows a small plugin that will populate all the data for you using an array :
var myPlugin = {
// We edit what is happening before the chart is initialized.
beforeInit: function(chart) {
var data = chart.config.data;
// `APIarray` is what you get from your API.
// For every data in this array ...
for (var i = 0; i < APIarray.length; i++) {
// Populate the labels array with the first value ..
data.labels.push(APIarray[i][0]);
// .. and the data with the second value
data.datasets[0].data.push(APIarray[i][1]);
}
}
};
Then you need to add this newly created plugin to your Chart plugin services :
Chart.pluginService.register(myPlugin);
Make sure to register the plugin before creating the chart (before calling
new Chart()
), or else it won't work.I also suggest to have an empty data in your chart (before the plugin occurs) to make sure you won't have data you don't want.
You can see a fully working example on this jsFiddle.
来源:https://stackoverflow.com/questions/39705268/data-with-pair-x-and-y-values