删除 matplotlib 子图并避免留空 [英] Delete a matplotlib subplot and avoid left blank(s)

查看:167
本文介绍了删除 matplotlib 子图并避免留空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

虽然删除 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 subplot Clearing 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 子图并避免留空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆