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.