在matplotlib中以对象为导向访问fill_between阴影区域

Ian*_*rts 3 python plot matplotlib fill

我正试图访问matplotlib图的阴影区域,以便我可以删除它而不用plt.cla()[因为cla()清除包括轴标签在内的整个轴]

如果我正在策划我的行,我可以这样做:

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()
Run Code Online (Sandbox Code Playgroud)

但是,为了绘制我执行的区域:

ax.fill_between(x, 0, y)
Run Code Online (Sandbox Code Playgroud)

所以ax.lines是空的.

我该如何清除这个阴影区域?

hit*_*tzg 6

由于文档状态fill_between返回一个PolyCollection实例.集合存储在ax.collections.所以

ax.collections.pop()
Run Code Online (Sandbox Code Playgroud)

应该做的伎俩.

但是,我认为你必须要小心,你删除了正确的事情,万一有在任多个对象ax.linesax.collections.您可以保存对该对象的引用,以便您知道要删除哪一个:

fill_between_col = ax.fill_between(x, 0, y)
Run Code Online (Sandbox Code Playgroud)

然后删除:

ax.collections.remove(fill_between_col)
Run Code Online (Sandbox Code Playgroud)

编辑:另一种方法,可能是最好的方法:所有的艺术家都有一个方法叫做remove你想做的正是:

fill_between_col.remove()
Run Code Online (Sandbox Code Playgroud)