删除 matplotlib 子图并避免留空

Delete a matplotlib subplot and avoid left blank(s)

虽然删除 matplotlib 似乎很容易 subplot/axis,例如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])

这将始终在删除的 subplot/axes 处留下一个 空白

None 提出的解决方案似乎解决了这个问题: Delete a subplot

有没有办法基本上压缩子图并在显示或保存之前删除空白?

我基本上是在寻找最简单的方法将剩余的子图转移到 "dense" 网格中,这样子图以前就没有空白了,可能比重新创建新的(子)图更好。

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

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

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()

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

import pprint

pprint.pprint(axs[0].properties())
pprint.pprint(axs[1].properties())

它有 .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()

之前 改变几何形状

改变几何形状后