问题描述
虽然删除 matplotlib 子图/轴似乎很容易,例如延迟
:
fig, ax = plt.subplots(3,1, sharex=True)对于范围(3)中的ii:ax[ii].plot(arange(10), 2*arange(10))fig.delaxes(ax[1])
这将始终在删除的子图/轴的位置留下空白.
提议的解决方案似乎都无法解决此问题:
更改几何形状后
While it seems it is quite easy to delete a matplotlib subplot/axis, e.g. with 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])
This will always leave a blank at the place of the removed subplot/axes.
None of the solutions proposed seems to fix this:Delete a subplotClearing a subplot in Matplotlib
Is there a way to basically squeeze subplots and remove the blank before showing it or saving them?
I am basically searching the easiest way to transfer remaining subplot into a "dense" grid so that there are no blanks were subplot were previously, possibly better than recreating new (sub)plots.
My first idea was to clear all data in figure, recreate subplots and plot again the same data.
And it works but it copies only data. If plot has some changes then new plot will lose it - or you would have to copy also properties.
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()
But when I start digging in code I found that every axes
keeps subplot's position (ie. (1,3,1)
) as property "geometry"
import pprint
pprint.pprint(axs[0].properties())
pprint.pprint(axs[1].properties())
and it has .change_geometry()
to change it
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 changing geometry
After changing geometry
这篇关于删除 matplotlib 子图并避免留空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!