生成子图后更改 Matplotlib GridSpec 属性

时间:2021-03-31 02:14:20

标签: matplotlib subplot

假设我的情节中出现了一些东西,要求我更改我在情节中生成的两个子情节之间的高度比。我试过改变 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_ratios 设置为 2:5,则不进行重大修改是不可行的。

我如何让它像我想要的那样更新?

1 个答案:

答案 0 :(得分:3)

可以操纵和调整相关子图的 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()

ratio 的输出:(2, 5):

2x5

(2, 10) 的输出:

2x10

相关问题