Matplotlib Change The Bar Color If A Condition Is Met
I am trying to build a Figure with 2 subplots. If the Item is in ax and ax1 the color of the bar is blue. If the item is in ax and not in ax1 the bar color should be green. If th
Solution 1:
You can change the color of the Rectangle
patches that barh
creates after its been plotted based on your conditions.
I modified your code a little to remove some of the unnecessary parts and make it run. I hope its clear below what its doing. You can use ax.patch[i].set_color('r')
to change the color of patch i
to red, for example.
import matplotlib.pyplot as plt
from collections import OrderedDict
fig,(ax1,ax2) = plt.subplots(1,2)
Testdic1 =OrderedDict([('Exploit', 14664), ('Botnet', 123), ('Virus', 52)])
Testdic2 =OrderedDict([('Botnet', 1252), ('Virus', 600), ('XSS', 452)])
list1 = list(Testdic1.items())
list2 = list(Testdic2.items())
n1 = len(list1)
n2 = len(list2)
values1 = [v for l,v in list1]
values2 = [v for l,v in list2]
ax1.barh(range(n1),values1,align='center', fc='#80d0f1', ec='w')
ax2.barh(range(n2),values2,align='center', fc='#80d0f1', ec='w')
# ====================================# Here's where we change colors# ====================================for i,(label,val) inenumerate(list1):
if label.title() in Testdic2:
pass# leave it blueelse:
ax1.patches[i].set_color('g')
for i,(label,val) inenumerate(list2):
if label.title() in Testdic1:
pass# leave it blueelse:
ax2.patches[i].set_color('r')
# ====================================
ax1.set_yticks(range(n1))
ax2.set_yticks(range(n2))
for i, (label, val) inenumerate(list1):
ax1.annotate(label.title(), xy=(10, i), fontsize=10, va='center')
for i, (label, val) inenumerate(list2):
ax2.annotate(label.title(), xy=(10, i), fontsize=10, va='center')
ax1.invert_yaxis()
ax2.invert_yaxis()
plt.show()
Post a Comment for "Matplotlib Change The Bar Color If A Condition Is Met"