首页 > 解决方案 > 使用 matplotlib 将多个直方图放在一个堆栈中

问题描述

我正在尝试将多个直方图放在垂直堆栈中。我能够在堆栈中获取图,但是所有直方图都在同一个图中。

fig, ax = plt.subplots(2, 1, sharex=True, figsize=(20, 18))

n = 2

axes = ax.flatten()
for i, j in zip(range(n), axes):
    plt.hist(np.array(dates[i]), bins=20, alpha=0.3)


plt.show()

在此处输入图像描述

标签: pythonmatplotlibhistogram

解决方案


您有一个 2x1 的轴对象网格。通过直接循环axes.flatten(),您一次访问一个子图。然后,您需要使用相应的轴实例来绘制直方图。

fig, axes = plt.subplots(2, 1, sharex=True, figsize=(20, 18)) # axes here

n = 2

for i, ax in zip(range(n), axes.flatten()): # <--- flatten directly in the zip
    ax.hist(np.array(dates[i]), bins=20, alpha=0.3)

您的原始版本也是正确的plt,只是您应该使用正确的变量j而不是,而不是plt

for i, j in zip(range(n), axes):
    j.hist(np.array(dates[i]), bins=20, alpha=0.3)

推荐阅读