创建一个引用计数的图形 [英] Create a figure that is reference counted

查看:43
本文介绍了创建一个引用计数的图形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 matplotlib 中创建图形的标准方法似乎不像我在 python 中期望的那样:默认情况下,在循环中调用 fig = matplotlib.figure() 将保持不变以创建所有数字,并最终耗尽内存.

It seems that the standard way of creating a figure in matplotlib doesn't behave as I'd expect in python: by default calling fig = matplotlib.figure() in a loop will hold on to all the figures created, and eventually run out of memory.

相当 一个 很少篇涉及变通方法的帖子,但需要显式调用matplotlib.pyplot.close(fig) 似乎有点hackish.我想要的是一种使 fig 引用计数的简单方法,这样我就不必担心内存泄漏.有没有办法做到这一点?

There are quite a few posts which deal with workarounds, but requiring explicit calls to matplotlib.pyplot.close(fig) seems a bit hackish. What I'd like is a simple way to make fig reference counted, so I won't have to worry about memory leaks. Is there some way to do this?

推荐答案

如果您在不使用 plt.figure 的情况下创建图形,那么它应该按预期进行引用计数.例如(这也是使用非交互式 Agg 后端.)

If you create the figure without using plt.figure, then it should be reference counted as you expect. For example (This is using the non-interactive Agg backend, as well.)

from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure

# The pylab figure manager will be bypassed in this instance.
# This means that `fig` will be garbage collected as you'd expect.
fig = Figure()
canvas = FigureCanvas(fig)
ax = fig.add_subplot(111)

这篇关于创建一个引用计数的图形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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