Masooma Ahmad
Masooma Ahmad

Reputation: 63

applying background-color in bar chart using chart.js

var myChart = new Chart(ctx, {
type: 'horizontalBar',
data: {
    labels:cmpny_timing,
    datasets: [{
        label: 'Hourly Attendance',
        data: d,
        backgroundColor: [
            'rgba(255, 99, 132, 0.2)',
            'rgba(54, 162, 235, 0.2)',
            'rgba(255, 206, 86, 0.2)',
            'rgba(75, 192, 192, 0.2)',
            'rgba(153, 102, 255, 0.2)'
        ],
        borderColor: [
            'rgba(255,99,132,1)',
            'rgba(54, 162, 235, 1)',
            'rgba(255, 206, 86, 1)',
            'rgba(75, 192, 192, 1)',
            'rgba(153, 102, 255, 1)
          ],
        borderWidth: 1
    }]
},

is there anyway i can change the color of each bar according to the data....i want to make background colors according to the data in my data i have an array of length 15 so is there anyway i can create 15 colors bars dynamically rather than hardcoding the background color property of chart.js

Upvotes: 3

Views: 14846

Answers (1)

tektiv
tektiv

Reputation: 14187

Using Chart.js plugins, you can create your own backgroundColor & borderColor properties and then assign them to the chart :

var randomColorPlugin = {

    // We affect the `beforeUpdate` event
    beforeUpdate: function(chart) {
        var backgroundColor = [];
        var borderColor = [];

        // For every data we have ...
        for (var i = 0; i < chart.config.data.datasets[0].data.length; i++) {

            // We generate a random color
            var color = "rgba(" + Math.floor(Math.random() * 255) + "," + Math.floor(Math.random() * 255) + "," + Math.floor(Math.random() * 255) + ",";

            // We push this new color to both background and border color arrays
            // .. a lighter color is used for the background
            backgroundColor.push(color + "0.2)");
            borderColor.push(color + "1)");
        }

        // We update the chart bars color properties
        chart.config.data.datasets[0].backgroundColor = backgroundColor;
        chart.config.data.datasets[0].borderColor = borderColor;
    }
};


You can see a working example on this jsFiddle. Every time you run the code, you'll get different colors.
Here is one of the result :

enter image description here

Upvotes: 6

Related Questions