首页 > 解决方案 > 如何在 matplotlib.pyplot.arrow 旁边放置一个文本标签?

问题描述

我可以在 Matplotlib 3.4.3 中的箭头旁边手动添加标签。通过估计它的位置。

import matplotlib.pyplot as plt
W, H = 2, 3
offsetX = 0.1*W

arrow_style = {"head_width":0.1, "head_length":0.2, "color":"k"}
plt.arrow(x=0, y=0, dx=W, dy=H, **arrow_style)
plt.text(x=W/2+offsetX, y=H/2, s="U")
plt.show()

输出:

在此处输入图像描述

我想知道是否有一种内置方法可以将标签添加到箭头并相应地对齐其标签?如果没有,最简单的方法是什么?

标签: pythonmatplotlib

解决方案


使用起来可能更容易阅读,axes.annotate但在某种程度上等同于您编写的代码:

import matplotlib.pyplot as plt

W, H = 2, 3
arrow_style = {
    "head_width": 0.1,
    "head_length": 0.2,
    "color":"k"
}

plt.arrow(x=0, y=0, dx=W, dy=H, **arrow_style)
plt.annotate('U',
             xy=(W/2, H/2),
             xytext=(10, -10),
             textcoords='offset points')
plt.show()

在哪里:

  • xy是要标注的点 (x, y)
  • xytext是放置文本的位置 (x, y)(默认值:xy)。坐标系由文本坐标确定。
  • textcoords是给定 xy 的坐标系(“偏移点”表示从 xy 值偏移的点数)

所以简而言之,箭头中心向右 10 个点,向下 10 个点。


推荐阅读