Sometimes, we want to set different color for each bar in a bar chart with Chart.js and JavaScript.
In this article, we’ll look at how to set different color for each bar in a bar chart with Chart.js and JavaScript.
How to set different color for each bar in a bar chart with Chart.js and JavaScript?
To set different color for each bar in a bar chart with Chart.js and JavaScript, we can set the fillColor
of each entry in the datasets
array.
For instance, we write
const barChartData = {
labels: ["January", "February", "March"],
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],
},
],
};
window.onload = () => {
const ctx = document.getElementById("mycanvas").getContext("2d");
window.myObjBar = new Chart(ctx).Bar(barChartData, {
responsive: true,
});
myObjBar.datasets[0].bars[0].fillColor = "green";
myObjBar.datasets[0].bars[1].fillColor = "orange";
myObjBar.datasets[0].bars[2].fillColor = "red";
myObjBar.update();
};
To add the datasets
object property into barChartData
.
Then we use that to create the Bar
chart.
Next, we set the bar colors with
myObjBar.datasets[0].bars[0].fillColor = "green";
myObjBar.datasets[0].bars[1].fillColor = "orange";
myObjBar.datasets[0].bars[2].fillColor = "red";
Finally, we call update
to update the chart.
Conclusion
To set different color for each bar in a bar chart with Chart.js and JavaScript, we can set the fillColor
of each entry in the datasets
array.