如何完全清除所有 matplotlib 图的内存 [英] How to clear memory completely of all matplotlib plots

查看:68
本文介绍了如何完全清除所有 matplotlib 图的内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据分析模块,其中包含多次调用 matplotlib.pyplot API 以在每次运行中生成多达 30 个数字的函数.这些数字在生成后会立即写入磁盘,因此我需要将它们从内存中清除.

I have a data analysis module that contains functions which call on the matplotlib.pyplot API multiple times to generate up to 30 figures in each run. These figures get immediately written to disk after they are generated, and so I need to clear them from memory.

目前,在我的每个函数结束时,我会:

Currently, at the end of each of my function, I do:

import matplotlib.pyplot as plt

plt.clf()

不过,我不太确定这个语句是否真的可以清除内存.我特别担心,因为我发现每次运行我的模块进行调试时,我的可用内存空间都在不断减少.

However, I'm not too sure if this statement can actually clear the memory. I'm especially concerned since I see that each time I run my module for debugging, my free memory space keeps decreasing.

每次将绘图写入磁盘后,我需要做什么才能真正清除我的记忆?

What do I need to do to really clear my memory each time after I have written the plots to disk?

推荐答案

特别是当您运行多个进程或线程时,最好定义您的图形变量并直接使用它:

Especially when you are running multiple processes or threads, it is much better to define your figure variable and work with it directly:

from matplotlib import pyplot as plt

f = plt.figure()
f.clear()
plt.close(f)

无论如何,你必须结合使用 plt.clear() 和 plt.close()

In any case, you must combine the use of plt.clear() and plt.close()

更新 (2021/01/21)

UPDATE (2021/01/21)

如果您使用的是 MacOS 系统及其默认后端(称为MacOSX"),这将不起作用(至少在 Big Sur).我找到的唯一解决方案是切换到其他知名后端,例如 TkAgg、Cairo 等.为此,只需键入:

If you are using a MacOS system along with its default backend (referred as 'MacOSX'), this does NOT work (at least in Big Sur). The only solution I have found is to switch to other of the well-known backends, such as TkAgg, Cairo, etc. To do it, just type:

import matplotlib
matplotlib.use('TkAgg') # Your favorite interactive or non-interactive backend

这篇关于如何完全清除所有 matplotlib 图的内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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