[Chartjs]-Can the colors of bars in a bar chart be varied based on their value?

3πŸ‘

βœ…

As far as I know there is no configuration or callback for each individual point being drawn. The best way I can think of to do this would be to create a function that would modify your chart config/data object. This isn’t the most elegant way to deal with the problem, but it would work.

The Fix

Pass your chart config/data object to a function that will add the background color.

Main Point of the example is function AddBackgroundColors(chartConfig)

Example:

function AddBackgroundColors(chartConfig) {
  var min = 1; // Min value
  var max = 100; // Max value
  var datasets;
  var dataset;
  var value;
  var range = (max - min);
  var percentage;
  var backgroundColor;

  // Make sure the data exists
  if (chartConfig &&
    chartConfig.data &&
    chartConfig.data.datasets) {
    // Loop through all the datasets
    datasets = chartConfig.data.datasets;
    for (var i = 0; i < datasets.length; i++) {
      // Get the values percentage for the value range
      dataset = datasets[i];
      value = dataset.data[0];
      percentage = value / range * 100;

      // Change the background color for this dataset based on its percentage
      if (percentage > 100) {
        // > 100%
        backgroundColor = '#0000ff';
      } else if (percentage >= 50) {
        // 50% - 100%
        backgroundColor = '#00ff00';
      } else {
        // < 50%
        backgroundColor = '#ff0000';
      }
      dataset.backgroundColor = backgroundColor;
    }
  }

  // Return the chart config object with the new background colors
  return chartConfig;
}

var chartConfig = {
  type: 'bar',
  data: {
    labels: ["percentage"],
    datasets: [{
      label: '100%',
      data: [100]
    }, {
      label: '50%',
      data: [50]
    }, {
      label: '49%',
      data: [49]
    }, {
      label: '5%',
      data: [5]
    }]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
};

window.onload = function() {
  var ctx = document.getElementById("canvas").getContext("2d");
  chartConfig = AddBackgroundColors(chartConfig);
  var myChart = new Chart(ctx, chartConfig);
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.2/Chart.bundle.min.js"></script>
<canvas id="canvas" width="400" height="200"></canvas>

0πŸ‘

In Chart.js 2 it is possible to set multiple colors with an array.

So you can define the backgroundColor as an array of color strings, matching the datasets data.

var myChart = new Chart(ctx, {
  datasets: [{
    label: 'Votes',
    data: [1, 2, 3],
    // Make the first bar red, the second one green and the last one blue
    backgroundColor: ['#f00', '#0f0', '#00f']
  }]
});

You can easily generate an array based on the values in data:

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;
}

See this fiddle for a working demo

Leave a comment