关闭Matplotlib数字

ng1*_*716 13 python matplotlib

我正在使用Matplotlib和MPLD3来创建可以在html plages中显示的图形(使用django).目前,我的图表是从csv文件中提取的数据动态生成的.我经常在终端收到这条消息:

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

我不确定它的意思,但我假设它意味着我应该有一些方法来关闭未使用的图形.无论如何要做到这一点还是完全偏离基地?谢谢.

Sim*_*mon 14

我更喜欢评论中tacaswell的答案,但不得不寻找它.

完成后清理你的情节:

plt.close(fig)

要么

plt.close('all')

  • 奇怪,我想知道为什么没有这个图的`close()`方法. (4认同)

dsh*_*erd 6

如果不通过 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
Run Code Online (Sandbox Code Playgroud)

(基于这个答案