关于过多开放数字的警告

编程入门 行业动态 更新时间:2024-10-25 16:30:47
本文介绍了关于过多开放数字的警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在我使用 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();删除图.在我的代码中,我一次打开不止一个图形.尽管如此,我还是收到了关于太多开放数字的警告.这是什么意思/我怎样才能避免收到警告?

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 在评论中提到 plt.close(fig) 将从 pylab 状态机(plt._pylab_helpers.Gcf) 并允许它被垃圾收集.

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.

更多推荐

关于过多开放数字的警告

本文发布于:2023-11-25 12:14:56,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1629706.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数字

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!