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)
plt.draw()in youronclick()function to redraw the figure?https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.draw.html