如何修正Matplotlib中ax.annotate的坐标偏移问题
解决matplotlib中ax.annotate双向箭头与坐标不对齐的问题
问题描述:使用ax.annotate添加|-|样式的双向箭头时,指定的x起点0和终点200未被准确对齐,实际箭头起点大于0、终点小于200。
原因分析
matplotlib中arrowprops的默认参数里,shrinkA和shrinkB默认值为0.05(即箭头两端会向内收缩5%的长度),再加上|-|箭头的竖线帽(cap)会占用部分空间,导致箭头线段无法完全贴合指定的坐标点。
解决方案
在arrowprops中显式设置shrinkA=0和shrinkB=0,关闭箭头的自动收缩,确保箭头线段与指定坐标精准对齐。
修改后的代码
import numpy as np import matplotlib.pyplot as plt x_start = 0 x_end = 200 y_start = 20 y_end = 20 fig, ax = plt.subplots(figsize=(5,5),dpi=600) ax.plot(np.asarray([i for i in range(0,1000)])) ax.annotate('', xy=(x_start, y_start), xytext=(x_end, y_end), xycoords='data', textcoords='data', arrowprops={'arrowstyle': '|-|', 'shrinkA': 0, 'shrinkB': 0}) plt.show()
补充说明
如果需要调整箭头竖线帽的大小,可以在arrowprops中添加mutation_scale参数,比如mutation_scale=10来放大或缩小帽的尺寸,同时保持箭头线段与指定坐标的对齐状态。
内容的提问来源于stack exchange,提问作者Johnny Tam
相关产品推荐
相关产品推荐

