import matplotlib.pyplot as plt
# 下面柱子标值
def autolabel(ax, rects):
"""Attach a text label above each bar in *rects*, displaying its height."""
for rect in rects:
height = rect.get_height()
ax.annotate('{}'.format(height),
xy=(rect.get_x() + rect.get_width() / 2, height/2),
xytext=(0, 3), # 3 points vertical offset
textcoords="offset points",
ha='center', va='bottom')
# 上面柱子标值
def autolabel_up(ax, rects, bottom_rects):
"""Attach a text label above each bar in *rects*, displaying its height."""
for i in range(len(rects)):
height = rects[i].get_height()/2+bottom_rects[i].get_height()
ax.annotate('{}'.format(rects[i].get_height()),
xy=(rects[i].get_x() + rects[i].get_width() / 2, height),
xytext=(0, 3), # 3 points vertical offset
textcoords="offset points",
ha='center', va='bottom')
labels = ['G1', 'G2', 'G3', 'G4', 'G5']
men_means = [20, 35, 30, 35, 27]
women_means = [25, 32, 34, 20, 25]
men_std = [2, 3, 4, 1, 2]
women_std = [3, 5, 2, 3, 3]
width = 0.35 # the width of the bars: can also be len(x) sequence
fig, ax = plt.subplots()
rect1 = ax.bar(labels, men_means, width, label='Men')
rect2 = ax.bar(labels, women_means, width, bottom=men_means, label='Women')
autolabel(ax, rect1)
autolabel_up(ax, rect2, rect1)
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.legend()
plt.show()
结果图: