如何在matplotlib.pyplot.arrow旁添加并自动对齐文本标签
Matplotlib箭头自动对齐标签实现方案
内置方法说明
Matplotlib 3.4.3版本没有提供直接为plt.arrow添加自动对齐标签的独立内置接口,不过可以通过自带的annotate接口同时实现箭头绘制+标签自动对齐的需求,不需要手动估算标签位置。
最简实现方案
annotate接口原生支持同时定义箭头样式、标签内容和对齐规则,会自动适配箭头位置完成排版,示例代码如下:
import matplotlib.pyplot as plt W, H = 2, 3 plt.annotate( text='U', # 标签内容 xy=(W, H), # 箭头终点坐标 xytext=(0, 0), # 箭头起点坐标 arrowprops={"head_width":0.1, "head_length":0.2, "color":"k"}, ha='center', va='center' # 标签居中对齐到箭头中间位置 ) plt.xlim(-0.5, W+0.5) plt.ylim(-0.5, H+0.5) plt.show()
如果需要保留plt.arrow的调用习惯,也可以封装通用工具函数自动计算标签位置,无需每次手动估算偏移:
import matplotlib.pyplot as plt import math def add_arrow_with_label(x, y, dx, dy, label, side_offset=0.1, **arrow_kwargs): # 绘制箭头 plt.arrow(x, y, dx, dy, **arrow_kwargs) # 自动计算箭头中点 mid_x, mid_y = x + dx/2, y + dy/2 # 计算箭头法向量实现侧偏移 if dx == 0 and dy == 0: offset_x, offset_y = 0, 0 else: norm = math.hypot(dx, dy) offset_x = -dy * side_offset / norm offset_y = dx * side_offset / norm plt.text(mid_x + offset_x, mid_y + offset_y, label, ha='center', va='center') # 调用示例 arrow_style = {"head_width":0.1, "head_length":0.2, "color":"k"} add_arrow_with_label(x=0, y=0, dx=2, dy=3, label="U", side_offset=0.15, **arrow_style) plt.xlim(-0.5, 2.5) plt.ylim(-0.5, 3.5) plt.show()
内容的提问来源于stack exchange,提问作者Iyach tharwa nambarek
相关产品推荐
相关产品推荐

