删除matplotlib子图并避免留空

问题描述 投票:0回答:1

虽然似乎很容易删除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])

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

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

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

python matplotlib subplot
1个回答
0
投票

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

并且它可以工作,但只复制数据。如果绘图有一些更改,则新绘图将丢失它-否则您也必须复制属性。

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

[Before更改几何形状

enter image description here

[After更改几何形状

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.