How to remove line lines created with Mouse Over Event in Matplolib?

I created a vertical and horizontal line in the plot with the mouseover event. These lines intend to help the user choose where to click on the plot. My problem is that when the mouse moves around the plot, the lines drawn earlier do not disappear. Can someone explain to me how to do this?
I used ax.lines.pop () after drawing a graph inside the OnOver function, but this did not work.

This is the code I'm using.

from matplotlib import pyplot as plt import numpy as np fig = plt.figure() ax = fig.add_subplot(111) ax.plot(np.random.rand(10)) def OnClick(event): print 'button=%d, x=%d, y=%d, xdata=%f, ydata=%f'%( event.button, event.x, event.y, event.xdata, event.ydata) def OnOver(event): x = event.xdata y = event.ydata ax.axhline(y) ax.axvline(x) plt.draw() did = fig.canvas.mpl_connect('motion_notify_event', OnOver) #iii = fig.canvas.mpl_disconnect(did) # get rid of the click-handler cid = fig.canvas.mpl_connect('button_press_event', OnClick) plt.show() 

Thanks in advance for your help. Ivo

+4
source share
1 answer

You need to delete lines that you do not want. for instance

 def OnOver(event): if len(ax.lines) > 1 : ax.lines[-1].remove() ax.lines[-1].remove() ax.axhline(event.ydata) ax.axvline(event.xdata) plt.draw() 

It is not reliable and effective.

Instead of constantly creating and destroying strings, we can simply draw them once and continue updating them.

 lhor = ax.axhline (0.5) lver = ax.axvline (1) def OnOver2(event): lhor.set_ydata(event.ydata) lver.set_xdata(event.xdata) plt.draw() 

Here I used global variables and drew a β€œcrosshair” in the viewport to begin with. Instead, it could be pulled beyond it or not made visible, but you get this idea.

I do not know the best way to achieve this.

+10
source

Source: https://habr.com/ru/post/1493042/


All Articles