【问题标题】:Changing matplotlib subplot size/position after axes creation创建轴后更改 matplotlib 子图大小/位置
【发布时间】:2014-04-05 13:08:12
【问题描述】:

是否可以在创建轴后设置 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 在地图上绘制数据)。地图可能会变得又高又窄,或者又短又宽(或介于两者之间)。所以网格布局的决定将在绘图功能之后发生。

【问题讨论】:

  • 感谢您提出这样的问题,我已经搜索了几个小时才找到您的问题。有关信息,我的用例:在PyQt 中显示的Figure 中动态添加/删除子图,避免在发生此类修改时对项目创建和后续数据加载进行新调用。

标签: python matplotlib


【解决方案1】:

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

【讨论】:

  • 这里重要的是1) 创建一个具有预期布局的新GridSpec 实例,因为它的行数或列数无法更新(即使使用它的update() 方法); 2) 调用ax.set_position(gs[0:2].get_position(fig)) 调整大小;调用set_subplotspec只创建ref,不更新位置。
【解决方案2】:

您可以使用 subplot2gridrowspan 参数创建一个包含一个跨两行的子图和一个跨行的子图的图形:

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

如果要在创建子图后更改子图的大小和位置,可以使用set_position 方法。

ax1.set_position([0.1,0.1, 0.5, 0.5])

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

【讨论】:

  • 谢谢莫莉。看起来 ax.set_position(plt.subplot(gs[0:2]).get_position()) 应该做我想做的事。
  • ax.set_position() 有效,但在我之前的评论中对 plt.subplot() 的额外调用仅在您想要一个空图时才有用!
【解决方案3】:

您可以通过使用fig.tight_layout() 来避免ax.set_position(),而不是重新计算新的gridspec:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-30
    • 2017-11-14
    • 1970-01-01
    • 1970-01-01
    • 2017-12-12
    • 2013-02-09
    相关资源
    最近更新 更多