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

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

问题描述

在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)似乎有点hacker.我想要的是一种简单的方法来计算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天全站免登陆