【问题标题】:Changing the Matplotlib GridSpec properties after generating the subplots生成子图后更改 Matplotlib GridSpec 属性
【发布时间】:2021-06-27 01:10:02
【问题描述】:

假设我的情节中出现了一些问题,要求我更改我在情节中生成的两个子情节之间的高度比。我尝试更改GridSpec 的身高比例,但无济于事。

import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec

fig = plt.figure()
gs = GridSpec(2, 1, height_ratios=[2, 1])

ax1 = fig.add_subplot(gs[0])
ax1 = fig.axes[0]
ax2 = fig.add_subplot(gs[1])
ax2 = fig.axes[1]

ax1.plot([0, 1], [0, 1])
ax2.plot([0, 1], [1, 0])

gs.height_ratios = [2, 5]

最后一行对容积率没有影响。

在我的实际代码中,如果不进行重大修改,将 height_ratio 提前设置为 2:5 是不可行的。

如何按我的意愿进行更新?

【问题讨论】:

  • 你尝试过 constrained_layout 吗?
  • @JodyKlymak 我更喜欢让 Matplotlib 自动计算我指定的高度比,而不是自己尝试使用 constrained_layout 来计算它们。当然这里有一个更简单的解决方案。
  • 我不确定您所说的“自己解决”是什么意思。 Constrained_layout 在重绘之前会自动调整大小,这是您想要的。
  • 对不起,我收回 - constrained_layout 不会在绘制时传递高度比,而是在创建时传递。看起来您需要重新构建代码,或者手动执行此操作。
  • 当然,手动操作。获取轴的位置,使一个较短,另一个较高。 Matplotlib 的布局工具是相对静态的。您可以在github.com/matplotlib/matplotlib 提出功能请求

标签: matplotlib subplot


【解决方案1】:

可以对相关子图的axes 进行操作和调整以获得新的高度比。

import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec

fig = plt.figure()
gs = GridSpec(2, 1, height_ratios=[2, 1]) #nrows, ncols

ax1 = fig.add_subplot(gs[0])
ax1 = fig.axes[0]
ax2 = fig.add_subplot(gs[1])
ax2 = fig.axes[1]

ax1.plot([0, 1], [0, 1])
ax2.plot([0, 1], [1, 0])

# new height ratio: 2:5 is required for the 2 subplots
rw, rh = 2, 5

# get dimensions of the 2 axes
box1 = ax1.get_position()
box2 = ax2.get_position()
# current dimensions
w1,h1 = box1.x1-box1.x0, box1.y1-box1.y0
w2,h2 = box2.x1-box2.x0, box2.y1-box2.y0
top1 = box1.y0+h1
#top2 = box2.y0+h2
full_h = h1+h2   #total height

# compute new heights for each axes
new_h1 = full_h*rw/(rw + rh)
new_h2 = full_h*rh/(rw + rh)

#btm1,btm2 = box1.y0, box2.y0
new_bottom1 = top1-new_h1

# finally, set new location/dimensions of the axes
ax1.set_position([box1.x0, new_bottom1, w1, new_h1])
ax2.set_position([box2.x0, box2.y0, w2, new_h2])

plt.show()

比率的输出:(2, 5):

(2, 10) 的输出:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-17
    • 2018-10-11
    • 2015-09-20
    • 2021-04-05
    相关资源
    最近更新 更多