这是一个很长的解释,是我为我的一个同事打的。我认为在这里也会有所帮助。不过,请耐心等待。我谈到了你在最后遇到的真正问题。就像预告片一样,这是一个额外引用您的 Line2D 对象的问题。
警告:在我们深入之前还有一点需要注意。如果您使用 IPython 来测试这一点,IPython 会保留自己的引用,并且并非所有引用都是弱引用。因此,在 IPython 中测试垃圾收集不起作用。它只会使事情变得混乱。
好的,我们开始吧。每个matplotlib 对象(Figure、Axes 等)通过各种属性提供对其子艺术家的访问。下面的例子很长,但应该很有启发性。
我们首先创建一个Figure 对象,然后向该图形添加一个Axes 对象。注意ax 和fig.axes[0] 是同一个对象(同一个id())。
>>> #Create a figure
>>> fig = plt.figure()
>>> fig.axes
[]
>>> #Add an axes object
>>> ax = fig.add_subplot(1,1,1)
>>> #The object in ax is the same as the object in fig.axes[0], which is
>>> # a list of axes objects attached to fig
>>> print ax
Axes(0.125,0.1;0.775x0.8)
>>> print fig.axes[0]
Axes(0.125,0.1;0.775x0.8) #Same as "print ax"
>>> id(ax), id(fig.axes[0])
(212603664, 212603664) #Same ids => same objects
这也扩展到轴对象中的线:
>>> #Add a line to ax
>>> lines = ax.plot(np.arange(1000))
>>> #Lines and ax.lines contain the same line2D instances
>>> print lines
[<matplotlib.lines.Line2D object at 0xce84bd0>]
>>> print ax.lines
[<matplotlib.lines.Line2D object at 0xce84bd0>]
>>> print lines[0]
Line2D(_line0)
>>> print ax.lines[0]
Line2D(_line0)
>>> #Same ID => same object
>>> id(lines[0]), id(ax.lines[0])
(216550352, 216550352)
如果你使用上面的方法调用plt.show(),你会看到一个包含一组轴和一条线的图形:
现在,虽然我们已经看到lines 和ax.lines 的内容是相同的,但非常重要的是要注意lines 变量引用的对象与@ 尊敬的对象不同987654339@ 如下图所示:
>>> id(lines), id(ax.lines)
(212754584, 211335288)
因此,从lines 中删除一个元素对当前绘图没有任何作用,但从ax.lines 中删除一个元素会从当前绘图中删除该行。所以:
>>> #THIS DOES NOTHING:
>>> lines.pop(0)
>>> #THIS REMOVES THE FIRST LINE:
>>> ax.lines.pop(0)
因此,如果您要运行第二行代码,您将从当前绘图中删除 ax.lines[0] 中包含的 Line2D 对象,它就会消失。请注意,这也可以通过ax.lines.remove() 完成,这意味着您可以将Line2D 实例保存在变量中,然后将其传递给ax.lines.remove() 以删除该行,如下所示:
>>> #Create a new line
>>> lines.append(ax.plot(np.arange(1000)/2.0))
>>> ax.lines
[<matplotlib.lines.Line2D object at 0xce84bd0>, <matplotlib.lines.Line2D object at 0xce84dx3>]
>>> #Remove that new line
>>> ax.lines.remove(lines[0])
>>> ax.lines
[<matplotlib.lines.Line2D object at 0xce84dx3>]
以上所有内容都适用于fig.axes,同样适用于ax.lines
现在,真正的问题在这里。如果我们将 ax.lines[0] 中包含的引用存储到 weakref.ref 对象中,然后尝试删除它,我们会注意到它没有被垃圾回收:
>>> #Create weak reference to Line2D object
>>> from weakref import ref
>>> wr = ref(ax.lines[0])
>>> print wr
<weakref at 0xb758af8; to 'Line2D' at 0xb757fd0>
>>> print wr()
<matplotlib.lines.Line2D at 0xb757fd0>
>>> #Delete the line from the axes
>>> ax.lines.remove(wr())
>>> ax.lines
[]
>>> #Test weakref again
>>> print wr
<weakref at 0xb758af8; to 'Line2D' at 0xb757fd0>
>>> print wr()
<matplotlib.lines.Line2D at 0xb757fd0>
参考仍然有效!为什么?这是因为wr 中的引用指向的Line2D 对象还有另一个引用。还记得lines 没有与ax.lines 相同的ID 但包含相同的元素吗?嗯,这就是问题所在。
>>> #Print out lines
>>> print lines
[<matplotlib.lines.Line2D object at 0xce84bd0>, <matplotlib.lines.Line2D object at 0xce84dx3>]
To fix this problem, we simply need to delete `lines`, empty it, or let it go out of scope.
>>> #Reinitialize lines to empty list
>>> lines = []
>>> print lines
[]
>>> print wr
<weakref at 0xb758af8; dead>
所以,这个故事的寓意是,清理自己。如果您希望某些东西会被垃圾回收,但事实并非如此,那么您可能会将引用留在某处。