【问题标题】:Delete a matplotlib subplot and avoid left blank(s)删除 matplotlib 子图并避免留空
【发布时间】:2020-08-07 03:29:17
【问题描述】:

虽然删除 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 subplot Clearing a subplot in Matplotlib

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

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

【问题讨论】:

  • blank 是什么意思?如果您删除情节,我不明白您的期望是什么。如果要删除绘图上的线并保留轴,则必须删除 ax.data 而不是删除 axes
  • 如果你想删除空格,那么你应该创建具有不同值的新子图 - 即subplots(2,1) 并再次绘制所有图,但在新轴上。

标签: python matplotlib subplot


【解决方案1】:

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

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

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

改变几何之前

改变几何之后

【讨论】:

  • 太棒了! “change_geometry”似乎完全符合我的意思:)
猜你喜欢
  • 1970-01-01
  • 2018-08-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多