删除 matplotlib 子图并避免留空

glu*_*uke 4 python matplotlib subplot

虽然删除 matplotlib 子图/轴似乎很容易,例如delaxes

fig, ax = plt.subplots(3,1, sharex=True)
for ii in range(3):
    ax[ii].plot(arange(10), 2*arange(10))
fig.delaxes(ax[1])
Run Code Online (Sandbox Code Playgroud)

这将始终留下空白在删除的子图/轴的位置

所提出的解决方案似乎都无法解决此问题: Delete a subplot Clearing a subplot in Matplotlib

有没有一种方法可以在显示或保存子图之前基本上挤压子图并删除空白?

我基本上正在寻找将剩余的子图转移到“密集”网格中的最简单方法,以便以前的子图没有空白,可能比重新创建新的(子)图更好。

fur*_*ras 9

我的第一个想法是清除图中的所有数据,重新创建子图并再次绘制相同的数据。

它可以工作,但它只复制数据。如果绘图有一些更改,那么新绘图将丢失它 - 或者您还必须复制属性。

from matplotlib import pyplot as plt

# original plots    
fig, axs = plt.subplots(1,3)
axs[0].plot([1,2],[3,4])
axs[2].plot([0,1],[2,3])
fig.delaxes(axs[1])

# keep data
data0 = axs[0].lines[0].get_data()
data2 = axs[2].lines[0].get_data()

# clear all in figure
fig.clf()

# create again axes and plot line
ax0 = fig.add_subplot(1,2,1)
ax0.plot(*data0)

# create again axis and plot line
ax1 = fig.add_subplot(1,2,2)
ax1.plot(*data2)

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

但是当我开始挖掘代码时,我发现每个都axes将子图的位置(即(1,3,1))保留为属性"geometry"

import pprint

pprint.pprint(axs[0].properties())
pprint.pprint(axs[1].properties())
Run Code Online (Sandbox Code Playgroud)

它必须.change_geometry()改变它

from matplotlib import pyplot as plt

fig, axs = plt.subplots(1,3)
axs[0].plot([1,2],[3,4])
axs[2].plot([0,1],[2,3])
fig.delaxes(axs[1])

# chagen position    
axs[0].change_geometry(1,2,1)
axs[2].change_geometry(1,2,2)

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

更改几何形状之前

在此输入图像描述

改变几何形状

在此输入图像描述

  • 极好的!“change_geometry”似乎正是我的意思:) (3认同)