How to clear memory completely of all matplotlib plots
Solution 1:
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
Solution 2:
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)
Solution 3:
I have data analysis module that contains functions which call on Matplotlib pyplot API multiple
Can you edit your functions which is calling matplotlib? I was facing the same issue, I tried following command but none of it worked.
plt.close(fig)
fig.clf()
gc.collect()
%reset_selective -f fig
Then one trick worked for me, instead of creating a new figure every time, I pass the same fig object to the function and this solved my issue.
for example use,
fig = plt.figure()
for i in range(100):
plt.plot(x,y)
instead of,
for i in range(100):
fig = plt.figure()
plt.plot(x,y)