Black Lives Matter. Please consider donating to Black Girls Code today.

Customizing individual bar colors

I’m completely new to Plotly.js (and relatively new to JavaScript) and was looking at the sample code in the website to customize the colors of the individual bars.

As per the code in the sample, we pass in the color for each data point. The following is the code that is given in the web-page.

var trace1 = {
  x: ['Feature A', 'Feature B', 'Feature C', 'Feature D', 'Feature E'],
  y: [20, 14, 23, 25, 22],
  marker:{
    color: ['rgba(204,204,204,1)', 'rgba(222,45,38,0.8)', 'rgba(204,204,204,1)', 'rgba(204,204,204,1)', 'rgba(204,204,204,1)']
  },
  type: 'bar'
};

I wanted to know if there is any way for me to achieve this based on the value of the data point. For e.g.say I want to highlight the bars which have a value less than 15 with a red color. Is there an easy way to achieve this in Plotly.js.

Thanks in advance!

No. You can try something like:

var trace1 = {
  x: ['Feature A', 'Feature B', 'Feature C', 'Feature D', 'Feature E'],
  y: [20, 14, 23, 25, 22],
  marker: {},
  type: 'bar'
};

trace.marker.color = trace.y.map(function (v) {
  return v < 15 ? 'red' : 'blue'
});

to make this easier.