简体   繁体   English

如何消除matplotlib中子图之间的间隙?

[英]How to remove gaps between subplots in matplotlib?

The code below produces gaps between the subplots.下面的代码在子图之间产生间隙。 How do I remove the gaps between the subplots and make the image a tight grid?如何消除子图之间的间隙并使图像成为紧密网格?

在此处输入图片说明

import matplotlib.pyplot as plt

for i in range(16):
    i = i + 1
    ax1 = plt.subplot(4, 4, i)
    plt.axis('on')
    ax1.set_xticklabels([])
    ax1.set_yticklabels([])
    ax1.set_aspect('equal')
    plt.subplots_adjust(wspace=None, hspace=None)
plt.show()

The problem is the use of aspect='equal' , which prevents the subplots from stretching to an arbitrary aspect ratio and filling up all the empty space.问题是使用aspect='equal' ,它可以防止子图拉伸到任意纵横比并填满所有空白空间。

Normally, this would work:通常,这会起作用:

import matplotlib.pyplot as plt

ax = [plt.subplot(2,2,i+1) for i in range(4)]

for a in ax:
    a.set_xticklabels([])
    a.set_yticklabels([])

plt.subplots_adjust(wspace=0, hspace=0)

The result is this:结果是这样的:

However, with aspect='equal' , as in the following code:但是,使用aspect='equal' ,如下面的代码所示:

import matplotlib.pyplot as plt

ax = [plt.subplot(2,2,i+1) for i in range(4)]

for a in ax:
    a.set_xticklabels([])
    a.set_yticklabels([])
    a.set_aspect('equal')

plt.subplots_adjust(wspace=0, hspace=0)

This is what we get:这是我们得到的:

The difference in this second case is that you've forced the x- and y-axes to have the same number of units/pixel.第二种情况的不同之处在于您已强制 x 轴和 y 轴具有相同数量的单位/像素。 Since the axes go from 0 to 1 by default (ie, before you plot anything), using aspect='equal' forces each axis to be a square.由于默认情况下轴从 0 到 1(即,在绘制任何内容之前),使用aspect='equal'强制每个轴为正方形。 Since the figure is not a square, pyplot adds in extra spacing between the axes horizontally.由于图形不是正方形,因此 pyplot 在水平轴之间增加了额外的间距。

To get around this problem, you can set your figure to have the correct aspect ratio.要解决此问题,您可以将图形设置为具有正确的纵横比。 We're going to use the object-oriented pyplot interface here, which I consider to be superior in general:我们将在这里使用面向对象的 pyplot 接口,我认为它总体上是优越的:

import matplotlib.pyplot as plt

fig = plt.figure(figsize=(8,8)) # Notice the equal aspect ratio
ax = [fig.add_subplot(2,2,i+1) for i in range(4)]

for a in ax:
    a.set_xticklabels([])
    a.set_yticklabels([])
    a.set_aspect('equal')

fig.subplots_adjust(wspace=0, hspace=0)

Here's the result:结果如下:

You can use gridspec to control the spacing between axes.您可以使用gridspec来控制轴之间的间距。 There's more information here.这里有更多信息

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

plt.figure(figsize = (4,4))
gs1 = gridspec.GridSpec(4, 4)
gs1.update(wspace=0.025, hspace=0.05) # set the spacing between axes. 

for i in range(16):
   # i = i + 1 # grid spec indexes from 0
    ax1 = plt.subplot(gs1[i])
    plt.axis('on')
    ax1.set_xticklabels([])
    ax1.set_yticklabels([])
    ax1.set_aspect('equal')

plt.show()

轴非常靠近

Without resorting gridspec entirely, the following might also be used to remove the gaps by setting wspace and hspace to zero:在不完全使用gridspec的情况下,以下内容也可用于通过将wspacehspace设置为零来消除间隙:

import matplotlib.pyplot as plt

plt.clf()
f, axarr = plt.subplots(4, 4, gridspec_kw = {'wspace':0, 'hspace':0})

for i, ax in enumerate(f.axes):
    ax.grid('on', linestyle='--')
    ax.set_xticklabels([])
    ax.set_yticklabels([])

plt.show()
plt.close()

Resulting in:导致:

.

With recent matplotlib versions you might want to try Constrained Layout .使用最近的 matplotlib 版本,您可能想尝试Constrained Layout This does (or at least did) not work with plt.subplot() however, so you need to use plt.subplots() instead:但是,这确实(或至少确实)不适用于plt.subplot() ,因此您需要改用plt.subplots()

fig, axs = plt.subplots(4, 4, constrained_layout=True)

Have you tried plt.tight_layout() ?你试过plt.tight_layout()吗?

with plt.tight_layout()plt.tight_layout()在此处输入图片说明 without it:没有它:在此处输入图片说明

Or: something like this (use add_axes )或者:像这样(使用add_axes

left=[0.1,0.3,0.5,0.7]
width=[0.2,0.2, 0.2, 0.2]
rectLS=[]
for x in left:
   for y in left:
       rectLS.append([x, y, 0.2, 0.2])
axLS=[]
fig=plt.figure()
axLS.append(fig.add_axes(rectLS[0]))
for i in [1,2,3]:
     axLS.append(fig.add_axes(rectLS[i],sharey=axLS[-1]))    
axLS.append(fig.add_axes(rectLS[4]))
for i in [1,2,3]:
     axLS.append(fig.add_axes(rectLS[i+4],sharex=axLS[i],sharey=axLS[-1]))
axLS.append(fig.add_axes(rectLS[8]))
for i in [5,6,7]:
     axLS.append(fig.add_axes(rectLS[i+4],sharex=axLS[i],sharey=axLS[-1]))     
axLS.append(fig.add_axes(rectLS[12]))
for i in [9,10,11]:
     axLS.append(fig.add_axes(rectLS[i+4],sharex=axLS[i],sharey=axLS[-1]))

If you don't need to share axes, then simply axLS=map(fig.add_axes, rectLS)如果您不需要共享轴,那么只需axLS=map(fig.add_axes, rectLS)在此处输入图片说明

Another method is to use the pad keyword from plt.subplots_adjust() , which also accepts negative values:另一种方法是使用plt.subplots_adjust()pad关键字,它也接受负值:

import matplotlib.pyplot as plt

ax = [plt.subplot(2,2,i+1) for i in range(4)]

for a in ax:
    a.set_xticklabels([])
    a.set_yticklabels([])

plt.subplots_adjust(pad=-5.0)

Additionally, to remove the white at the outer fringe of all subplots (ie the canvas), always save with plt.savefig(fname, bbox_inches="tight") .此外,要删除所有子图(即画布)外边缘的白色,请始终使用plt.savefig(fname, bbox_inches="tight")

The answer by MERose is correct but you can use it as shown below: MERose 的答案是正确的,但您可以使用它,如下所示:

plt.tight_layout(pad=1) plt.tight_layout(pad=1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM