I have data analysis module that contains functions which call on Matplotlib pyplot API multiple times to generate up to 30 figures in each run. These figures get immediatel
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()
Late answer, but this worked for me. I had a long sequential code generating many plots, and it would always end up eating all the RAM by the end of the process. Rather than calling fig.close() after each figure is complete, I have simply redefined the plt.figure function as follows, so that it is done automatically:
import matplotlib.pyplot as plt
import copy
try:
# if script it run multiple times, only redefine once
plt.old_figure
except:
# matplotlib is imported for the first time --> redefine
plt.old_figure = copy.deepcopy(plt.figure)
def newfig(*args):
plt.show()
plt.close("all")
return plt.old_figure(*args)
plt.figure = newfig
I am well aware that this is not a nice solution, however it easy, quick, and did the trick for me ! Maybe there's a way to decorate plt.figure instead of redefining it.
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)