Johans
Johans

Reputation: 5

Chart JS - Change the color of the last element in a Bar Chart

So far I am able to make it work by hard coding the last element but I would like to automatically have it colored no matter what data is passed in the chart. I tried with (index.length - 1 ) but it doesn't work.

labels: ["Red", "Blue", "Yellow", "Red", "Blue"],
datasets: [{
    data: [22, 19, 23, 84, 22],
    backgroundColor: function(context) {
      var index = context.dataIndex;
      var value = context.dataset.data[index];
      console.log(value);
      return value === context.dataset.data[4] && index === 4 ?
        "red" :
        "blue";
    }
  }]
}

Upvotes: 0

Views: 868

Answers (1)

Maihan Nijat
Maihan Nijat

Reputation: 9355

Use a callback on the backgroundColor:

backgroundColor: this.data.map((item, index) => {
  if (index === this.data.length - 1) {
    return 'red';
  } else return 'blue'
})

Or using ternary operator:

backgroundColor: this.data.map((item, index) => {
  return index === this.data.length - 1 ? 'red' : 'blue'
}),

this.data is the data used for creating the chart.

Full solution:

data = [22, 19, 23, 84, 22];
labels: ["Red", "Blue", "Yellow", "Red", "Blue"],
  datasets: [{
    data: this.data,
    backgroundColor: this.data.map((item, index) => {
      return index === this.data.length - 1 ? 'red' : 'blue'
    }),
  }]
}

Upvotes: 3

Related Questions