You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Matplotlib:如何让文本与Axes位置动态对齐,不受tight_layout影响

解决Matplotlib文本注释跟随Axes动态位置的问题

要让Figure上的文本注释始终跟随Axes的最终位置(包括tight_layout或其他布局调整后的位置),可以通过两种直接可行的方案实现:

方案1:绑定绘制事件动态更新位置

监听画布的draw_event事件,每次绘制时重新获取Axes的最新位置并同步更新文本坐标,适配所有会改变Axes位置的操作:

import matplotlib.pyplot as plt

def update_text_positions(event):
    ax_bbox = ax.get_position()
    txt_left.set_x(ax_bbox.x0)
    txt_right.set_x(ax_bbox.x1)

fig, ax = plt.subplots()
# 先创建文本对象,初始位置不影响后续动态更新
txt_left = fig.text(0, 0.01, "left text", ha="left")
txt_right = fig.text(1, 0.01, "right text", ha="right")

# 绑定绘制事件,每次绘图前自动更新位置
fig.canvas.mpl_connect('draw_event', update_text_positions)

fig.tight_layout()
plt.show()

方案2:利用坐标变换直接绑定位置

通过混合坐标变换,将文本的x坐标与Axes的边缘(归一化坐标)绑定,y坐标保留在Figure坐标系,无需额外更新逻辑:

import matplotlib.pyplot as plt
from matplotlib.transforms import blended_transform_factory

fig, ax = plt.subplots()
# 创建混合变换:x轴用Axes归一化坐标,y轴用Figure归一化坐标
trans = blended_transform_factory(ax.transAxes, fig.transFigure)

# 直接用Axes的左边缘(0)、右边缘(1)作为x坐标,固定y位置
fig.text(0, 0.01, "left text", ha="left", transform=trans)
fig.text(1, 0.01, "right text", ha="right", transform=trans)

fig.tight_layout()
plt.show()

内容的提问来源于stack exchange,提问作者Snaptraks

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 17:29:56