Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib: Removing all artists and lines

Let's say I make a series of AnnotationBbox'es in matplotlib through a for loop, like this:

 for city in cities:
     x, y = self.map(city[1], city[0])

     ab = AnnotationBbox(imagebox, [x,y],
                                xybox=(0, 0),
                                xycoords='data',
                                boxcoords="offset points",
                                frameon=False)
            self.axes.add_artist(ab)
            self.locationImages.append(ab)

In this example, I've created a series of AnnotationBBoxes, and stored them in a list called self.locationImages. Then I go through the self.locationImages in a loop, and remove each one by doing this:

    for image in self.locationImages:
        image.remove()

Is there a way to remove all the artists, without having to go through a loop? Or to remove all artists, and lines completely, without having to remove the axes or the figure?

I'm plotting points on a map, and I need the map to stay. I'm doing zoom ins and outs, but during zoom ins and outs, I need to remove everything and replot. I'm working with a large data set and doing iterations is an expensive action

like image 533
Lee Torres Avatar asked Mar 29 '26 20:03

Lee Torres


1 Answers

I believe a pretty nasty solution would be to do the following:

# remove all artists
while ax.artists != []:
  ax.artists[0].remove()

#remove all lines
while ax.lines != []:
  ax.lines[0].remove()

This works for dynamic plots (e.g. animation or ipywidgets). But if you tell there has to be a better way -- I'd definitely agree :)

like image 83
hayk Avatar answered Apr 02 '26 22:04

hayk