Reputation: 449
I have a piece of code that works fine looping once or twice but eventually it builds up memory. I tried to locate the memory leakage with memory_profiler
and this is the result:
row_nr Memory_usage Memory_diff row_text
470 52.699 MiB 0.000 MiB ax.axis('off')
471 167.504 MiB 114.805 MiB fig.savefig('figname.png', dpi=600)
472 167.504 MiB 0.000 MiB fig.clf()
473 109.711 MiB -57.793 MiB plt.close()
474 109.711 MiB 0.000 MiB gc.collect()`
I created the figure like this:
fig, ax = plt.subplots()
Any suggestion where the 109 - 52 = 57 MiB went?
I am using python 3.3.
Upvotes: 23
Views: 14548
Reputation: 3098
Nothing posted here worked for me. In my case, it had something to do with running on a server via SSH interpreter. Apparently this will use a non-interactive mode, and that started clearing all memory as normal:
import matplotlib
matplotlib.use('Agg')
Source: https://matplotlib.org/stable/faq/howto_faq.html#work-with-threads
Upvotes: 19
Reputation: 1611
Taken from here: Matplotlib errors result in a memory leak. How can I free up that memory?
Which has original ref: https://www.mail-archive.com/[email protected]/msg11809.html
To get ax and figure do:
instead of:
import matplotlib.pyplot as plt
fig,ax = plt.subplots(1)
use:
from matplotlib import figure
fig = figure.Figure()
ax = fig.subplots(1)
Also no need to do plt.close()
or anything. It worked for me.
Upvotes: 7
Reputation: 595
# Clear the current axes.
plt.cla()
# Clear the current figure.
plt.clf()
# Closes all the figure windows.
plt.close('all')
plt.close(fig)
gc.collect()
This worked for me. Just put these lines at the end of the loop!
Upvotes: 2
Reputation: 59
plt.ioff()
worked for me in notebook,
plt.close(fig)
otherwise.
Upvotes: 5
Reputation: 101
# Clear the current axes.
plt.cla()
# Clear the current figure.
plt.clf()
# Closes all the figure windows.
plt.close('all')
Hope this can help you
Upvotes: 10