Pyplot:共享坐标轴且子图无间距

13 投票
1 回答
15653 浏览
提问于 2025-04-17 23:38

这段内容是关于一个问题的后续,原问题可以在这里找到:在matplotlib中共享轴的方形子图的新Python风格?

我想要创建一些子图,它们共享一个轴,就像上面链接的问题那样。不过,我还希望这些图之间没有空隙。这是我代码中相关的部分:

f, (ax1, ax2) = plt.subplots(1, 2, sharex=True, sharey=True)
plt.setp(ax1, aspect=1.0, adjustable='box-forced')
plt.setp(ax2, aspect=1.0, adjustable='box-forced')

# Plot 1
ax1.matshow(pixels1, interpolation="bicubic", cmap="jet")
ax1.set_xlim((0,500))
ax1.set_ylim((0,500))

# Plot 2
ax2.matshow(pixels2, interpolation="bicubic", cmap="jet")
ax2.set_xlim((0,500))
ax2.set_ylim((0,500))

f.subplots_adjust(wspace=0)

这是我得到的结果:

enter image description here

如果我把两个plt.setp()命令注释掉,就会出现一些多余的白色边框:

enter image description here

我该如何让图形看起来像我第一个结果那样,但又让轴像第二个结果那样紧贴在一起呢?

1 个回答

13

编辑:得到结果最快的方法是@Benjamin Bannier描述的,只需使用

fig.subplots_adjust(wspace=0)

另一种方法是制作一个宽高比为2的图形(因为你有两个图)。如果你打算把这个图放到文档里,并且已经知道最终文档的列宽,这样做可能比较合适。

你可以在调用Figure(figsize=(width,height))时设置宽度和高度,或者作为参数传给plt.subplots(),单位是英寸。举个例子:

fig, axes = plt.subplots(ncols=2, sharex=True, sharey=True,figsize=(8,4))
fig.subplots_adjust(0,0,1,1,0,0)

截图:enter image description here

正如@Benjamin Bannier指出的,缺点是没有边距。你可以使用subplot_adjust()来调整,但如果想保持简单,得小心对称地留出空间。一个例子可以是fig.subplots_adjust(.1,.1,.9,.9,0,0)

撰写回答