如何在matplotlib中并排绘制堆叠的直方图?

问题描述:

我正在寻找在matplotlib中绘制两个并排堆积的直方图(类似于下面的示例图像). 我在

I'm looking to plot two side-by-side stacked histograms (similar to the example image below) in matplotlib. I've tried several variations on

bins = np.arange(10)
a1,b1,c1 =plt.hist([arr1,arr2,arr3],bins,stacked=True)
a2,b2,c2 =plt.hist([arr4,arr5,arr6],bins,stacked=True)

但是似乎无法避免让第二个图直接覆盖第一个图. 关于如何解决这个问题有什么想法吗?

But can't seem to avoid getting the second plot to directly overlay the first. Any ideas on how this could be resolved?

图片显示了条形图,而不是直方图.我指出这一点,不仅是因为我是一个讨厌的学徒,而且还因为我相信它可以帮助您找到合适的工具:-)
实际上,出于您的目的,plt.bar可能比plt.hist更好.

The picture shows a bar chart and not a histogram. I am pointing this out, not only because I am an obnoxious pedant, but also because I believe it could help you find the right tool :-)
Indeed, for your purpose plt.bar is probably a better pick than plt.hist.

根据Scironic的建议,我修改了演示示例以制作堆叠的条形,就像你的身材上的人一样.

Based on Scironic's suggestion, I modified this demonstration example to make stacked bars, like the ones on your figure.

为位置索引(plt.bar()中的第一个参数)添加偏移量是防止条形图相互重叠的原因.

Adding an offset to the position index (first argument in plt.bar()) is what prevents the bars from overlapping each other.

import numpy as np
import matplotlib.pyplot as plt

N = 5
men1 = (130, 90, 70, 64, 55)
men2 = (120, 85, 62, 50, 53)
men3 = (100, 70, 60, 45, 50)

ind = np.arange(N) + .15 # the x locations for the groups
width = 0.35       # the width of the bars

fig, ax = plt.subplots()
rects1 = ax.bar(ind, men1, width, color='g') 
rects2 = ax.bar(ind, men2, width, color='r') 
rects3 = ax.bar(ind, men3, width, color='b')

women4 = (140, 90, 78, 65, 50)
women5 = (130, 80, 70, 60, 45)
women6 = (120, 60, 60, 55, 44)

xtra_space = 0.05
rects2 = ax.bar(ind + width + xtra_space , women1, width, color='orange') 
rects2 = ax.bar(ind + width + xtra_space, women2, width, color='cyan') 
rects2 = ax.bar(ind + width + xtra_space, women3, width, color='purple')

# add some text for labels, title and axes ticks
ax.set_ylabel('Population, millions')
ax.set_title('Population: Age Structure')

ax.set_xticks(ind+width+xtra_space)
ax.set_xticklabels( ('USA', 'Brazil', 'Russia', 'Japan', 'Mexico') )

plt.show()