32

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:

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)

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.

Martin Geisler
  • 72,968
  • 25
  • 171
  • 229
ng150716
  • 2,195
  • 5
  • 40
  • 61
  • 13
    Not sure that is the best duplicate. The short answer is you should clean up your plots after you are done with them: `plt.close(fig)` or `plt.close('all')`. – tacaswell Jun 30 '14 at 23:01
  • 1
    @tcaswell why not add this as an answer? – Korem Jul 01 '14 at 10:50

2 Answers2

39

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

Clean up your plots after you are done with them:

plt.close(fig)

or

plt.close('all')

Community
  • 1
  • 1
Simon
  • 5,464
  • 6
  • 49
  • 85
8

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:

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)

Community
  • 1
  • 1
dshepherd
  • 4,989
  • 4
  • 39
  • 46