如何在matplotlib约束布局模式下检索轴的真实位置

ted*_*511 3 python matplotlib

我创建了一个 (2x3) 子图并强制它们constrained_layout=True使用下面的代码。我想隐藏 ax03 并在该区域创建其他图形。为了对齐的目的,我用来ax.get_position获取 ax03 的轴位置,并用来add_axes()创建一个新轴。但似乎并没有预期对齐。据我观察,get_position()返回布局重新安排之前轴的位置。

注意:如果我分两部分执行代码,那么我当然可以获得位置。我想通过一次执行来实现它。

import matploltib.pyplot as plt

# Section 1
fig, axes = plt.subplots(2, 3, figsize=(7.2, 7.2/1.68), constrained_layout=True)
axes = axes.ravel()
ax01 = axes[0]
ax02 = axes[1]
ax03 = axes[2]
ax11 = axes[3]
ax12 = axes[4]
ax13 = axes[5]

# Section 2
pos = ax03.get_position() # get the original position
width = pos.x1 - pos.x0
height = pos.y1 - pos.y0


print(ax03.get_position())
ax = fig.add_axes([pos.x0, pos.y0, width, height])
print(ax.get_position())    
# it seems the position of ax is the postion before constrained is applied.
Run Code Online (Sandbox Code Playgroud)

这是一起执行第 1 部分和第 2 部分时得到的结果。职位信息:

Bbox(x0=0.6720588235294118,y0=0.53,x1=0.9000000000000001,y1=0.88) Bbox(x0=0.6720588235294118,y0=0.53,x1=0.9000000000000001,y1 =0.88)

在此输入图像描述

如果执行第 1 部分,然后执行第 2 部分,我得到:

Bbox(x0=0.7209572530864197,y0=0.5704676577986438,x1=0.9728583333333332,y1=0.9773075117370893) Bbox(x0=0.7209572530864197,y0=0。 5704676577986438, x1=0.9728583333333332, y1=0.9773075117370893)

如果我关闭constrained_layout:

fig, axes = plt.subplots(2, 3, figsize=(7.2, 7.2/1.68), 
constrained_layout=False)
axes = axes.ravel()
ax01 = axes[0]
ax02 = axes[1]
ax03 = axes[2]
ax11 = axes[3]
ax12 = axes[4]
ax13 = axes[5]
ax03.axis('off')

pos = ax03.get_position() # get the original position
width = pos.x1 - pos.x0
height = pos.y1 - pos.y0

print(ax03.get_position())
ax10 = fig.add_axes([pos.x0, pos.y0, width, height])
print(ax10.get_position())  
Run Code Online (Sandbox Code Playgroud)

Bbox(x0=0.6720588235294118,y0=0.53,x1=0.9000000000000001,y1=0.88) Bbox(x0=0.6720588235294118,y0=0.53,x1=0.9000000000000001,y1 =0.88)

上面的帖子是 相同constrained_layout=False

如何在一次执行中获取新布局的 ax03 位置?

Imp*_*est 8

每次绘制图形时都会实现约束布局。因此,您需要先绘制图形,然后才能获取其中轴的实际位置。

import matplotlib.pyplot as plt

fig, ((ax01, ax02, ax03),(ax11, ax12, ax13)) = plt.subplots(2, 3, figsize=(7.2, 7.2/1.68), 
                                                            constrained_layout=True)
# draw the figure to apply constrained_layout
fig.canvas.draw()

# Section 2
pos = ax03.get_position() # get the original position
print(pos)
ax = fig.add_axes([pos.x0, pos.y0, pos.width, pos.height])
print(ax.get_position())    

plt.show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

但请注意,一旦再次调整图形大小,位置又会变得错误。所以问题是,为什么这个职位对你来说很重要?如果目标是在现有轴之上创建一个新轴,则宁愿将其放入同一现有网格的相同位置,例如如下

import matplotlib.pyplot as plt

fig, ((ax01, ax02, ax03),(ax11, ax12, ax13)) = plt.subplots(2, 3, figsize=(7.2, 7.2/1.68), 
                                                            constrained_layout=True)

gs = ax03.get_gridspec()
ax = fig.add_subplot(gs[0,2], label="new_axes")

plt.show()
Run Code Online (Sandbox Code Playgroud)

然后,constrained_layout也适用于该轴,它们将始终位于彼此之上。

在此输入图像描述