使用 matplotlib 将多个直方图放在堆栈中

Placing multiple histograms in a stack with 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()

您有一个 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)