我在 matplotlib 中动态设置子图数量的方式有什么不正确

What is incorrect about the way I'm dynamically setting the number of subplots in matplotlib

作为更大模块的一部分,我想使用 matplotlib 保存一系列图像。只有少量图像(即 1-3),因此我试图动态设置 plt.subplot 中指定的列数。当我尝试对三张图片执行此操作时,一切正常 - 我得到一行 3 张图片:

但是,当我尝试只用两张图片执行此操作时,我在子图的右侧得到了一张图片:

我提取了原始代码的关键方法并创建了一个示例(见下文),该示例以与实际代码完全相同的格式将图像数组提供给该方法。

为什么我能得到一行 3 张图片,而不是 2 张图片?

import matplotlib.pyplot as plt
import matplotlib
matplotlib.use('Agg') # suppresses plot

import numpy as np
from PIL import Image, ImageOps

def generate_images(test_input, path_filename):

    plt.figure(figsize=(15, 6))

    # This configuration works - Gives 3 images
    #display_list = [test_input[0], test_input[0], test_input[0]]
    #title = ['Test Image 1', 'Test Image 2', 'Test Image 3']

    # This configuration does not work - Only gives 1 image on right side
    # of subplot
    display_list = [test_input[0], test_input[0]]
    title = ['Test Image 1', 'Test Image 2']

    for i in range(len(title)):

        # Here is where I tried to dynamically create my subplot dimensions
        plt.subplot(1, len(title), i + 1)
        plt.title(title[i])


        # Getting the pixel values in the [0, 1] range to plot.
        plt.imshow(display_list[i] * 0.5 + 0.5, cmap=plt.get_cmap('gray'))
        plt.axis('off')
        plt.tight_layout()

    plt.savefig(path_filename, dpi=200)
    plt.close()

    print()
    print("Image Shape:",test_input.shape)
    print("len(title):",len(title))


# Get Sample Image 
file_path = <path to input image>
im = Image.open(file_path)

# Rescale and change from RGB to grayscale 
im2 = ImageOps.grayscale(im)
im2 = im2.resize((256,256))
num_array = np.asarray(im2)

# Convert to an array of images
num_array = num_array[np.newaxis,:,:,np.newaxis]

out_path = <path and filename of output image>
generate_images(num_array,out_path)

两张图是画出来的,不知道为什么,想用的时候出现问题:plt.tight_layout().

尝试在添加完所有轴后调用此函数

观察我是如何在 for 循环之后调用函数的,这应该可以解决您的问题

您可以在以下link中获得有关此功能的更多信息: matplotlib.pyplot.tight_layout