2017-05-11 3 views
0

Ich möchte anzeigen Text neben dem Cursor, wie es durch ein von Matplotlib generiert Plot bewegt.matplotlib: Textposition dynamisch ändern

Ich weiß, wie die Mausbewegungsereignisse zu bekommen, aber wie ich die Position des dynamisch Element Text ändern?

Der folgende Code zeigt, wie eine Linie in Abhängigkeit von der Position des Cursors positionieren:

import matplotlib.pyplot as plt 

fig = plt.figure() 
ax = fig.add_subplot(111) 
line = ax.plot([0, 1], [0,1])[0] 

def on_mouse_move(event): 
    if None not in (event.xdata, event.ydata): 
     # draws a line from the center (0, 0) to the current cursor position 
     line.set_data([0, event.xdata], [0, event.ydata]) 
     fig.canvas.draw() 

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

Wie kann ich etwas tun ähnlich mit Text? Ich habe versucht text.set_data, aber das hat nicht funktioniert.

+0

Siehe http://stackoverflow.com/questions/42446307/update-annotations-in-matplotlib-using-buttons – ImportanceOfBeingErnest

Antwort

1

Nach einigem Versuch und Irrtum fand ich die Lösung so einfach wie text.set_position((x, y)).

Siehe das folgende Beispiel unter:

import matplotlib.pyplot as plt 

fig = plt.figure() 
ax = fig.add_subplot(111) 
text = ax.text(1, 1, 'Text') 

def on_mouse_move(event): 
    if None not in (event.xdata, event.ydata): 
     text.set_position((event.xdata, event.ydata)) 
     fig.canvas.draw() 

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