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

标签 python matplotlib plot 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)

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

Stacked side-by-side histogram example

最佳答案

图为bar chart而不是histogram 。我指出这一点,不仅因为我是一个令人讨厌的学究,还因为我相信它可以帮助您找到合适的工具:-)
事实上,出于您的目的,plt.bar 可能比 plt.hist 更好。

根据Scironic的建议,我修改了这个demonstration example制作堆叠的条形,就像您图中的那样。

向位置索引添加偏移量(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()

enter image description here

关于python - 如何在 matplotlib 中并排绘制堆叠直方图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28152267/

相关文章:

python - 错误: No 'Access-Control-Allow-Origin' header in a Python web server

python - 使用 Python 将 LONGTEXT 从 MySQL 复制到 PostgreSQL 中的 CITEXT

python - Pandas 以最小的差距绘制时间序列

r - 在 R 中创建多个折线图

r - 如何在 R 中创建条形图,其中 y 轴为频率而不是密度?

python - 尝试过滤列表时出现 TypeError : 'NoneType' object is not iterable,

python - <枚举位于 0x7f0211ea2360 的对象>

python - 因 imshow 中的一个错误而关闭?

python - 如何使用 matplotlib 和 pandas 绘制日期时间与值的线性趋势线?

python - 在 matplotlib 中更改刻度标签行间距