在matplotlib图中删除空的子图

18
我如何确定一个子图(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')

注意:必须将squeeze设置为False
基本上我想要一个稀疏的图形。一些行中的子图可能是空的,但它们应该被停用(没有轴必须可见)。完全空的行必须被删除,不能设置为不可见。

你可以使用subplot2grid吗? - DavidG
我认为这是可能的,但它如何解决我的问题来确定空的子图? - hotsplots
请查看我的答案,看它是否适用于你的问题。 - DavidG
2个回答

25
您可以使用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)

7
实现您所需的一种方法是使用matplotlib的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()

这将生成以下图表:

enter image description here

编辑:

实际上,subplot2grid 会给你一个包含多个子图的轴列表。在您最初的问题中,您使用 fig, axes = plt.subplots(3, 7, squeeze=False),然后使用 axes[0][1].plot(x, y) 指定要绘制数据的子图。这与 subplot2grid 所做的相同,只是它仅显示您定义的包含数据的子图。

所以,在我上面的答案中采用 ax1 = plt.subplot2grid((3, 7), (0, 1)),我已经指定了“网格”的形状,即 3x7。这意味着如果我想要,我可以在该网格中拥有 21 个子图,就像您的原始代码一样。不同之处在于,您的代码显示所有子图,而 subplot2grid 不会。上述 ax1 = ... 中的 (3,7) 指定整个网格的形状,(0,1) 指定子图将在该网格中的哪个位置显示。

你可以在3x7网格中的任何位置使用子图。如果需要,你也可以填充该网格的所有21个空间,并在其中放置具有数据的子图,方法是一直使用到ax21 = plt.subplot2grid(...)

这个 fig, axes = plt.subplots(3, 7, squeeze=False) 也是一个轴列表。我如何使用 subplot2grid 获得类似的轴列表? - hotsplots
当你说“轴列表”时,你的意思是使用fig, axes = plt.subplots(3, 7, squeeze=False)可以让你执行axes[0][1].plot(x, y)并选择实际显示绘图的子图吗? - DavidG
我已经更新了我的答案,试图回答您的评论(如果我理解正确的话)。 - DavidG
太好了。感谢您的帮助和解释。这确实解决了我的问题。 - hotsplots
这似乎类似于图形上的add_subplot函数。 - CMCDragonkai

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接