[Chartjs]-Chart.js bar chart change color based on value

7👍

Given an array of number values named “data”, you create a sorted array out of it. Then you map the values of the original data, returning the appropriate color depending on its position in the sorted array.

const backgroundColors = data.map(v => sortedData.indexOf(v) >= data.length - 3 ? 'red' : 'green');

Please have a look at the runnable code sample below.

const labels = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'K', 'L', 'M', 'N', 'O'];
const data = labels.map(l => Math.floor(Math.random() * 1000) + 1);
const sortedData = data.slice().sort((a, b) => a - b);
const backgroundColors = data.map(v => sortedData.indexOf(v) >= data.length - 3 ? 'red' : 'green');

new Chart(document.getElementById('myChart'), {
  type: 'bar',
  data: {
    labels: labels,
    datasets: [{
      label: "My Dataset",
      data: data,
      backgroundColor: backgroundColors
    }]
  },
  options: {
    legend: {
      display: false
    },
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChart" height="90"></canvas>

Leave a comment