原则上你是正确的:你需要将之前的条形高度相加才能获得bottom
下一个酒吧的。
问题是你不能简单地添加元组。所以一个好主意是让它们numpy
数组,menMeans = np.array(menMeans)
.
Those numpy
数组可以很容易地相加在一起,这样
p3 = plt.bar(ind, childrenMeans, width, bottom=menMeans+womenMeans)
效果很好。
完整代码:
import numpy as np
import matplotlib.pyplot as plt
menMeans = np.array((20, 35, 30, 35, 27))
womenMeans = np.array((25, 32, 34, 20, 25))
childrenMeans = np.array((21, 30, 32, 10, 36))
ind = np.arange(5)
width = 0.35
p1 = plt.bar(ind, menMeans, width, color='#d62728', )
p2 = plt.bar(ind, womenMeans, width, bottom=menMeans)
p3 = plt.bar(ind, childrenMeans, width, bottom=menMeans+womenMeans)
plt.ylabel('Scores')
plt.title('Scores by group and gender')
plt.xticks(ind, ('G1', 'G2', 'G3', 'G4', 'G5'))
plt.yticks(np.arange(0, 81, 10))
plt.legend((p1[0], p2[0], p3[0]), ('Men', 'Women', "Children"))
plt.show()