Skip to content
Advertisement

Different color for each bar in a bar chart; ChartJS

I’m using ChartJS in a project I’m working on and I need a different color for each bar in a Bar Chart.

Here’s an example of the bar chart data set:

    var barChartData = {
      labels: ["001", "002", "003", "004", "005", "006", "007"],
      datasets: [{
        label: "My First dataset",
        fillColor: "rgba(220,220,220,0.5)", 
        strokeColor: "rgba(220,220,220,0.8)", 
        highlightFill: "rgba(220,220,220,0.75)",
        highlightStroke: "rgba(220,220,220,1)",
        data: [20, 59, 80, 81, 56, 55, 40]
      }]
    };

Is there any way to paint each bar differently?

Advertisement

Answer

After looking into the Chart.Bar.js file I’ve managed to find the solution. I’ve used this function to generate a random color:

function getRandomColor() {
    var letters = '0123456789ABCDEF'.split('');
    var color = '#';
    for (var i = 0; i < 6; i++ ) {
        color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
}

I’ve added it to the end of the file and i called this function right inside the “fillColor:” under

helpers.each(dataset.data,function(dataPoint,index){
                    //Add a new point for each piece of data, passing any required data to draw.

so now it looks like this:

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 : getRandomColor(),
                        highlightFill : dataset.highlightFill || dataset.fillColor,
                        highlightStroke : dataset.highlightStroke || dataset.strokeColor
                    }));
                },this);

and it works I get different color for each bar.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement