Chart.js update bars of a bar-chart

时间:2016-10-15 17:03:42

标签: javascript chart.js

I've got a BarChart on my Webpage using Chart.js.

Ive added two datapoints to it using

chart.addData([5], "A");
chart.addData([7], "B");

Now I want to update those bars A and B without removing them and adding them again (which I already figured out how to do that). I want them to move vertically to adjust to their new values but I cant find out how to access the data thats already in the chart.

Theres nothing like

chart.updateData(0,[6]);
chart.updateData(1,[9]);

where the first value would be the index of the stored data (f.e.).

How should I do this?

1 个答案:

答案 0 :(得分:4)

一般情况下,您希望浏览数据对象,添加,删除或替换元素,然后调用.update,就是这样。

以下是我在图表末尾添加2个列的示例:

function addData() {
  myBarChart.data.labels[12] ="2017";
  myBarChart.data.labels[13] ="2018";
  myBarChart.data.datasets[0].data[12] = 500;
  myBarChart.data.datasets[0].data[13] = 600;
  myBarChart.update();
}

更具体地说,在这里,我修改了一年的价值:

function adjust2016() {
  myBarChart.data.datasets[0].data[11] = 300;
  myBarChart.update();
}

完整示例:

Codepen Chart.js Add replace data example