Save every iteration to png image file:
import matplotlib.pyplot as plt
fig, ax = plt.subplots( nrows=1, ncols=1 ) # create figure & 1 axis
ax.plot([0,1,2], [10,20,3])
fig.savefig('path/to/save/image/to.png') # save the figure to file
plt.close(fig) # close the figure window
source: https://stackoverflow.com/a/9890599/12576990
Convert generated images to a video file:
import cv2
import os
image_folder = 'images'
video_name = 'video.avi'
images = [img for img in os.listdir(image_folder) if img.endswith(".png")]
frame = cv2.imread(os.path.join(image_folder, images[0]))
height, width, layers = frame.shape
video = cv2.VideoWriter(video_name, 0, 1, (width,height))
for image in images:
video.write(cv2.imread(os.path.join(image_folder, image)))
cv2.destroyAllWindows()
video.release()
source: https://stackoverflow.com/a/44948030/12576990
As others have said, `plt.savefig()` or `fig1.savefig()` is indeed the way to save an image.
However I've found that in certain cases **the figure is always shown**. (eg. with Spyder having `plt.ion()`: interactive mode = On.) I work around this by forcing the closing of the figure window in my giant loop with `plt.close(figure_object)` (see [documentation][1]), so I don't have a million open figures during the loop:
import matplotlib.pyplot as plt
fig, ax = plt.subplots( nrows=1, ncols=1 ) # create figure & 1 axis
ax.plot([0,1,2], [10,20,3])
fig.savefig('path/to/save/image/to.png') # save the figure to file
plt.close(fig) # close the figure window
You should be able to re-open the figure later if needed to with `fig.show()` (didn't test myself).
[1]: https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.close.html