python - 如何在 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()
输出:
我想知道是否有一种内置方法可以将标签添加到箭头并相应地对齐其标签?如果没有,最简单的方法是什么?
解决方案
使用起来可能更容易阅读,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 个点。
推荐阅读
- android - TypeError: Network request failed only on POST method
- ios - 训练图像的纵横比是否会影响 Turi Create 创建的对象检测模型?
- recursion - DrRacket 计划合同违反预期数量
- python - Raspberry Pi 未按预期显示带有屏幕的 pygame
- python - ahtzee 上节得分
- matlab - 重写 medfilt1 MATLAB 函数以支持 codegen
- javascript - 无法在 Cheerio 中显示选择器内容
- python - 如何获取 Gmail API 消息的文本/纯文本部分
- ansible - Ansible:如何获取ansible连接的主机的接口名称?
- javascript - 如何为 Firebase 实时数据库创建增量 ID?