python - 在给定的提及代码中,当鼠标悬停在线图上时,我想要 X 和 Y 的实际值,我该怎么办?
问题描述
代码:在给定的代码中,当将鼠标悬停在折线图上时,我想要注释文本中的实际 X 和 Y 值。所以我做了什么改变请帮助我。
import matplotlib.pyplot as plt
import numpy as np; np.random.seed(1)
x = np.sort(np.random.rand(15))
y = np.sort(np.random.rand(15))
names = np.array(list("ABCDEFGHIJKLMNO"))
fig,ax = plt.subplots()
line, = plt.plot(x,y, marker="o")
annot = ax.annotate("", xy=(0,0), xytext=(-20,20),textcoords="offset points",
bbox=dict(boxstyle="round", fc="w"),
arrowprops=dict(arrowstyle="->"))
annot.set_visible(False)
def update_annot(ind):
x,y = line.get_data()
annot.xy = (x[ind["ind"][0]], y[ind["ind"][0]])
text = "{}, {}".format(" ".join(list(map(str,ind["ind"]))),
" ".join([names[n] for n in ind["ind"]]))
annot.set_text(text)
annot.get_bbox_patch().set_alpha(0.4)
def hover(event):
vis = annot.get_visible()
if event.inaxes == ax:
cont, ind = line.contains(event)
if cont:
update_annot(ind)
annot.set_visible(True)
fig.canvas.draw_idle()
else:
if vis:
annot.set_visible(False)
fig.canvas.draw_idle()
fig.canvas.mpl_connect("motion_notify_event", hover)
plt.show()
解决方案
我不太确定我是否正确理解了您的问题,但如果您真的只想要注释内点的坐标,我会将update_annot()
函数更改为如下所示:
def update_annot(ind):
x,y = line.get_data()
x0 = x[ind["ind"][0]]
y0 = y[ind["ind"][0]]
annot.xy = (x0, y0)
text = "{}, {}: ({:.2g},{:.2g})".format(
" ".join(list(map(str,ind["ind"]))),
" ".join([names[n] for n in ind["ind"]]),
x0,y0,
)
annot.set_text(text)
annot.get_bbox_patch().set_alpha(0.4)
顺便说一句,这是您在那里编写的一些不错的代码!
推荐阅读
- palantir-foundry - 为什么我不应该在我的 Python 转换中使用 collect()?
- spring-boot - 在不启动服务器的情况下使用 Spring 应用程序属性
- apache-nifi - 如何在 NiFi 处理器中重新加载外部配置数据
- php - 上传图片或创建新帖子时,Wordpress 中的 net::ERR_CONNECTION_RESET
- cllocationmanager - iOS 14 - 当精确位置权限被拒绝时,如何让 iBeacon 唤醒应用程序?
- php - 指示作曲家在模棱两可时使用不同的类
- python - 您如何重新组织数据框的数据框,以便只有 1 个最终数据框?
- javascript - JS getElementsByName 以部分 id 作为变量
- angular - Firebase:使用另一个检索数据检索数据
- autodesk-forge - 为什么查看器使用 developer-dev.api.autodesk.com 而不是 developer.api.autodesk.com 会导致令牌无效?