将鼠标悬停在图形上以打印图形名称

时间:2019-01-27 00:30:50

标签: python-3.x matplotlib hover

我有3个文本文件,这些文件具有要在单个图中绘制的特定名称。这是我的文件:

111.txt

0 0
1 1
2 2
3 3

222.txt

0 0
1 3
2 6
3 9

333.txt

0 0
1 5
2 10
3 15

当我在这些行上移动鼠标光标时,我希望图形名称(不带' .txt ')出现在鼠标光标旁边。这是我尝试过的:

import matplotlib.pyplot as plt
import os

def GetFiles():
    return [file for file in os.listdir('/home/myfolder') if 
file.endswith(".txt")]

#Get All Available file in current directry
textfiles=GetFiles()

#Storing the names of the files without .txt in an array
s=[]
for j in range (len(textfiles)):
    without_txt = textfiles[j].replace(".txt", "")
    s.append(without_txt)
#print (s)

fig = plt.figure()
plot = fig.add_subplot(111)

# plot the text files in the folder
for i in range(len(s)):
    plt.plotfile(str(textfiles[i]), delimiter=' ', cols=(0, 1), 
linestyle='-', linewidth=2, color='b', newfig=False,gid=s[i])

#plt.gca().invert_xaxis()

def on_plot_hover(event):
    for curve in plot.get_lines():
        if curve.contains(event)[0]:
            print "over %s" % curve.get_gid()  

fig.canvas.mpl_connect('motion_notify_event', on_plot_hover)
plt.show()

我遵循了this帖子中提到的第二种解决方案。它会打印图形的名称,但正如我所说,我希望其在悬停时显示在鼠标光标旁边。我不知道。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

您没有使用示例链接中的注释。只需将其添加到您的代码中,并将注释的xy值设置为悬停事件的xdataydata值,便可以找到所需的内容:

import matplotlib.pyplot as plt
import os

def GetFiles():
    return [file for file in os.listdir('/home/myfolder') if 
file.endswith(".txt")]

#Get All Available file in current directry
textfiles=GetFiles()

#Storing the names of the files without .txt in an array
s=[]
for j in range (len(textfiles)):
    without_txt = textfiles[j].replace(".txt", "")
    s.append(without_txt)

fig = plt.figure()
plot = fig.add_subplot(111)

annot = plot.annotate("", xy=(2,2), xytext=(10,10),textcoords="offset points",
                    bbox=dict(boxstyle="round", fc="w"))
annot.set_visible(False)

# plot the text files in the folder
for i in range(len(s)):
    plt.plotfile(str(textfiles[i]), delimiter=' ', cols=(0, 1), 
linestyle='-', linewidth=2, color='b', newfig=False,gid=s[i])

def update_annot(x,y, text):
    annot.set_text(text)
    annot.xy = [x,y]

def on_plot_hover(event):
    vis = annot.get_visible()
    for curve in plot.get_lines():
        if curve.contains(event)[0]:
            print("over %s" % curve.get_gid())
            update_annot(event.xdata, event.ydata, curve.get_gid())
            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', on_plot_hover)
plt.show()