[Chartjs]-Chart.js changing the color of the max value bar

2๐Ÿ‘

โœ…

I think the easiest way to do it is by defining backgroundColor for each bars. Then you can find the max index and change the color. Here is a simplified example:

function argMax(array) {
  return array.map((x, i) => [x, i]).reduce((r, a) => (a[0] > r[0] ? a : r))[1];
}

// dummy data
var data = [12, 19, 1, 14, 3, 10, 9];
var labels = data.map((x, i) => i.toString()); 

// other data color
var color = data.map(x => 'rgba(75,192,192,0.4)');

// change max color
color[argMax(data)] = 'red';

var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: labels,
            datasets: [{
                    label: 'value',
                    data: data,
                    backgroundColor: color,
            }]
        }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.0.0-beta/Chart.js"></script>

<canvas id="myChart" width="600" height="300"></canvas>

0๐Ÿ‘

backgroundColor: "rgba(75,192,192,0.4)"

instead of giving it a single color, you can add an array:

backgroundColor:["rgba(255, 99, 132, 0.2)","rgba(255, 159, 64, 0.2)","rgba(255, 205, 86, 0.2)"]

Example:

new Chart(document.getElementById("chartjs-1"), {
  "type": "bar",
  "data": {
    "labels": ["First", "Second", "Third", "Fourth"],
    "datasets": [{
      "label": "Example Dataset",
      "data": [65, 59, 80, 31],
      "fill": false,
      "backgroundColor": ["rgba(255, 99, 132, 0.2)", "rgba(255, 159, 64, 0.2)", "rgba(255, 99, 132, 0.2)", "rgba(255, 99, 132, 0.2)"],
      "borderColor": ["rgb(255, 99, 132)", "rgb(255, 159, 64)", "rgb(255, 99, 132)", "rgb(255, 99, 132)"],
      "borderWidth": 1
    }]
  },
  "options": {
    "scales": {
      "yAxes": [{
        "ticks": {
          "beginAtZero": true
        }
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
<canvas id="chartjs-1" class="chartjs">https://stackoverflow.com/posts/51843404/edit#

In the documentation [] denotes which properties accept also arrays (backgroundColor โ€“ Color/Color[])

Leave a comment