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

use*_*135 94 python matplotlib

下面的代码会在子图之间产生间隙.如何消除子图之间的间隙并使图像成为紧密的网格?

在此输入图像描述

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()
Run Code Online (Sandbox Code Playgroud)

Thu*_*411 103

问题是使用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)
Run Code Online (Sandbox Code Playgroud)

结果是这样的:

但是,使用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)
Run Code Online (Sandbox Code Playgroud)

这就是我们得到的:

第二种情况的不同之处在于,您已迫使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)
Run Code Online (Sandbox Code Playgroud)

这是结果:

  • 我尝试了这个,但每列图像之间仍然存在垂直间隙..并且 set_aspect('equal') 对我来说没有任何改变 (5认同)
  • 谢谢!你的答案很简单,效果很好.`plt.subplots_adjust(wspace = 0,hspace = 0)` (3认同)

Mol*_*lly 79

您可以使用gridspec来控制轴之间的间距.这里有更多信息.

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()
Run Code Online (Sandbox Code Playgroud)

轴非常靠近

  • 它不仅限于`GridSpec`,如果你在创建时抓住图形,你也可以设置距离:`fig.subplots_adjust(hspace =,wspace =)` (25认同)
  • `for`循环中的最后一行是什么意思? (3认同)
  • 有没有办法消除第一行和第二行轴之间**仅**的水平间距? (2认同)

Her*_*eer 24

而不诉诸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()
Run Code Online (Sandbox Code Playgroud)

导致:

.


Mic*_*ter 9

使用最近的 matplotlib 版本,您可能想尝试Constrained Layoutplt.subplot()但是,这确实(或至少确实)不起作用,因此您需要plt.subplots()改用:

fig, axs = plt.subplots(4, 4, constrained_layout=True)
Run Code Online (Sandbox Code Playgroud)


MER*_*ose 8

另一种方法是使用pad关键字 from plt.subplots_adjust(),它也接受负值:

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)
Run Code Online (Sandbox Code Playgroud)

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

  • 它将返回: TypeError: subplots_adjust() got an Unexpected keywords argument 'pad' (5认同)

CT *_*Zhu 5

你试过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]))
Run Code Online (Sandbox Code Playgroud)

如果您不需要共享轴,那么只需 axLS=map(fig.add_axes, rectLS) 在此处输入图片说明