0

I'm trying to write something that lets me remove lines by clicking on a matplotlib plot. I'll later try deleting the lines by clicking on them.

For now, I've simplified the code as much as I can, but I still can't figure it out. Both lines remain on the plot, and if I click twice, I get the message:

"ValueError: list.remove(x): x not in list".

The remove command works if I put it outside of onclick(event), and print statements work when I put them inside of onclick(event).

But I can't get any farther than that. I've also tried clearing the entire plot with plt.gca(), but that doesn't seem to do anything.

Clearly something basic I don't understand, so I was hoping someone could clarify what I'm doing wrong.

import matplotlib.pyplot as plt
import numpy as np
    
xdata = np.arange(0,20,1)
ydata1 = np.arange(0,40,2)
ydata2 = np.arange(0,80,4)
    
fig,ax = plt.subplots()
line1, = ax.plot(xdata, ydata1)
line2, = ax.plot(xdata, ydata2)
          
def onclick(event):
    line1.remove()   #error on second click
    
plt.gcf().canvas.mpl_connect('button_press_event', onclick)
2
  • 1
    Can you try including plt.draw() in your onclick() function to redraw the figure? https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.draw.html Commented Jan 31, 2021 at 12:39
  • Thank you. This appears to solve the problem. Commented Feb 1, 2021 at 23:56

1 Answer 1

2

If you need to just delete lines and you don't care about the order. You can use this:

def onclick(event):

    plt.gca().lines[-1].remove()

If you require to delete a specific line:

fig,ax = plt.subplots()
line1, = ax.plot(xdata, ydata1, picker=5)
line2, = ax.plot(xdata, ydata2, picker=5)
          
def onclick(event):
    thisline = event.artist
    thisline.remove()
    
plt.gcf().canvas.mpl_connect('pick_event', onclick)

You can read more about it: https://matplotlib.org/3.1.1/gallery/event_handling/pick_event_demo.html

Sign up to request clarification or add additional context in comments.

1 Comment

I was not able to get either of these code samples to work, but thank you for the link. I will read that and see if I can understand it better.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.