创建轴后更改 matplotlib 子图大小/位置 [英] Changing matplotlib subplot size/position after axes creation

查看:57
本文介绍了创建轴后更改 matplotlib 子图大小/位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在创建轴后设置 matplotlib 子图的大小/位置?我知道我可以做到:

Is it possible to set the size/position of a matplotlib subplot after the axes are created? I know that I can do:

import matplotlib.pyplot as plt

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

将轴放在三个的顶行.但我希望轴跨越前两行.我试过这个:

to put the axes on the top row of three. But I want the axes to span the first two rows. I have tried this:

import matplotlib.gridspec as gridspec

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

但轴仍然填满整个窗口.

but the axes still fill the whole window.

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

Update for clarity I want to change the position of an existing axes instance rather than set it when it is created. This is because the extent of the axes will be modified each time I add data (plotting data on a map using cartopy). The map may turn out tall and narrow, or short and wide (or something in between). So the decision on the grid layout will happen after the plotting function.

推荐答案

感谢 Molly 为我指明了正确的方向,我有了一个解决方案:

Thanks to Molly pointing me in the right direction, I have a solution:

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

这篇关于创建轴后更改 matplotlib 子图大小/位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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