我创建了一个 (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.
这是同时执行第 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())
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 位置?
最佳答案
Constrained Layout 会在每次绘制图形时执行。因此,您需要先绘制图形,然后才能获得其中轴的实际位置。
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()
但是请注意,一旦您再次调整图形的大小,位置又会变得错误。所以问题是,为什么这个职位对你很重要?如果目标是在现有轴的顶部创建一个新轴,那么人们宁愿将其放入相同现有网格的相同位置,例如如下
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()
然后,constrained_layout
也适用于该轴,它们将始终在彼此之上。
https://stackoverflow.com/questions/54584747/
相关文章:
python - 如何将 Base64 图像字符串从 Flask Python 代码传递到 HTML
reactjs - React.HTMLProps
python - 如何展平嵌套模型? (keras 函数式 API)
typescript - 从 Flow 迁移到 Typescript : $Keys equival
python-3.x - 如何从 gensim 模块导入 WordEmbeddingSimilari
python - 如何使用 django import-export 在 admin 中订购导入字段