Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.figure()
    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: https://stackoverflow.com/a/11688881/354979 but I don't understand how. How can I optimize it?

like image 284
rhombidodecahedron Avatar asked Aug 13 '13 16:08

rhombidodecahedron


2 Answers

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:

When to use cla(), clf() or close() for clearing a plot in matplotlib?

like image 184
Hooked Avatar answered Oct 05 '22 00:10

Hooked


Although this question is old, the answer would be:

import matplotlib.pyplot as plt
fig = plt.figure()
plot = plt.plot(results[0])
title = plt.title('title')

plt.xlabel('xlabel')
plt.ylabel('ylabel')
plt.ylim([0,1])
plt.grid(True)

for i in range(1,len(results)):
    plot.set_data(results[i])
    title.set_text('new title')
    plt.savefig(location[i], bbox_inches=0)
plt.close('all')
like image 43
Renatius Avatar answered Oct 05 '22 01:10

Renatius