0

I have 3 text files with specific names that I want to plot in a single figure. Here are my files:

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

I want the names of the graphs (without '.txt') to apprear next to the mouse cursor when I move the mouse cursor on these lines. This is what I have tried:

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

I followed the second solution mentioned in this post. It prints the name of the graph but as I said I want it to appear next to the mouse cursor while hovering. I could not figure it out. Any help would be appreciated.

Leo
  • 479
  • 2
  • 6
  • 16

1 Answers1

1

You didn't use the annotation from your example link. Just adding this to your code and setting the annotation's xy value to the xdata and ydata values of your hover event gets you what you are looking for:

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

Freya W
  • 487
  • 3
  • 11
  • Thanks for your help. – Leo Jan 28 '19 at 16:58
  • @Leo, as a side note, as I learned from [this answer](https://stackoverflow.com/a/54403514/10944175) you should look into plotting using something different from `plotfile`: "once you want to make significant changes to figure or axes, best do not rely on `plotfile`" – Freya W Jan 30 '19 at 10:14