Chart.js bar color based on labels values - Javascript Chart.js

Javascript examples for Chart.js:Bar Chart

Description

Chart.js bar color based on labels values

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript" src=" https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.js"></script> 
      <script type="text/javascript">
    window.onload=function(){/*from ww w.ja  v  a2  s.  c  om*/
var barChartData = {
    labels: ["bad", "average", "good"],
    datasets: [{
        label: "My First dataset",
        fillColor: "rgba(220,220,220,0.5)",
        strokeColor: "rgba(220,220,220,0.8)",
        highlightFill: "rgba(220,220,220,0.75)",
        highlightStroke: "rgba(220,220,220,1)",
        data: [1, 5, 10]
    }]
};
var ctx = document.getElementById("mycanvas").getContext("2d");
window.myObjBar = new Chart(ctx).Bar(barChartData, {
    responsive: true
});
var bars = myObjBar.datasets[0].bars;
for (i = 0; i < bars.length; i++) {
    var color = "green";
    console.log(bars);
    if (bars[i].label == "bad") {
        color = "red";
    } else if (bars[i].label == "average") {
        color = "orange"
    } else {
        color = "green"
    }
    bars[i].fillColor = color;
}
myObjBar.update(); //update the cahrt
    }
      </script> 
   </head> 
   <body> 
      <canvas id="mycanvas"></canvas>  
   </body>
</html>

Related Tutorials