Печать названий графиков при наведении на них - PullRequest
0 голосов
/ 27 января 2019

У меня есть 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()

Я следовал второму решению, упомянутому в этом посте. Он печатает имя графика, но, как я уже сказал, я хочу, чтобы он появлялся рядом с курсором мыши при наведении курсора . Я не мог понять это. Любая помощь будет оценена.

1 Ответ

0 голосов
/ 28 января 2019

Вы не использовали аннотацию из вашего примера ссылки. Просто добавив это в свой код и установив значение аннотации xy в значениях xdata и ydata вашего события при наведении, вы получите то, что ищете:

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()

...