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

当x、y值大于1时adjustText标注定位异常问题求助

解决adjustText在大坐标值下标注错乱的问题

当你的坐标值远大于1时,adjustText出现标注位置错乱,本质是因为没有指定它对应的绘图轴对象,导致它用了默认的全局坐标系计算布局,和当前轴的范围不匹配。小数值时坐标范围接近matplotlib默认的0-1区间,所以不会出问题。

修正方案:

  • 绑定标注到当前绘图轴:用ax.text替代plt.text生成标注
  • 调用adjust_text时必须传入ax参数,指定当前的轴对象
  • 可选:如果布局仍不理想,可调整expand_points或expand_text参数,扩大标注与数据点的间距

修改后的完整代码:

import matplotlib.pyplot as plt
from adjustText import adjust_text

fig, ax = plt.subplots()
x = [10,20,30,40,50,60,70,80,90,100]
y = [11,12,13,14,15,16,17,18,19,20]
ax.plot(x, y)
ax.set_title('Peaks')
ax.set_xlabel('X')
ax.set_ylabel('Y')

annotations = []
for i in range(len(x)):
    # 使用ax.text绑定标注到当前轴
    annotations.append(ax.text(x[i], y[i], f"Label{i}"))

# 关键:指定ax参数,确保基于当前轴的坐标计算布局
adjust_text(annotations, 
            ax=ax,
            arrowprops=dict(arrowstyle="-", color='k', lw=0.5))

plt.show()

这样修改后,adjustText就能基于当前轴的实际坐标范围正确计算标注位置,避免错乱。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 08:35:07