最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Chart.js update bars of a bar-chart - Stack Overflow

programmeradmin8浏览0评论

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?

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?

Share Improve this question asked Oct 15, 2016 at 17:03 RaviorRavior 6113 gold badges11 silver badges30 bronze badges 1
  • "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)" ... oh my ...gawd . besides the obvious flaw in your title and your question .. what is the code you used to "update the bars" – user1752532 Commented Oct 15, 2016 at 17:50
Add a ment  | 

1 Answer 1

Reset to default 5

In general, you want to go through your data object, add,delete or replace your elements and then call .update , that's it.

Here's an example where I add 2 more columns at the end of a chart:

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

And more specifically to your case, here I modify the value of one year:

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

Full Example:

Codepen Chart.js Add replace data example

发布评论

评论列表(0)

  1. 暂无评论