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

25 投票
3 回答
38061 浏览
提问于 2025-04-18 01:28

我想知道,在创建了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)。地图可能会变得又高又窄,或者又矮又宽(或者介于两者之间)。所以,网格布局的决定会在绘图函数之后进行。

3 个回答

1

你可以用 fig.tight_layout() 来代替 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()
8

你可以用 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])

不过,创建你所描述的图形并不需要这个方法。

20

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

撰写回答