Different color for each bar in a bar chart; ChartJS

BoooYaKa picture BoooYaKa · Aug 31, 2014 · Viewed 186.9k times · Source

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?

Answer

thanksd picture thanksd · Jun 15, 2017

As of v2, you can simply specify an array of values to correspond to a color for each bar via the backgroundColor property:

datasets: [{
  label: "My First dataset",
  data: [20, 59, 80, 81, 56, 55, 40],
  backgroundColor: ["red", "blue", "green", "blue", "red", "blue"], 
}],

This is also possible for the borderColor, hoverBackgroundColor, hoverBorderColor.

From the documentation on the Bar Chart Dataset Properties:

Some properties can be specified as an array. If these are set to an array value, the first value applies to the first bar, the second value to the second bar, and so on.