Home > Software engineering >  Color Negative Values on Matplotlib Bar Plots Differently
Color Negative Values on Matplotlib Bar Plots Differently

Time:09-23

I am trying to color the bar plots of the negative values differently. Any pointer to accomplish this is much appreciated. Thanks.

import matplotlib.pyplot as plt
import numpy as np


city=['a','b','c','d']
pos = np.arange(len(city))
Effort =[4, 3, -1.5, -3.5]


plt.barh(pos,Effort,color='blue',edgecolor='black')
plt.yticks(pos, city)
plt.xlabel('DV', fontsize=16)
plt.ylabel('Groups', fontsize=16)
plt.title('ABCDEF',fontsize=20)
plt.show()

enter image description here

CodePudding user response:

This will colour the positive bars as green and the negative as red.

import matplotlib.pyplot as plt
import numpy as np


city=['a','b','c','d']
pos = np.arange(len(city))
Effort =[4, 3, -1.5, -3.5]

colors = ['g' if e >= 0 else 'r' for e in Effort]

plt.barh(pos,Effort,color=colors,edgecolor='black')
plt.yticks(pos, city)
plt.xlabel('DV', fontsize=16)
plt.ylabel('Groups', fontsize=16)
plt.title('ABCDEF',fontsize=20)
plt.show()

enter image description here

If Effort was a numpy array we could use np.where to get the colours rather than a list comprehension.

Effort = np.array([4, 3, -1.5, -3.5])

colors = np.where(Effort >= 0, 'g', 'r')
  • Related