在创建轴之后更改matplotlib子图大小/位置

24

在创建Axes之后,是否可能设置matplotlib子图的大小和位置?我知道可以这样做:

import matplotlib.pyplot as plt

ax = plt.subplot(111)
ax.change_geometry(3,1,1)

将三个图表的坐标轴放在顶部。但我希望坐标轴跨越前两行。我尝试过以下方法:

import matplotlib.gridspec as gridspec

ax = plt.subplot(111)
gs = gridspec.GridSpec(3,1)
ax.set_subplotspec(gs[0:2])

但是坐标轴仍然填满整个窗口。

澄清更新 我想改变现有坐标轴实例的位置而不是在创建时设置它。这是因为每次添加数据时(使用cartopy在地图上绘制数据),坐标轴的范围将被修改。地图可能会变得高而窄,或短而宽(或介于两者之间)。因此,网格布局的决定将在绘图函数之后发生。


1
感谢您提出这样的问题,我在找到您的问题之前已经搜索了几个小时。我的用例是:在PyQt中显示的Figure中动态添加/删除子图,避免在进行此类修改时创建新项并加载后续数据。 - Joël
3个回答

19

多亏了Molly指引我正确的方向,我找到了解决方案:

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

fig = plt.figure()

ax = fig.add_subplot(111)

gs = gridspec.GridSpec(3,1)
ax.set_position(gs[0:2].get_position(fig))
ax.set_subplotspec(gs[0:2])              # only necessary if using tight_layout()

fig.add_subplot(gs[2])

fig.tight_layout()                       # not strictly part of the question

plt.show()

3
这里的关键是:1) 创建一个新的GridSpec实例,并设置预期的布局,因为它的行数或列数无法更新(即使使用其update()方法); 2)调用ax.set_position(gs[0:2].get_position(fig))进行调整大小;仅调用set_subplotspec只会创建引用,而不会更新位置。 - Joël

7

您可以使用rowspan参数来创建一个跨越两行的子图和一个跨越一行的子图,从而创建一个带有一个子图的图形,使用subplot2grid

import matplotlib.pyplot as plt

fig = plt.figure()
ax1 = plt.subplot2grid((3,1), (0,0), rowspan=2)
ax2 = plt.subplot2grid((3,1), (2,0))
plt.show()

enter image description here

如果您想在创建子图后更改其大小和位置,则可以使用set_position方法。
ax1.set_position([0.1,0.1, 0.5, 0.5])

但是你不需要这个来创建你所描述的图形。

谢谢,莫莉。看起来ax.set_position(plt.subplot(gs[0:2]).get_position())应该可以满足我的需求。 - RuthC
ax.set_position() 是有效的,但我之前评论中多余的 plt.subplot() 调用只有在你想要一个空图时才有用! - RuthC

1
你可以使用fig.tight_layout()代替ax.set_position(),它会重新计算新的网格规范,从而避免使用ax.set_position()
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

# create the first axes without knowing of further subplot creation
fig, ax = plt.subplots()
ax.plot(range(5), 'o-')

# now update the existing gridspec ...
gs = gridspec.GridSpec(3, 1)
ax.set_subplotspec(gs[0:2])
# ... and recalculate the positions
fig.tight_layout()

# add a new subplot
fig.add_subplot(gs[2])
fig.tight_layout()
plt.show()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接