在 python 中无法使用 matplotlib 堆叠直方图条

Histogram bars cannot stacked using matplotlib in python

我在 python 中使用“matplotlib”实现了直方图。我有两个变量 x1 和 x2,每个变量有 15 个元素。当运行代码时,直方图条不是堆叠而是重叠,如下图所示。

我想绘制变量条形的堆叠直方图。

代码是:

x1= [23, 25, 40, 35, 40, 53, 33, 28, 55, 34, 20, 37, 36, 23, 33]
x2= [36, 20, 27, 50, 34, 47, 18, 28, 52, 21, 44, 34, 13, 40, 49]
colors = ['blue', 'orange']
bins = [10,20,30,40,50,60]
fig, (ax0, ax1, ax2) = plt.subplots(nrows=3)

ax0.hist(x1,bins = bins,  histtype='bar',  label=colors[0], rwidth=0.8)
ax0.hist(x2,bins, histtype='bar', stacked=True, label=colors[1], rwidth=0.8)

ax1.hist(x1, bins = bins, histtype='bar',  label=colors[0], rwidth=0.8)
ax1.hist(x2,bins = bins, histtype='bar', stacked=True,  label=colors[1], rwidth=0.8)

ax2.hist(x1, bins = bins, histtype='bar',  label=colors[0], rwidth=0.8)
ax2.hist(x2,bins = bins, histtype='bar', stacked=True,  label=colors[1], rwidth=0.8)

plt.show()

输出

尝试同时传递两个列表并使用 stacked=True。只传递一个列表并使用 stacked=True 没有多大意义。

ax0.hist([x1, x2], bins, histtype='bar', stacked=True, label=colors, rwidth=0.8)
ax1.hist([x1, x2], bins, histtype='bar', stacked=True, label=colors, rwidth=0.8)
ax2.hist([x1, x2], bins, histtype='bar', stacked=True, label=colors, rwidth=0.8)