如何删除 Matplotlib 图中的线条 [英] How to remove lines in a Matplotlib plot

查看:141
本文介绍了如何删除 Matplotlib 图中的线条的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何删除 matplotlib 轴的一行(或多行)以使其实际被垃圾收集并释放内存?下面的代码似乎删除了该行,但永远不会释放内存(即使显式调用 gc.collect())

How can I remove a line (or lines) of a matplotlib axes in such a way as it actually gets garbage collected and releases the memory back? The below code appears to delete the line, but never releases the memory (even with explicit calls to gc.collect())

from matplotlib import pyplot
import numpy
a = numpy.arange(int(1e7))
# large so you can easily see the memory footprint on the system monitor.
fig = pyplot.Figure()
ax  = pyplot.add_subplot(1, 1, 1)
lines = ax.plot(a) # this uses up an additional 230 Mb of memory.
# can I get the memory back?
l = lines[0]
l.remove()
del l
del lines
# not releasing memory
ax.cla() # this does release the memory, but also wipes out all other lines.

那么有没有办法从轴中删除一行并恢复记忆?这个潜在的解决方案也不起作用.

So is there a way to just delete one line from an axes and get the memory back? This potential solution also does not work.

推荐答案

我正在展示 lines.pop(0) l.remove() 的组合而 del l 可以解决问题.

I'm showing that a combination of lines.pop(0) l.remove() and del l does the trick.

from matplotlib import pyplot
import numpy, weakref
a = numpy.arange(int(1e3))
fig = pyplot.Figure()
ax  = fig.add_subplot(1, 1, 1)
lines = ax.plot(a)

l = lines.pop(0)
wl = weakref.ref(l)  # create a weak reference to see if references still exist
#                      to this object
print wl  # not dead
l.remove()
print wl  # not dead
del l
print wl  # dead  (remove either of the steps above and this is still live)

我检查了你的大数据集,在系统监视器上也确认了内存的释放.

I checked your large dataset and the release of the memory is confirmed on the system monitor as well.

当然,更简单的方法(当不排除故障时)是将它从列表中弹出并在行对象上调用 remove 而不创建对它的硬引用:

Of course the simpler way (when not trouble-shooting) would be to pop it from the list and call remove on the line object without creating a hard reference to it:

lines.pop(0).remove()

这篇关于如何删除 Matplotlib 图中的线条的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆