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:
JavaScript
x
12
12
1
var barChartData = {
2
labels: ["001", "002", "003", "004", "005", "006", "007"],
3
datasets: [{
4
label: "My First dataset",
5
fillColor: "rgba(220,220,220,0.5)",
6
strokeColor: "rgba(220,220,220,0.8)",
7
highlightFill: "rgba(220,220,220,0.75)",
8
highlightStroke: "rgba(220,220,220,1)",
9
data: [20, 59, 80, 81, 56, 55, 40]
10
}]
11
};
12
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:
JavaScript
1
9
1
function getRandomColor() {
2
var letters = '0123456789ABCDEF'.split('');
3
var color = '#';
4
for (var i = 0; i < 6; i++ ) {
5
color += letters[Math.floor(Math.random() * 16)];
6
}
7
return color;
8
}
9
I’ve added it to the end of the file and i called this function right inside the “fillColor:” under
JavaScript
1
3
1
helpers.each(dataset.data,function(dataPoint,index){
2
//Add a new point for each piece of data, passing any required data to draw.
3
so now it looks like this:
JavaScript
1
14
14
1
helpers.each(dataset.data,function(dataPoint,index){
2
//Add a new point for each piece of data, passing any required data to draw.
3
4
datasetObject.bars.push(new this.BarClass({
5
value : dataPoint,
6
label : data.labels[index],
7
datasetLabel: dataset.label,
8
strokeColor : dataset.strokeColor,
9
fillColor : getRandomColor(),
10
highlightFill : dataset.highlightFill || dataset.fillColor,
11
highlightStroke : dataset.highlightStroke || dataset.strokeColor
12
}));
13
},this);
14
and it works I get different color for each bar.