matplotlib 中的第三个堆叠条

Mar*_*urg 6 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()
Run Code Online (Sandbox Code Playgroud)

假设我有第三个系列并且我希望将其堆叠在顶部。如何表达一个

bottom
Run Code Online (Sandbox Code Playgroud)

范围?我试着简单地做

menMeans + womenMeans
Run Code Online (Sandbox Code Playgroud)

但这没有用。

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

Imp*_*est 8

原则上你是正确的:你需要将前一个柱的高度相加才能获得bottom下一个柱的高度。

问题是你不能简单地添加元组。所以一个好主意是将它们制作为numpy数组menMeans = np.array(menMeans)。
这些numpy数组可以很容易地添加在一起,这样

p3 = plt.bar(ind, childrenMeans, width, bottom=menMeans+womenMeans) 
Run Code Online (Sandbox Code Playgroud)

效果很好。

完整代码:

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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述