Issue
I would like to add stars to certain variables in a matplotlib.pyplot bar plot.
import numpy as np
import matplotlib.pyplot as plt
N = 5
menMeans = (20, 35, 30, 35, 27)
womenMeans = (25, 32, 34, 20, 25)
ind = np.arange(N) # the x locations for the groups
width = 0.35
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
ax.bar(ind, menMeans, width, color='r')
ax.bar(ind, womenMeans, width,bottom=menMeans, color='b')
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.set_xticks(ind, ('G1', 'G2', 'G3', 'G4', 'G5'))
ax.set_yticks(np.arange(0, 81, 10))
ax.legend(labels=['Men', 'Women'])
plt.show()
Supose I wanted to add stars *** to the top of the bars at G1 and G3. How could I do this?
Solution
You could do it by placing the ***
with matplotlib.axes.Axes.text
. First calculate, the bar heights by summing both meanMeans
and womenMeans
, then pass the bar as x
and the height as y
.
# Add *** to G1 and G3
bar_heights = [mm + wm for mm, wm in zip(menMeans, womenMeans)]
ax.text(x=0, y=bar_heights[0]+1, s="***", ha='center', va='center', fontsize=15)
ax.text(x=2, y=bar_heights[2]+1, s="***", ha='center', va='center', fontsize=15)
plt.show()
Answered By - viggnah
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.