Set colors of bars in a bar chart based on their value - Javascript Chart.js

Javascript examples for Chart.js:Bar Chart

Description

Set colors of bars in a bar chart based on their 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/2.1.2/Chart.min.js"></script> 
      <script type="text/javascript">
    window.onload=function(){/*from   w w w .  j ava  2  s. co  m*/
var ctx = document.getElementById("myChart");
function getColorArray(data, threshold, colorLow, colorHigh) {
   var colors = [];
   for(var i = 0; i < data.length; i++) {
     if(data[i] > threshold) {
       colors.push(colorHigh);
    } else {
       colors.push(colorLow);
    }
  }
  return colors;
}
var data = [12, 19, 3, 5, 2, 3];
var backgroundColors = getColorArray(data, 6, 'rgba(217, 97, 97, 0.75)', 'rgba(185, 214, 200, 0.75)');
var myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: '# of Votes',
      data: data,
      backgroundColor: backgroundColors
    }]
  },
  options: {
    scales: {
       xAxes: [{
         gridLines: {
           display: false
        }
      }],
      yAxes: [{
        ticks: {
           beginAtZero:true
        }
      }]
    }
  }
});
    }

      </script> 
   </head> 
   <body> 
      <canvas id="myChart" width="400" height="200"></canvas>  
   </body>
</html>

Related Tutorials