Change bar color depending on value for chartjs - Javascript Chart.js

Javascript examples for Chart.js:Bar Chart

Description

Change bar color depending on value for chartjs

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <title>Change Chart.js bar color based on value</title> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript" src="https://code.jquery.com/jquery-git.js"></script> 
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script> 
      <script type="text/javascript">
    $(window).on('load', function() {
var chartColors = {//from   w  ww . j a v a2 s  . c  om
  red: 'rgb(255, 99, 132)',
  blue: 'rgb(54, 162, 235)'
};
var ctx = document.getElementById("myChart").getContext("2d");
var myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ['value 1', 'value 2', 'value 3', 'value 4'],
    datasets: [{
      label: 'Dataset 1',
      backgroundColor: [
        chartColors.blue,
        chartColors.blue,
        chartColors.blue,
        chartColors.blue
      ],
      data: [33, 57, 65, 42]
    }],
  }
});
var colorChangeValue = 50;
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();
    });

      </script> 
   </head> 
   <body> 
      <canvas id="myChart" height="150"></canvas>  
   </body>
</html>

Related Tutorials