使用多个x / y网格动态更新Chart.JS中的散点图/折线图

时间:2021-04-03 21:16:35

I would like to create a function that I can send data to push to my line chart. My function currently looks like this:

我想创建一个函数,我可以发送数据推送到我的折线图。我的功能目前看起来像这样:

function addData(label, xp1, yp1, xp2, yp2) {
  chart.data.labels.push(label);
  chart.data.datasets.data.push({x: xp1, y: yp1}, {x: xp2, y: yp2}); 
  chart.update();
}

label is a string

label是一个字符串

xp1, xp2, yp1, yp2 are doubles

xp1,xp2,yp1,yp2是双打

I am running a loop that will execute this function. Nothing happens and my chart remains blank.

我正在运行一个将执行此功能的循环。什么都没发生,我的图表仍然是空白。

I have looked at the Chart.js docs and it doesn't seem to be helpful for my situation and it appears they have errors in their example code

我查看了Chart.js文档,它似乎对我的情况没有帮助,看起来它们的示例代码中有错误

This is my starting code:

这是我的起始代码:

var ctx = document.getElementById('chart').getContext('2d');
var chart = new Chart(ctx, {
    type: 'line',
    data: {
        labels: [''],
        datasets: [{}]
    },
    options: {}
});

This is what I expect it to look like once it's filled in:

这是我希望它一旦填满就会看起来像:

var ctx = document.getElementById('chart').getContext('2d');
var chart = new Chart(ctx, {
    type: 'line',
    data: {
        labels: ['a', 'b', 'c'],
        datasets: [{
            label: 'a',
            fill: false,
            data: [
                {
                    x: 0,
                    y: 9
                }, {
                    x: 3,
                    y: 9
                }
            ]
        },
        {
            label: 'a',
            fill: false,
            data: [
                {
                    x: 3,
                    y: 7
                }, {
                    x: 5,
                    y: 7
                }
            ]
        },
        {
            label: 'c',
            fill: false,
            data: [
                {
                    x: 5,
                    y: 5
                }, {
                    x: 10,
                    y: 5
                }
            ]
        }]
    },
    options: {}
});

1 个解决方案

#1


3  

You need to change your function that way:

你需要改变你的功能:

function addData(label, xp1, yp1, xp2, yp2) {
    chart.data.labels.push(label);
    chart.data.datasets.push({ label: label, fill: false, data: [{ {x: xp1, y: yp1}, {x: xp2, y: yp2} }] });
    chart.update();
}

#1


3  

You need to change your function that way:

你需要改变你的功能:

function addData(label, xp1, yp1, xp2, yp2) {
    chart.data.labels.push(label);
    chart.data.datasets.push({ label: label, fill: false, data: [{ {x: xp1, y: yp1}, {x: xp2, y: yp2} }] });
    chart.update();
}