Gabriel
Gabriel

Reputation: 42349

matplotlib: releasing memory after plot is done

I'd like to know the correct way to release memory after a plot is done since I'm getting a RuntimeError: Could not allocate memory for image error when plotting multiple images in a loop.

Currently I have the following commands in another code to supposedly do just that:

import matplotlib.pyplot as plt

# The code
.....

# Make plot
fig = plt.figure()
# Plotting stuff.
plt.imshow(...)
plt.plot(...)
plt.scatter(...)

# Save plot to file.
plt.savefig(...)

# Release memory.
plt.clf()
plt.close()

A comment in this answer states that the correct syntax is actually plt.close(fig) but the highest voted answer given here says that plt.clf() is enough and doesn't mention .close.

The questions are: what is(are) the correct command(s) to release memory after the plot is saved to file? Do I need both .clf and .close or is one of them enough?

Upvotes: 3

Views: 2791

Answers (1)

wim
wim

Reputation: 362796

I would like to suggest for you an alternate approach. Note that imshow returns a handle for you. Grab a reference on this, and use the set_data method on that object for subsequent iterations.

>>> h = plt.imshow(np.zeros([480, 640]))
>>> h
<matplotlib.image.AxesImage at 0x47a03d0>
>>> for img in my_imgs:
...     h.set_data(img)  #etc

Upvotes: 2

Related Questions