Python 关闭 Matplotlib 图形

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24500065/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 04:41:30  来源:igfitidea点击:

Closing Matplotlib figures

pythonmatplotlib

提问by ng150716

I am using Matplotlib and MPLD3 to create graphs that can be displayed in html plages (using django). Currently my graphs are being generated dynamically from data being pulled from csv files. Every so often I get this message in my Terminal:

我正在使用 Matplotlib 和 MPLD3 创建可以在 html plages 中显示的图形(使用 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)

运行时警告:已打开 20 多个图形。通过 pyplot 接口 ( matplotlib.pyplot.figure)创建的图会保留直到明确关闭,并且可能会消耗太多内存。(要控制此警告,请参阅 rcParam figure.max_num_figures)。max_open_warning、运行时警告)

I am not really sure what it means, but I am assuming it means I should have some way of closing graphs that are not in use. Is there anyway to do this or am I completely off base? Thanks.

我不太确定这意味着什么,但我假设这意味着我应该有某种方法来关闭未使用的图表。无论如何要这样做还是我完全偏离了基地?谢谢。

回答by dshepherd

Figures will automatically be closed (by garbage collection) if you don't create them through the pyplot interface. For example you can create figures using:

如果不通过 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

(Based on this answer)

(基于这个答案

回答by Simon

I preferred the answer of tacaswellin the comments, but had to search for it.

我更喜欢评论中tacaswell的答案,但不得不搜索它。

Clean up your plots after you are done with them:

完成后清理你的图:

plt.close(fig)

plt.close(fig)

or

或者

plt.close('all')

plt.close('all')