多分类累积柱状图Stacked Bar(bottom参数解释)——matplotlib实现

plt.bar的参数bottom应该传什么值呢?

matplotlib的Stacked Bar官网的example链接为:

https://matplotlib.org/gallery/lines_bars_and_markers/bar_stacked.html#sphx-glr-gallery-lines-bars-and-markers-bar-stacked-py

官档并没有对bottom这个参数做过多的解释。亲自实验后得出结论:bottom需要传入的是[第0个类别~(当前类别-1)]的数据总和

多分类累积柱状图Stacked Bar(bottom参数解释)——matplotlib实现

当我们想加入第三个分类的时候unknown,应该怎么写呢?

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

那么p3是否应该是上一个数据集womenMeans呢?如下:

p3 = plt.bar(ind, unknownMeans, width,
             bottom=womenMeans, yerr=unknownStd)
效果如下图。会发现堆叠的位置错误。


再次强调:bottom的值应该是[第0个类别~(当前类别-1)]的数据总和
p3的代码做以下修改就能得到正确的结果:
cum =list(map(sum, zip(list(menMeans),list(womenMeans))))
p3 = plt.bar(ind, unknownMeans, width,bottom=cum, yerr=unknownStd)
修改后的图为: