Chart.js bar chart color change based on value - Javascript Chart.js

Javascript examples for Chart.js:Bar Chart

Description

Chart.js bar chart color change based on value

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(){//w ww  . j av a  2  s.  c o m
var barChartData = {
    labels: ["January", "February", "March"],
    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, 3, 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";
       if(bars[i].value<3){
          color="red";
       }
       else if(bars[i].value<5){
          color="orange"
       }
       else if(bars[i].value<8){
          color="yellow"
       }
       else{
          color="green"
       }
       bars[i].fillColor = color;
    }
    myObjBar.update(); //update the cahrt
}

      </script> 
   </head> 
   <body> 
      <canvas id="mycanvas"></canvas>  
   </body>
</html>

Related Tutorials