Tuesday, June 28, 2022

[FIXED] How to change bar color based on number value in matplotlib

Issue

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()

Solution

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.



Answered By - EthMM
Answer Checked By - Marie Seifert (PHPFixing Admin)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.