首页 > 解决方案 > 删除水平方向子图之间的分隔

问题描述

我有四个二维数组,我想使用 imshow 在四个子图中绘制。我希望删除这些子图之间的分隔,使子图相互接触,类似于Matplotlib 文档(倒数第二个示例)。我的尝试是

fig, axs = plt.subplots(2, 2, sharex='col', sharey='row', gridspec_kw={'hspace': 0, 'wspace': 0})
(ax1, ax2), (ax3, ax4) = axs

ax1.imshow(im1)
ax2.imshow(im2)
ax3.imshow(im3)
ax4.imshow(im4)

for ax in fig.get_axes():
    ax.label_outer()

plt.show()

这产生

在此处输入图像描述

垂直方向的分离似乎被正确删除,但我仍然有水平方向的分离。有谁知道我怎么能在这里摆脱它?

标签: pythonmatplotlibsubplot

解决方案


您可以按照ImportanceOfBeingErnest的答案尝试一些方法。我已经根据它为您的问题准备了以下伪代码。您可以尝试一下,看看它是否适合您。

from matplotlib import gridspec

nrow, ncol = 2, 2

fig = plt.figure(figsize=(6,6)) 

gs = gridspec.GridSpec(nrow, ncol,
         wspace=0.0, hspace=0.0, 
         top=1.-0.5/(nrow+1), bottom=0.5/(nrow+1), 
         left=0.5/(ncol+1), right=1-0.5/(ncol+1)) 

ims = [im1, im2, im3, im4]

c = 0 # Counter for the ims array

for i in range(nrow):
    for j in range(ncol):
        ax= plt.subplot(gs[i,j])
        ax.imshow(ims[c])
        ax.set_xticklabels([])
        ax.set_yticklabels([])
        c += 1

for ax in fig.get_axes():
    ax.label_outer()       

推荐阅读