Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory overflow when saving Matplotlib plots in a loop

I am using an iterative loop to plot soame data using Matplotlib. When the code has saved around 768 plots, it throws the following exception.

RuntimeError: Could not allocate memory for image

My computer has around 3.5 GB RAM. Is there any method to free the memory in parallel so that the memory does not get exhausted?

like image 547
tanzil Avatar asked Dec 16 '22 11:12

tanzil


2 Answers

Are you remembering to close your figures when you are done with them? e.g.:

import matplotlib.pyplot as plt

#generate figure here
#...
plt.close(fig)  #release resources associated with fig
like image 50
mgilson Avatar answered Dec 18 '22 12:12

mgilson


As a slightly different answer, remember that you can re-use figures. Something like:

fig = plt.figure()
ax = plt.gca()

im = ax.imshow(data_list[0],...)

for new_data in data_list:
    im.set_cdata(new_data)
    fig.savefig(..)

Which will make your code run much faster as it will not need to set up and tear down the figure 700+ times.

like image 29
tacaswell Avatar answered Dec 18 '22 10:12

tacaswell