4

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?

hitzg
  • 12,133
  • 52
  • 54
IanRoberts
  • 2,846
  • 5
  • 26
  • 33

1 Answers1

7

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()
hitzg
  • 12,133
  • 52
  • 54
  • Thanks for the useful comment. Trying to manually pop them by name is a good idea, although it doesn't seem to work. If I do: my_line = ax.plot(x,y); my_line.pop() This does not remove the line (even after forcing a redraw of the canvas using draw()) – IanRoberts Jun 15 '15 at 14:45
  • That is not what I suggested. You can't call `pop()` on an artist you have to call: `ax.lines.remove(my_line)`. And by the way: `ax.plot` always returns a list (since you can plot multiple lines at once), so you should use `my_line = ax.plot(x,y)[0]` – hitzg Jun 15 '15 at 14:55