如何确定子图(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。
基本上我想要一个稀疏的图形。行中的一些子图可以是空的,但它们应该被停用(轴必须不可见)。必须删除完全为空的行,并且不能将其设置为不可见。
发布于 2016-07-22 17:27:06
实现所需功能的一种方法是使用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()这将显示以下图表:

编辑:
实际上,Subplot2grid确实为您提供了轴的列表。在最初的问题中,您先使用fig, axes = plt.subplots(3, 7, squeeze=False),然后使用axes[0][1].plot(x, y)指定将在哪个子图中绘制数据。这与subplot2grid所做的相同,不同之处在于它只显示您定义的带有数据的子图。
以我上面的答案中的ax1 = plt.subplot2grid((3, 7), (0, 1))为例,这里我已经指定了“网格”的形状,即3* 7。这意味着如果我想要的话,我可以在网格中有21个子图,就像你的原始代码一样。不同之处在于,您的代码显示了所有的子图,而subplot2grid则不显示。上面ax1 = ...中的(3,7)指定了整个网格的形状,(0,1)指定了子图将在中的哪个位置显示。
您可以在3x7网格内的任何位置使用子图。如果需要,您还可以使用包含数据的子图填充该网格的所有21个空间,方法是一直到ax21 = plt.subplot2grid(...)。
发布于 2016-12-06 23:49:05
您可以使用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)https://stackoverflow.com/questions/38522408
复制相似问题