我想创建一个函数,我可以将数据发送到我的折线图。我的功能目前看起来像这样:
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();
}
标签是一个字符串
xp1,xp2,yp1,yp2 是双打
我正在运行一个执行此功能的循环。什么都没发生,我的图表仍然是空白的。
我查看了Chart.js docs,它似乎对我的情况没有帮助,看起来他们的示例代码中有错误
这是我的开始代码:
var ctx = document.getElementById('chart').getContext('2d');
var chart = new Chart(ctx, {
type: 'line',
data: {
labels: [''],
datasets: [{}]
},
options: {}
});
这是我希望它填写后的样子:
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: {}
});
答案 0 :(得分:3)
您需要以这种方式更改您的功能:
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 :(得分:0)
您可以直接访问数据并使用以下内容更新内容:
chart.data.datasets[0].data.push( {x:5, y:2} ,{x:10, y:12},...,{x:50, y:25} );
如果您要维护系列绘画/颜色设置,这会更容易。