首页 > 解决方案 > 在给定的提及代码中,当鼠标悬停在线图上时,我想要 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()

标签: pythonmatplotlib

解决方案


我不太确定我是否正确理解了您的问题,但如果您真的只想要注释内点的坐标,我会将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)

顺便说一句,这是您在那里编写的一些不错的代码!


推荐阅读