[Chartjs]-Chart Js – Globally set bar chart color based on value

2👍

Given an array named “win” that contains boolean values, you could create the “myBorderColors” array as follows using Array.map.

var myBorderColors = win.map(b => b ? "rgba(0, 177, 106, 1)" : "rgba(207, 0, 15, 1)");

And then use the following assignment to Chart.defaults.

Chart.defaults.global.datasets.bar.borderColor = myBorderColors;

Please have a look at the runnable code snippet below.

var win = [true, false, false, true];
var myBorderColors = win.map(b => b ? "rgba(0, 177, 106, 1)" : "rgba(207, 0, 15, 1)");

Chart.defaults.global.datasets.bar.borderColor = myBorderColors;

new Chart(document.getElementById('myChart'), {
  type: 'bar',
  data: {
    labels: ['A', 'B', 'C', 'D'],
    datasets: [{
      label: "My Dataset",
      data: [3, 5, 4, 2],
      borderWidth: 3
    }]
  },
  options: {
    legend: {
      display: false
    },
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});
canvas {
  max-width: 300px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChart" height="200"></canvas>

Leave a comment