X和Y值对的数据 [英] Data with pair X and Y values

查看:146
本文介绍了X和Y值对的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在Chart.js的 data 选项中使用一对X和Y创建条形字符?

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]
],

[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
            }]


推荐答案

没有内置的方法可以直接在数据中使用数组来创建图表。

There is no built-in way to create your chart using an array straight into the data.

但是您可以使用 Chart.js插件。它们使您可以处理在整个图表创建期间触发的事件,例如在初始化图表之前,在调整大小之后等。



跟随一个小插件,它将为您填充所有数据使用数组:

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]);
        }
    }
};

然后,您需要将此新创建的插件添加到Chart插件服务中:

Then you need to add this newly created plugin to your Chart plugin services :

Chart.pluginService.register(myPlugin);



确保在之前注册插件创建图表(在调用前 new Chart()),否则它将不起作用。

我也建议(在插件出现之前)在图表中保留一个空数据,以确保您没有不需要的数据。


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.

您可以看到一个完全正常的工作例如在此jsFiddle上

You can see a fully working example on this jsFiddle.

这篇关于X和Y值对的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆