Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib doesn't release memory after savefig and close()

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.

like image 754
axel_ande Avatar asked Jul 01 '15 08:07

axel_ande


People also ask

Does matplotlib overwrite Savefig?

But being honest it's strange that matplotlib does not overwrite the file. This is useful - I'll accept in a few days if no one has a Windows-based explanation for what has changed, and how to fix.

What is matplotlib use (' AGG ')?

The last, Agg, is a non-interactive backend that can only write to files. It is used on Linux, if Matplotlib cannot connect to either an X display or a Wayland display.


2 Answers

# 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

like image 53
YOYO Lu Avatar answered Oct 07 '22 08:10

YOYO Lu


plt.ioff() worked for me in notebook, plt.close(fig) otherwise.

like image 35
Javier Jaimes Avatar answered Oct 07 '22 10:10

Javier Jaimes