matplotlib中的第三个堆叠条

时间:2017-04-20 21:47:19

标签: python matplotlib

考虑来自matplotlib网站的这个示例代码:

# a stacked bar plot with errorbars
import numpy as np
import matplotlib.pyplot as plt


N = 5
menMeans = (20, 35, 30, 35, 27)
womenMeans = (25, 32, 34, 20, 25)
menStd = (2, 3, 4, 1, 2)
womenStd = (3, 5, 2, 3, 3)
ind = np.arange(N)    # the x locations for the groups
width = 0.35       # the width of the bars: can also be len(x) sequence

p1 = plt.bar(ind, menMeans, width, color='#d62728', yerr=menStd)
p2 = plt.bar(ind, womenMeans, width,
         bottom=menMeans, yerr=womenStd)

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]), ('Men', 'Women'))

plt.show()

假设我有第三个系列,我希望它叠在上面。如何表达

bottom

参数?我试着简单地做

menMeans + womenMeans

但这不起作用。

来源:https://matplotlib.org/2.0.0/examples/pylab_examples/bar_stacked.html

1 个答案:

答案 0 :(得分:1)

原则上你是对的:你需要加上以前的栏高,以获得下一个栏的bottom

问题是你不能简单地添加元组。因此,一个好主意是制作numpy数组,menMeans = np.array(menMeans) 可以轻松地将这些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()

enter image description here