Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object-oriented access to fill_between shaded region in matplotlib

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?

like image 577
IanRoberts Avatar asked Mar 16 '23 17:03

IanRoberts


1 Answers

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()
like image 121
hitzg Avatar answered Mar 18 '23 06:03

hitzg