warning about too many open figures

后端 未结 6 1891
陌清茗
陌清茗 2020-11-29 15:38

In a script where I create many figures with fix, ax = plt.subplots(...), I get the warning RuntimeWarning: More than 20 figures have been opened. Figures c

6条回答
  •  無奈伤痛
    2020-11-29 16:03

    Use .clf or .cla on your figure object instead of creating a new figure. From @DavidZwicker

    Assuming you have imported pyplot as

    import matplotlib.pyplot as plt
    

    plt.cla() clears an axis, i.e. the currently active axis in the current figure. It leaves the other axes untouched.

    plt.clf() clears the entire current figure with all its axes, but leaves the window opened, such that it may be reused for other plots.

    plt.close() closes a window, which will be the current window, if not specified otherwise. plt.close('all') will close all open figures.

    The reason that del fig does not work is that the pyplot state-machine keeps a reference to the figure around (as it must if it is going to know what the 'current figure' is). This means that even if you delete your ref to the figure, there is at least one live ref, hence it will never be garbage collected.

    Since I'm polling on the collective wisdom here for this answer, @JoeKington mentions in the comments that plt.close(fig) will remove a specific figure instance from the pylab state machine (plt._pylab_helpers.Gcf) and allow it to be garbage collected.

提交回复
热议问题