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

如何在Matplotlib中将xytext设为annotate箭头的起点?

解决Matplotlib注释箭头起点精准控制问题

可以通过调整annotate方法中arrowprops的relpos参数,结合文本的对齐方式,实现让箭头从xytext指定的坐标点出发,无需拆分多个注释实例。

原理说明

默认情况下,箭头起点是注释文本边界框(bbox)的中心,对应relpos=(0.5, 0.5)。我们可以通过修改relpos的值,将箭头起点定位到文本bbox的锚点位置(也就是xytext对应的位置):

  • 文本水平对齐为ha='left'时,锚点在bbox左边缘中心,设置relpos=(0, 0.5)
  • 文本水平对齐为ha='right'时,锚点在bbox右边缘中心,设置relpos=(1, 0.5)
  • 文本垂直对齐为va='top'时,锚点在bbox顶部中心,设置relpos=(0.5, 1)
  • 文本垂直对齐为va='bottom'时,锚点在bbox底部中心,设置relpos=(0.5, 0)

修改后的示例代码

import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot()
    
ax.plot(0, 0, linestyle='none', marker='o', markersize=4, c='k')
    
# 调整relpos参数,让箭头从xytext位置(文本左边缘中心)出发
ax.annotate('annotation', [0, 0], xytext=[1, 1],
            ha='left', va='center',
            bbox=dict(pad=0, fc='none', ec='k'),
            arrowprops=dict(arrowstyle='-', relpos=(0, 0.5)))
    
ax.plot(1, 1, linestyle='none', marker='o', markersize=4, c='red')
    
ax.annotate('desired\nanchorpoint', [1, 1], xytext=[0, 1],
            ha='center', va='center',
            arrowprops=dict(arrowstyle='->', shrinkB=5))
    
ax.set_xlim([-1, 2])
ax.set_ylim([-1, 2])

plt.show()

效果验证

修改后,箭头会精准从xytext=(1,1)的红色圆点位置出发,连接到目标点(0,0),完全匹配你想要的锚点效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 04:39:34