'matplotlib savefig of multiple subplots without displaying

I have an array of images which I have reshaped as size (28, 28, 3) of 100 images.

I want to save the plot which the below code generates, but without displaying (imshow) the plot.

I struggled a lot but couldn't find a solution. I found suggestion to use matplotlib.use('Agg'), but it didn't work, because I'm still using imshow here. I am thinking that it could be achieved if it is possible to subplot images without imshow.

Is there any way to save a plot, made of multiple subplots, without displaying it?

If anyone would please let me know, I would be grateful.

import numpy as np
import matplotlib.pyplot as plt

images = np.random.randint(0, 255, size=235200)
# Reshaped to 100 images of size (28, 28) with 3 channels
images = images.reshape(100, 28, 28, 3)

plt.figure(figsize=(10, 10))
for i in range(images.shape[0]):
    plt.subplot(10, 10, i + 1)
    plt.imshow(images[i], interpolation='nearest', cmap='gray_r')
    plt.axis('off')
plt.savefig('all_images.png')


Solution 1:[1]

Possible solution is to use plt.close(fig) as shown bellow.

import numpy as np
import matplotlib.pyplot as plt

images = np.random.randint(0, 255, size=235200)
# Reshaped to 100 images of size (28, 28) with 3 channels
images = images.reshape(100, 28, 28, 3)

# create the figure
fig, axs = plt.subplots(nrows=10, ncols=10, figsize=(10, 10))
axs = axs.flatten()

for i, image in enumerate(images):
    axs[i].imshow(images[i], interpolation='nearest', cmap='gray_r')
    axs[i].axis('off')

plt.savefig('all_images.png')

plt.close(fig) # << HERE

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 gremur