删除matplotlib图中的空子图

hot*_*ots 9 python matplotlib

如何确定subplot(AxesSubplot)是否为空?我想停用空子图的空轴并删除完全空行.

例如,在该图中,仅填充了两个子图,其余的子图是空的.

import matplotlib.pyplot as plt

# create figure wit 3 rows and 7 cols; don't squeeze is it one list
fig, axes = plt.subplots(3, 7, squeeze=False)
x = [1,2]
y = [3,4]

# plot stuff only in two SubAxes; other axes are empty
axes[0][1].plot(x, y)
axes[1][2].plot(x, y)

# save figure
plt.savefig('image.png')
Run Code Online (Sandbox Code Playgroud)

注意:必须设置squeezeFalse.

基本上我想要一个稀疏的人物.行中的某些子图可以为空,但应将其取消激活(不能显示任何轴).必须删除完全空行,不得将其设置为不可见.

小智 13

您可以使用以下fig.delaxes()方法:

import matplotlib.pyplot as plt

# create figure wit 3 rows and 7 cols; don't squeeze is it one list
fig, axes = plt.subplots(3, 7, squeeze=False)
x = [1,2]
y = [3,4]

# plot stuff only in two SubAxes; other axes are empty
axes[0][1].plot(x, y)
axes[1][2].plot(x, y)

# delete empty axes
for i in [0, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15, 16, 17,
          18, 19, 20]:
    fig.delaxes(axes.flatten()[i])

# save figure
plt.savefig('image.png')
plt.show(block=False)
Run Code Online (Sandbox Code Playgroud)


Dav*_*idG 5

实现您所需要的一种方法是使用matplotlibs subplot2grid功能。使用此功能,您可以设置网格的总大小(在您的情况下为3.7),并选择仅在该网格的某些子图中绘制数据。我在下面修改了您的代码以给出示例:

import matplotlib.pyplot as plt

x = [1,2]
y = [3,4]

fig = plt.subplots(squeeze=False)
ax1 = plt.subplot2grid((3, 7), (0, 1))
ax2 = plt.subplot2grid((3, 7), (1, 2))

ax1.plot(x,y)
ax2.plot(x,y)

plt.show()
Run Code Online (Sandbox Code Playgroud)

这给出了下图:

在此处输入图片说明

编辑:

实际上,Subplot2grid确实为您提供了轴列表。在最初的问题中,您使用fig, axes = plt.subplots(3, 7, squeeze=False),然后使用axes[0][1].plot(x, y)来指定将在其中绘制数据的子图。这与subplot2grid所做的相同,不同之处在于,它仅显示带有已定义数据的子图。

因此,请ax1 = plt.subplot2grid((3, 7), (0, 1))接受上面的答案,在此我指定了“网格”的形状,该形状为3 x7。这意味着,如果需要的话,可以在该网格中有21个子图,就像您的原始代码一样。区别在于您的代码显示所有子图,而subplot2grid不显示。的(3,7)ax1 = ...上述指定整个格栅的形状和(0,1)其中指定该网格中的副区将被显示。

您可以在3x7网格中的任意位置使用子图的任何位置。如果需要,您还可以用子图填充该网格的所有21个空间,直到最大极限ax21 = plt.subplot2grid(...)