警告有太多未完成的数字 [英] warning about too many open figures

查看:67
本文介绍了警告有太多未完成的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我用fix, ax = plt.subplots(...)创建许多图形的脚本中,收到警告 RuntimeWarning:已打开20多个图形.通过pyplot界面(matplotlib.pyplot.figure)创建的图形将保留到显式关闭,并且可能会占用过多的内存.

In a script where I create many figures with fix, ax = plt.subplots(...), I get the warning RuntimeWarning: More than 20 figures have been opened. Figures created through the pyplot interface (matplotlib.pyplot.figure) are retained until explicitly closed and may consume too much memory.

但是,我不明白为什么为什么收到此警告,因为用fig.savefig(...)保存图形后,我用fig.clear(); del fig删除了它.在我的代码中,我一次都没有打开多个图形.不过,我仍然收到有关未结数字过多的警告.这是什么意思/如何避免收到警告?

However, I don't understand why I get this warning, because after saving the figure with fig.savefig(...), I delete it with fig.clear(); del fig. At no point in my code, I have more than one figure open at a time. Still, I get the warning about too many open figures. What does that mean / how can I avoid getting the warning?

推荐答案

在图形对象上使用.clf.cla而不是创建 new 图形.来自 @DavidZwicker

Use .clf or .cla on your figure object instead of creating a new figure. From @DavidZwicker

假设您已将pyplot导入为

import matplotlib.pyplot as plt

plt.cla()清除轴,即当前图中的当前活动轴.它使其他轴保持不变.

plt.cla() clears an axis, i.e. the currently active axis in the current figure. It leaves the other axes untouched.

plt.clf()清除了整个当前图形的所有轴,但保持窗口打开,以便可以将其重新用于其他图.

plt.clf() clears the entire current figure with all its axes, but leaves the window opened, such that it may be reused for other plots.

plt.close()关闭一个窗口如果没有另外指定,将是当前窗口. plt.close('all')将关闭所有未完成的图形.

plt.close() closes a window, which will be the current window, if not specified otherwise. plt.close('all') will close all open figures.

del fig不起作用的原因是pyplot状态机保留对周围图形的引用(因为要知道当前图形"是什么,必须这样做).这意味着即使您删除该图的您的引用,也至少有一个活动引用,因此将永远不会被垃圾收集.

The reason that del fig does not work is that the pyplot state-machine keeps a reference to the figure around (as it must if it is going to know what the 'current figure' is). This means that even if you delete your ref to the figure, there is at least one live ref, hence it will never be garbage collected.

由于我在这里就此答案进行集体智慧调查,因此@JoeKington在评论中提到

Since I'm polling on the collective wisdom here for this answer, @JoeKington mentions in the comments that plt.close(fig) will remove a specific figure instance from the pylab state machine (plt._pylab_helpers.Gcf) and allow it to be garbage collected.

这篇关于警告有太多未完成的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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