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

Kie*_*unt 2 python plot matplotlib histogram

我希望在 matplotlib 中绘制两个并排堆叠的直方图(类似于下面的示例图像)。我尝试过几种变体

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

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

并排堆叠直方图示例

sna*_*mer 5

该图显示的是条形图而不是直方图。我指出这一点,不仅因为我是一个令人讨厌的学究,而且因为我相信它可以帮助您找到正确的工具:-)
事实上,对于您的目的来说,plt.bar可能是比plt.hist.

根据 Scironic 的建议,我修改了这个演示示例以制作堆叠条,就像您图中的那样。

向位置索引(中的第一个参数plt.bar())添加偏移量可以防止条形图彼此重叠。

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

在此输入图像描述