Why do I need to remove patches twice from my matplotlib Axes in order to remove them all?

Viewed 115

I have a matplotlib Axes object self.a defined on a matplotlib canvas object self.fold_canvas. During its construction, at some point I plot a bunch of transparent boxes on the plot, via

self.a.axvspan(bins[lower],bins[upper],color=palette[i],alpha=0.3, gid='foldstate')

Later, I want to get rid of them. I do this using the loop:

for p in self.a.patches:
    if p.get_gid() == 'foldstate':
        p.remove()
self.fold_canvas.draw()

For some reason, this loop removes all but one of the axvspan instances. If I then do it again, ie

for p in self.a.patches:
    if p.get_gid() == 'foldstate':
        p.remove()
for p in self.a.patches:
    if p.get_gid() == 'foldstate':
        p.remove()
self.fold_canvas.draw()

it works as intended, and all of the axvspans are removed.

Why do I need to do the loop twice to remove all of them?

EDIT: it appears that labelling them all with unique gid fixes the problem, so it may relate to an internal issue when multiple patches share the same gid.

1 Answers

Since this hasn't been touched: there seems to be an issue internal to matplotlib where gid needs to be unique for every labelled item. It seems to cause some silent failures if you reuse a gid anywhere.

Related