如何清除Python / matplotlib内存?

时间:2017-07-02 06:41:09

标签: python memory matplotlib

使用pyplot绘制几个图形后,Python会发出内存错误(我在笔记本电脑上绘制了超过一百万个点的图形 - 在错误与点数量有直接关系之前可以绘制多少个图形。)< / p>

如何清除内存,以便我可以绘制更多图形?现在唯一的选择是ctrl + .重新启动内核。

我尝试过推荐:

matplotlib.pyplot.close("all")
matplotlib.pyplot.clf()

不清除错误。

3 个答案:

答案 0 :(得分:0)

假设您正在使用Jupyter Notebook,您只需在单元格中调用%reset

答案 1 :(得分:0)

也许这已经在最近的修订中得到修复,但我仍然使用它:

plt.close()
# http://matplotlib.org/users/pyplot_tutorial.html
# >>> WORKING WITH MULTIPLE FIGURES AND AXES
# is a must

pyplot tutorial解释说:

  

如果要制作大量数字,则需要注意另一件事:在使用.close()显式关闭数字之前,图形所需的内存不会完全释放。
/>   删除对图的所有引用,和/或使用窗口管理器来终止屏幕上显示图形的窗口是不够的,因为 pyplot 维护内部引用,直到 .close()

如果不处理,也可以使python解释器整体崩溃

对此感到很头疼。

# #####################################################################################
#
# AFTER SOME 50 calls, matplotlib crashed first, after a few more, python was killed too
#
# ###################################################################################### >>> http://stackoverflow.com/questions/32318643/how-to-properly-delete-a-matplotlib-figure-embedded-in-a-child-window-in-pyside
#
# Traceback (most recent call last):
#   File "C:\Python27.anaconda\lib\site-packages\matplotlib\backends\backend_qt5agg.py", line 91, in paintEvent
#     stringBuffer = self.renderer._renderer.tostring_bgra()
# MemoryError
# Traceback (most recent call last):
#   File "C:\Python27.anaconda\lib\site-packages\matplotlib\backends\backend_qt5agg.py", line 91, in paintEvent
#     stringBuffer = self.renderer._renderer.tostring_bgra()
# MemoryError
# Traceback (most recent call last):
#   File "C:\Python27.anaconda\lib\site-packages\matplotlib\backends\backend_qt5agg.py", line 91, in paintEvent
#     stringBuffer = self.renderer._renderer.tostring_bgra()
# MemoryError
# Traceback (most recent call last):
#   File "C:\Python27.anaconda\lib\site-packages\matplotlib\backends\backend_qt5agg.py", line 91, in paintEvent
#     stringBuffer = self.renderer._renderer.tostring_bgra()
# MemoryError
#
# ######################################################################################

答案 2 :(得分:0)

我已经为此奋斗了几周,对我而言唯一有效的方法是此处提供的解决方案:

How to clear memory completely of all Matplotlib plots

matplotlib.pyplot.figure().clear()
matplotlib.pyplot.close()

以下内容:

plt.cla()

plt.clf() 

根本不适合我...我怀疑是因为它是为您有多个子图而设计的...