python - 删除 matplotlib 图中的空子图

标签 python matplotlib

如何确定子图 (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/

相关文章:

python - "Invalid shape for y"用于 Keras LSTM w/return_sequences=True(和 sklearn API)

python - Matplotlib 轴位置和颜色条对齐

python - set_data 和 autoscale_view matplotlib

python - 来自 Pandas DataFrame 的烛台图中的重叠日期

python - 如何从 treq 请求中获取响应文本?

python - 用 pandas 绘制水平持续时间

plot - 在子图之间共享等值线图属性

python - 在 Mac OS X 10.9 上安装 matplotlib

python - Pandas DataFrame分组生成数值多索引

python - 使用 for 循环遍历列表时从 csv 文件中提取值