Change bar color depending on value

一个人想着一个人 提交于 2020-01-07 04:41:05

问题


I'm using chart-js/ng2-charts for an angular 2 app.

I can display a bar graph, but at the moment, all the bars are the same color. I'd like to have a different color depending on the value.

Can that be done?


回答1:


After you create your chart, you can use the following function to loop through the dataset and change the color depending on the data value.

In this example, if the value is above a 50, the color changes to red.

var colorChangeValue = 50; //set this to whatever is the deciding color change value
var dataset = myChart.data.datasets[0];
for (var i = 0; i < dataset.data.length; i++) {
  if (dataset.data[i] > colorChangeValue) {
    dataset.backgroundColor[i] = chartColors.red;
  }
}
myChart.update();

JSFiddle Demo: https://jsfiddle.net/6d0jsyxu/1/



来源:https://stackoverflow.com/questions/43968743/change-bar-color-depending-on-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!