rhombidodecahedron rhombidodecahedron - 1 year ago 129
Python Question

Matplotlib crashes after saving many plots

I am plotting and saving thousands of files for later animation in a loop like so:

import matplotlib.pyplot as plt
for result in results:
plt.plot(result) # this changes
plt.xlabel('xlabel') # this doesn't change
plt.ylabel('ylabel') # this doesn't change
plt.title('title') # this changes
plt.ylim([0,1]) # this doesn't change
plt.grid(True) # this doesn't change
plt.savefig(location, bbox_inches=0) # this changes

When I run this with a lot of results, it crashes after several thousand plots are saved. I think what I want to do is reuse my axes like in this answer: http://stackoverflow.com/a/11688881/354979 but I don't understand how. How can I optimize it?

Answer Source

I would create a single figure and clear the figure each time (use .clf).

import matplotlib.pyplot as plt

fig = plt.figure()

for result in results:
    fig.clf()   # Clears the current figure

You are running out of memory since each call to plt.figure creates a new figure object. Per @tcaswell's comment, I think this would be faster than .close. The differences are explained in:

matplotlib: clearing a plot, when to use cla(), clf() or close()?