2

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

ABCDEF matplotlib graph

2 Answers 2

4

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')
Sign up to request clarification or add additional context in comments.

Comments

1

Just color a second plot differently:

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


plt.barh(pos[Effort >= 0], Effort[Effort >= 0], color='blue', edgecolor='black') # positive values in blue
plt.barh(pos[Effort < 0], Effort[Effort < 0], color='red', edgecolor='black') # negative values in red
plt.yticks(pos, city)
plt.xlabel('DV', fontsize=16)
plt.ylabel('Groups', fontsize=16)
plt.title('ABCDEF', fontsize=20)
plt.show()

This results in:

enter image description here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.