代码之家  ›  专栏  ›  技术社区  ›  user1245262

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

  •  0
  • user1245262  · 技术社区  · 4 年前

    作为一个更大模块的一部分,我想使用matplotlib保存一系列图像。只有少量的图像(即1-3),所以我试图动态设置plt.subplot中指定的列数。当我尝试对三个图像执行此操作时,一切都很好-我得到了一行3个图像: enter image description here

    然而,当我尝试只使用两张图像时,我会在子画面的右手边得到一张图像: enter image description here

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

    为什么我可以得到一行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)
    
    1 回复  |  直到 4 年前
        1
  •  1
  •   user18376478 user18376478    4 年前

    由于某些原因,绘制这两幅图像时会出现问题: plt.tight_layout()

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

    enter image description here

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

    enter image description here

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