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

zazmityj  于 2023-10-24  发布在  其他
关注(0)|答案(7)|浏览(181)

下面的代码在子图之间产生了间隙。我如何消除子图之间的间隙,使图像成为一个紧密的网格?

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()
ct3nt3jp

ct3nt3jp1#

问题在于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([])

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

结果是:

但是,对于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)

这就是我们得到的:

第二种情况的不同之处在于,你强制x轴和y轴具有相同的单位/像素数。由于默认情况下轴从0到1(即在绘制任何东西之前),使用aspect='equal'强制每个轴都是正方形。由于图形不是正方形,pyplot在轴之间增加了额外的水平间距。
为了解决这个问题,你可以设置你的图有正确的长宽比。我们将在这里使用面向对象的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)

结果如下:

umuewwlo

umuewwlo2#

你可以使用gridspec来控制轴之间的间距。这里有更多的information

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()

c7rzv4ha

c7rzv4ha3#

在不完全重新排序gridspec的情况下,也可以使用以下方法通过将 wspacehspace 设置为零来消除间隙:

import matplotlib.pyplot as plt

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

for ax in axarr.flatten():
    ax.grid('on', linestyle='--')
    ax.set_xticklabels([])
    ax.set_yticklabels([])

plt.show()
plt.close()

导致:

webghufk

webghufk4#

对于最新的matplotlib版本,你可能想尝试Constrained Layout。但是这对plt.subplot()不起作用,所以你需要使用plt.subplots()来代替:

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

3ks5zfa05#

你试过plt.tight_layout()吗?
plt.tight_layout()

没有它:

或者:类似这样的东西(使用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]))

如果不需要共享轴,则只需axLS=map(fig.add_axes, rectLS)

vulvrdjw

vulvrdjw6#

另一种方法是使用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)

此外,要删除所有子图(即画布)外边缘的白色,请始终使用plt.savefig(fname, bbox_inches="tight")进行保存。

g6ll5ycj

g6ll5ycj7#

Matplotlib将检查“subplotpars”参数来定义子图位置。所以这应该可以工作:

left   = 0.03 #The position of the left edge of the subplots, as a fraction of the figure width.
bottom = 0.05 #The position of the bottom edge of the subplots, as a fraction of the figure height.
right  = 0.99 #The position of the right edge of the subplots, as a fraction of the figure width.
top    = 0.97 #The position of the top edge of the subplots, as a fraction of the figure height.
wspace = None #The width of the padding between subplots, as a fraction of the average Axes width.
hspace = None #The height of the padding between subplots, as a fraction of the average Axes height.

fig.subplotpars.update(left, bottom, right, top, wspace, hspace)

您可以根据需要单独调整上述参数(在0和1之间)。

相关问题