我有一个包含 6 个子图的网格。最后一个子图是正方形的。我需要将其向左移动,以便其左侧 y 轴与其上方绘图的 y 轴完全对齐。我知道我可以获取并设置 Bbox 参数,但我无法将其移向正确的方向。无论我增加还是减少 x1 和 x2,它似乎总是向右移动。
import matplotlib.pyplot as plt
fig, axs = plt.subplots(2, 3)
fig.tight_layout(pad=3.0)
fig.set_figwidth(30)
fig.set_figheight(15)
axs[1, 2].set_aspect('equal')
print(axs[1, 2].get_position())
打印命令返回:
Bbox(x0=0.7620938740079364, y0=0.16765873015873023, x1=0.8925502232142856, y1=0.4285714285714286)
最佳答案
.get_position()
方法确实返回给定轴的边界框。这个想法是使用方轴正上方的轴的 Bbox
来将它们与其对齐。这可以通过以下方式完成:
import matplotlib.pyplot as plt
# the figure size can be set directly from here
# I used smaller figure size than in your example for visibility
fig, axs = plt.subplots(2, 3, figsize=(15, 7))
fig.tight_layout(pad=3.0)
axs[1, 2].set_aspect('equal')
# extract positions of square and above axes
p02 = axs[0, 2].get_position()
p12 = axs[1, 2].get_position()
# make square axes with left position taken from above axes, and set position
p12 = [p02.x0, p12.y0, p12.width, p12.height]
axs[1, 2].set_position(p12)
plt.show()
结果是:
关于python - Matplotlib。将子图与 Bbox 对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64066011/