开发者

python matplotlib add and remove text to figure using button events

开发者 https://www.devze.com 2023-02-23 07:16 出处:网络
I\'m trying to add text to a graph at the location of the mouse pointerwhen button_press_event is called and remove it when button_release_event is called.I have successfully added the text but I can

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 added the text but I can not get it to erase. Here is part of the code I used:

def onclick(event):
    print 'you pressed', event.button, event.xdata, event.ydata
    plt.text(event.xdata, event.ydata, 'TESTTEST', fontsize=8)
    fig.canvas.draw()

def offclick(event):
    print 'you released', event.button, event.xdata, event.ydata
    #not sure what to put here
    #I tried:
    #plt.text(event.xdata, ev开发者_运维知识库ent.ydata, '')
    fig.canvas.draw()

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

plt.show()


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

精彩评论

暂无评论...
验证码 换一张
取 消