关闭Matplotlib图形界面

32

我正在使用Matplotlib和MPLD3创建图形,可以在html页面中显示(使用django)。目前,我的图形是从csv文件中获取的数据动态生成的。偶尔在终端里会收到以下警告信息:

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. (To control this warning, see the rcParam figure.max_num_figures). max_open_warning, RuntimeWarning)

我不太确定这意味着什么,但我假设这意味着我应该有一种关闭未使用图形的方法。有没有办法做到这一点,或者我完全错了? 谢谢。


13
不确定这是最好的重复内容。简短的答案是,在绘制完成后应该清理你的图表:plt.close(fig)plt.close('all') - tacaswell
1
@tcaswell为什么不把这个作为答案添加呢? - Korem
2个回答

39

我更喜欢评论区中 tacaswell 的答案,但是不得不搜索一下。

在完成绘图后清理它们:

plt.close(fig)

或者

plt.close('all')


7
奇怪,我想知道为什么图形没有 close() 方法。 - Jason S
是啊!为什么 fig.close() 不起作用呢? - DanHickstein
@DanHickstein,似乎在图形上没有实现close方法(参考https://matplotlib.org/api/_as_gen/matplotlib.figure.Figure.html)。 - Simon
我正在使用matplotlib版本:3.0.3,plt.close()对我有效。 - Mattman85208

8

如果你不通过pyplot接口创建图形,那么图形将会被自动关闭(由垃圾回收机制执行)。例如,你可以使用以下代码创建图形:

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


def new_fig():
    """Create a new matplotlib figure containing one axis"""
    fig = Figure()
    FigureCanvas(fig)
    ax = fig.add_subplot(111)

    return fig, ax

(基于这个答案


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接