Matplotlib 多个 imshow 共享一个轴

Matplotlib multiple imshow share an axis

我正在一个接一个地绘制 5 个 imshow,如下所示。

我使用下面的代码生成上面的图。

fig = plt.figure()
ax1 = plt.subplot(511) 
ax2 = plt.subplot(512)
ax3 = plt.subplot(513)
ax4 = plt.subplot(514)
ax5 = plt.subplot(515)
ax1.imshow(data1)
ax2.imshow(data2)
ax3.imshow(data3)
ax4.imshow(data4)
ax5.imshow(data5)
plt.show()

我想知道是否有办法让所有的 imshows 共享 x 轴(并将它们一个放在另一个下面,没有白色间隙)

谢谢。

可以使用 subplots_adjust 方法更改子图之间的间距。更多信息可以在 official documentation here.

中找到

下面是删除两个子图之间的垂直 space 的示例:

import numpy as np
import matplotlib.pyplot as plt

plt.subplots_adjust(left=0.125,
                    bottom=0.1,
                    right=0.9,
                    top=0.9,
                    wspace=0.2,
                    hspace=0)

x1 = np.linspace(0.0, 5.0)
x2 = np.linspace(0.0, 2.0)

y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
y2 = np.cos(2 * np.pi * x2)

plt.subplot(2, 1, 1)
plt.plot(x1, y1, 'o-')
plt.title('A tale of 2 subplots')
plt.ylabel('Damped oscillation')

plt.subplot(2, 1, 2)
plt.plot(x2, y2, '.-')
plt.xlabel('time (s)')
plt.ylabel('Undamped')

plt.show()

输出:

添加到 arsho 的答案中,您还可以使不同的子图共享轴,使用参数 share and/or sharey chen 创建子图。

像这样的东西应该适合你:

fig = plt.figure()
ax1 = plt.subplot(511) 
ax2 = plt.subplot(512, sharex = ax1)
ax3 = plt.subplot(513, sharex = ax1)
ax4 = plt.subplot(514, sharex = ax1)
ax5 = plt.subplot(515, sharex = ax1)
ax1.imshow(data1)
ax2.imshow(data2)
ax3.imshow(data3)
ax4.imshow(data4)
ax5.imshow(data5)
plt.show()