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?
答案 0 :(得分:6)
As the documentation states fill_between
returns a PolyCollection
instance. Collections are stored in ax.collections
. So
ax.collections.pop()
should 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
or ax.collections
. You could save a reference to the object so you know which one to remove:
fill_between_col = ax.fill_between(x, 0, y)
and then to remove:
ax.collections.remove(fill_between_col)
EDIT: Yet another method, and probably the best one: All the artists have a method called remove
which does exactly what you want:
fill_between_col.remove()