Matplotlib - How to remove a specific line or curve

Edit: tacaswell's answer is better than mine

I keep my answer anyhow for the records (and because the upvotes are nice :wink:)


If you don't want to save the reference of all the lines explicitly but you know the index of the line that you want to remove, you can use the fact that maptplotlib stores them for you.

self.axes.lines

is a list of matplotlib.lines.Line2D. So to remove, e.g., the second line drawn you can do

self.axes.lines[1].remove()

Almost all of the plotting functions return a reference to the artist object created ex:

ln, = plot(x, y)  # plot actually returns a list of artists, hence the ,
im = imshow(Z)

If you have the reference you can remove an artist via the remove (doc) function ex:

ln.remove()
im.remove()