Data with pair X and Y values

偶尔善良 提交于 2020-01-13 18:12:09

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!