Reputation: 63
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
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;
}
};
Upvotes: 6