Home > database >  How to change bar color based on number value in matplotlib
How to change bar color based on number value in matplotlib

Time:01-07

I have a horizontal bar chart where I'm supposed to turn the bars slowly from yellow to red based on the horizontal value. So the greater the X value the more the bars chart get red

(I wanted to show the plot but I couldn't upload the image of it due to my low reputation)

import matplotlib.pyplot as plt 

x = [3,3,4]
y = [1,2,5]
plt.barh(x,y)
plt.show()

CodePudding user response:

I'd do something of similar, hand-made:

colorsValue = []
for value in x:
    if value < LOW_TRESHOLD:
        colorsValue.append('yellow')
    elif value >= HIGH_TRESHOLD:
        colorsValue.append('red')
    else:
        colorsValue.append('orange')

plt.barh(x, y, color = colorsValue)

where LOW_TRESHOLD and HIGH_TRESHOLD are values decided by you, as well as colors. List of matplotlib colors is here.

This was only a minimal example to show you the syntax. Solution of Kroshtan is good as well and more general than my home-made solution, so I advice you to use his one.

CodePudding user response:

You can pass an array in the color parameter. The values of this array can be calculated using cmap from the matplotlib documentation.

colors = [(1, 1, 0), (1, 0, 0)]
my_cmap = LinearSegmentedColormap.from_list(
    'color_map', colors, N=100)

Then you scale the colors to the values you have:

rescale = lambda y: (y - np.min(y)) / (np.max(y) - np.min(y))    
plt.barh(x,y,color=my_cmap(rescale(y)))
plt.show()
  •  Tags:  
  • Related