多个子图的Matplotlib savefig不显示

3
我有一个包含100张图片的数组,它们已经被重塑为大小为 (28, 28, 3)。
我想保存下面代码生成的图表,但不显示 (imshow) 图表。
我尝试了很多但没有找到解决方案。我发现建议使用 matplotlib.use('Agg'),但它没有起作用,因为我仍然在这里使用 imshow。我认为如果可以在没有使用 imshow 的情况下对子图进行排列,就可以实现这一目标。
是否有任何方法可以保存由多个子图组成的图表而不显示它?
如果有人能告诉我,我将不胜感激。
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')
1个回答

0
可能的解决方案是使用下面所示的 plt.close(fig)
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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接