[Chartjs]-Different color for each column in angular-chartjs bar chart

5👍

As you want to give different color for each bar in graph, you are passing those value in array. But the thing is chart.js doesn’t support such type of feature.

Reason

The color which we are able to see in bar area is nothing but fillColor option, If you look at the source code of chart.js Line

Code

helpers.each(dataset.data, function(dataPoint, index) {
    //Add a new point for each piece of data, passing any required data to draw.
    datasetObject.bars.push(new this.BarClass({
        value: dataPoint,
        label: data.labels[index],
        datasetLabel: dataset.label,
        strokeColor: dataset.strokeColor,
        fillColor: dataset.fillColor, //<--This line responsible for filling color
        highlightFill: dataset.highlightFill || dataset.fillColor,
        highlightStroke: dataset.highlightStroke || dataset.strokeColor
    }));
}, this);

Above code clearly says that fillColor required string. In anyway the you can pass only one color in that string. And only one color will get applied to bar series. If we want to make you requirement workable then we need to make changes in chart.js.

Changes to be made in chart.js

We need to make change in this line from fillColor: dataset.fillColor, to fillColor: dataset.fillColor[index], so that we can pass color array which needs to be applied on each bar of chart. index variable of .each will ensure the color would be applied on Bar in order way which we had given in array. Our color would be changed to $scope.medals_colours = [{fillColor:['#087D76', '#B3BC3A', '#38B665', '#8B4A9D']}];.

Changed code

helpers.each(dataset.data, function(dataPoint, index) {
    //Add a new point for each piece of data, passing any required data to draw.
    datasetObject.bars.push(new this.BarClass({
        value: dataPoint,
        label: data.labels[index],
        datasetLabel: dataset.label,
        strokeColor: dataset.strokeColor,
        fillColor: dataset.fillColor[index] || dataset.fillColor, //<--getting color using index
        highlightFill: dataset.highlightFill || dataset.fillColor,
        highlightStroke: dataset.highlightStroke || dataset.strokeColor
    }));
}, this);

Markup

  <div class="graph-display" ng-controller="jsonServerBox">
    <canvas id="bar" class="chart chart-bar" data="medal_data" labels="medal_ticks" 
    colours="medals_colours"></canvas>
  </div>

Controller

  app.controller('jsonServerBox', function($scope) {

    $scope.medal_ticks = ['Gold', 'Silver', 'Bronze', 'Not passed'];
    $scope.series = ['Medaljer'];
    $scope.medals_colours = [{fillColor:['#087D76', '#B3BC3A', '#38B665', '#8B4A9D']}];

    $scope.medal_data = [['1', '5', '2', '0']];
  });

I know it does look hacky but we have to make it.

Kudos goes to @tpie this answer

Demo Plunkr

Leave a comment