Skip to content Skip to sidebar Skip to footer

Python Matplotlib Add And Remove Text To Figure Using Button Events

I'm trying to add text to a graph at the location of the mouse pointer when button_press_event is called and remove it when button_release_event is called. I have successfully ad

Solution 1:

Assuming you should use it in a class and refer to the following txt as self.txt I use global here for sake of ease:

txt = None

def onclick(event):
    global txt
    txt = plt.text(event.xdata, event.ydata, 'TESTTEST', fontsize=8)
    fig.canvas.draw()

def offclick(event):
    txt.remove()
    fig.canvas.draw()

fig.canvas.mpl_connect('button_press_event', onclick)
fig.canvas.mpl_connect('button_release_event', offclick) 

plt.show()

Post a Comment for "Python Matplotlib Add And Remove Text To Figure Using Button Events"