python - 在给定的提及代码中,我想要将鼠标悬停在线图上时 X 和 Y 的实际值,我该怎么办?

标签 python matplotlib

代码:在给定的代码中,我想要将鼠标悬停在折线图上时注释文本中的实际 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/

相关文章:

python - 使用接口(interface)在 Windows 上将 python 脚本作为服务运行

python - 从 python plot (matplotlib) 中找到相应 x 的 y 值

python matplotlib 用元组(x,y,值)制作热图

python - 在 matplotlib 中的垂直线旁边添加文本

轴 ('square' ) 和 set_xlim 之间的 python 相互作用

python - PyQt 关闭 QMessageBox

python - @classmethod 的位置

python - 如何处理 DELETE 语句删除任何行的失败?

python - 转置子列表中的元素

python - Basemap能否绘制城市级别的详细海岸线?