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

查看:15
本文介绍了具有 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]);
        }
    }
};

然后你需要将这个新创建的插件添加到你的图表插件服务中:

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天全站免登陆