Chart.js bar color based on labels values

亡梦爱人 提交于 2021-02-08 05:45:43

问题


The code I need is here: chart.js bar chart color change based on value
Dola changes the color of the bars based on the values of the datasets using myObjBar.datasets[0].bars
I want to do the same thing but with the labels values (good, average, bad) e.g.

var barChartData = {
    labels: ["good", "average", "bad"],
    datasets: [
        {
            data: [1, 3, 10]
        }
    ]
};

var ctx = document.getElementById("mycanvas").getContext("2d");
    window.myObjBar = new Chart(ctx).Bar(barChartData, {
          responsive : true
});

var bars = myObjBar.labels[0]; //I need this line
 for(i=0;i<bars.length;i++){
    var color="green";
    if(bars[i].value=="bad"){
       color="red";
       }
       else if(bars[i].value=="average"){
        color="orange"
       }
       else{
        color="green"
       }
       bars[i].fillColor = color;
    }
myObjBar.update();

回答1:


Instead of using bars[i].value property, you can use bars[i].label which gives you the label of the xAxe.

So in your loop, change to this :

for(i=0;i<bars.length;i++){
    var color="green";

    if(bars[i].label == "bad"){
        color="red";
    }
    else if(bars[i].label == "average"){
        color="orange"
    }
    else{
        color="green"
    }
    bars[i].fillColor = color;
}

You can find the full code in this jsFiddle and here is its result :



来源:https://stackoverflow.com/questions/39404626/chart-js-bar-color-based-on-labels-values

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