如何确定子图 (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
。
基本上我想要一个稀疏的图形。行中的一些子图可以是空的,但它们应该被停用(没有轴必须可见)。必须删除完全空的行,并且不得将其设置为不可见。
最佳答案
您可以使用 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)
关于python - 删除 matplotlib 图中的空子图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38522408/