Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clear memory completely of all matplotlib plots

I have a data analysis module that contains functions which call on the matplotlib.pyplot API multiple times to generate up to 30 figures in each run. These figures get immediately written to disk after they are generated, and so I need to clear them from memory.

Currently, at the end of each of my function, I do:

import matplotlib.pyplot as plt  plt.clf() 

However, I'm not too sure if this statement can actually clear the memory. I'm especially concerned since I see that each time I run my module for debugging, my free memory space keeps decreasing.

What do I need to do to really clear my memory each time after I have written the plots to disk?

like image 304
AKKO Avatar asked Feb 27 '15 04:02

AKKO


People also ask

What is the command to clear all existing plots?

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.


2 Answers

Especially when you are running multiple processes or threads, it is much better to define your figure variable and work with it directly:

from matplotlib import pyplot as plt  f = plt.figure() f.clear() plt.close(f) 

In any case, you must combine the use of plt.clear() and plt.close()

UPDATE (2021/01/21)

If you are using a MacOS system along with its default backend (referred as 'MacOSX'), this does NOT work (at least in Big Sur). The only solution I have found is to switch to other of the well-known backends, such as TkAgg, Cairo, etc. To do it, just type:

import matplotlib matplotlib.use('TkAgg') # Your favorite interactive or non-interactive backend 
like image 61
Luis DG Avatar answered Sep 16 '22 22:09

Luis DG


After one week trials, I got my solution! Hope it can help you. My demo is attached.

import matplotlib.pyplot as plt import numpy as np  A = np.arange(1,5) B = A**2  cnt=0 while(1):       cnt = cnt+1     print("########### test %d ###########" % cnt)      # here is the trick:      # set the figure a 'num' to prevent from re-malloc of a figure in the next loop      # and set "clear=True" to make the figure clear     # I never use plt.close() to kill the figure, because I found it doesn't work.     # Only one figure is allocated, which can be self-released when the program quits.     # Before: 6000 times calling of plt.figure() ~ about 1.6GB of memory leak     # Now: the memory keeps in a stable level     fig = plt.figure(num=1, clear=True)     ax = fig.add_subplot()      # alternatively use an other function in one line     # fig, ax = plt.subplots(num=1,clear=True)      ax.plot(A,B)     ax.plot(B,A)      # Here add the functions you need      # plt.show()     fig.savefig('%d.png' % cnt) 
like image 35
James Huang Avatar answered Sep 17 '22 22:09

James Huang