根据值更改条形颜色
问题描述:
我正在将chart-js / ng2-charts用于一个有角度的2应用程序。
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.
可以做到吗?
答
创建图表后,可以使用以下函数遍历数据集并根据数据值更改颜色。
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.
在此示例中,如果该值大于50,则颜色变为红色。
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演示: https://jsfiddle.net/6d0jsyxu/1/
JSFiddle Demo: https://jsfiddle.net/6d0jsyxu/1/