I'm trying to get access to the shaded region of a matplotlib plot, so that I can remove it without doing plt.cla()
[since cla()
clears the whole axis including axis label too]
If I were plotting I line, I could do:
import matplotlib.pyplot as plt
ax = plt.gca()
ax.plot(x,y)
ax.set_xlabel('My Label Here')
# then to remove the line, but not the axis label
ax.lines.pop()
However, for plotting a region I execute:
ax.fill_between(x, 0, y)
So ax.lines
is empty.
How can I clear this shaded region please?
As the documentation states
fill_between
returns aPolyCollection
instance. Collections are stored inax.collections
. Soshould do the trick.
However, I think you have to be careful that you remove the right thing, in case there are multiple objects in either
ax.lines
orax.collections
. You could save a reference to the object so you know which one to remove:and then to remove:
EDIT: Yet another method, and probably the best one: All the artists have a method called
remove
which does exactly what you want: