代码:在给定的代码中,我想要将鼠标悬停在折线图上时注释文本中的实际 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)
顺便说一句,这是您在那里编写的一些不错的代码!
关于python - 在给定的提及代码中,我想要将鼠标悬停在线图上时 X 和 Y 的实际值,我该怎么办?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50522230/