Issue
I have positive and negative values and I want to plot it as a bar chart. I want to plot the classic "green" positive colors and "red" negative values. I have this code currently:
import numpy as np
import matplotlib.pyplot as plt
x = [1,2,3,4,5,6]
y2 = [10000,11682,20842,12879,4576,7845]
y1 = [-1456,-10120,-2118,10003,-2004,1644]
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax2.plot(x, y2, color='k')
ax2.set_ylabel('Y2 data', color='k')
ax1.bar(x, y1, color='g')
plt.show()
Solution
add this line before ploting bar:
color = ['r' if y<0 else 'g' for y in y1]
finally code:
import numpy as np
import matplotlib.pyplot as plt
x = [1,2,3,4,5,6]
y2 = [10000,11682,20842,12879,4576,7845]
y1 = [-1456,-10120,-2118,10003,-2004,1644]
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax2.plot(x, y2, color='k')
ax2.set_ylabel('Y2 data', color='k')
color = ['r' if y<0 else 'g' for y in y1]
ax1.bar(x, y1, color=color)
plt.show()
Output:
If you convert y1
array to numpy.array
, you can use np.where
like below (output from this code is same as output from first code):
y1 = np.array([-1456,-10120,-2118,10003,-2004,1644])
...
ax1.bar(x, y1, color=np.where(y1 < 0, 'r', 'g'))
Answered By - user1740577
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.