【问题标题】:Multiple figures in a single window单个窗口中的多个图形
【发布时间】:2012-06-24 22:38:51
【问题描述】:

我想创建一个函数,在单个窗口中在屏幕上绘制一组图形。现在我写了这段代码:

import pylab as pl

def plot_figures(figures):
    """Plot a dictionary of figures.

    Parameters
    ----------
    figures : <title, figure> dictionary

    """
    for title in figures:
        pl.figure()
        pl.imshow(figures[title])
        pl.gray()
        pl.title(title)
        pl.axis('off')

它工作得很好,但我希望可以选择在单个窗口中绘制所有数字。而这段代码没有。我读过一些关于 subplot 的东西,但它看起来很棘手。

【问题讨论】:

标签: python image matplotlib subplot


【解决方案1】:
def plot_figures(figures, nrows=None, ncols=None):
    if not nrows or not ncols:
        # Plot figures in a single row if grid not specified
        nrows = 1
        ncols = len(figures)
    else:
        # check minimum grid configured
        if len(figures) > nrows * ncols:
            raise ValueError(f"Too few subplots ({nrows*ncols}) specified for ({len(figures)}) figures.")

    fig = plt.figure()

    # optional spacing between figures
    fig.subplots_adjust(hspace=0.4, wspace=0.4)

    for index, title in enumerate(figures):
        plt.subplot(nrows, ncols, index + 1)
        plt.title(title)
        plt.imshow(figures[title])
    plt.show()

可以指定任何网格配置(或不指定),只要行数和列数的乘积等于或大于图形数即可。

例如,对于 len(figures) == 10,这些是可以接受的

plot_figures(数字)
plot_figures(数字, 2, 5)
plot_figures(数字, 3, 4)
plot_figures(数字, 4, 3)
plot_figures(figures, 5, 2)

【讨论】:

    【解决方案2】:

    如果你想在一个窗口中组合多个数字,你可以这样做。像这样:

    import matplotlib.pyplot as plt
    import numpy as np
    
    
    img = plt.imread('C:/.../Download.jpg') # Path to image
    img = img[0:150,50:200,0] # Define image size to be square --> Or what ever shape you want
    
    fig = plt.figure()
    
    nrows = 10 # Define number of columns
    ncols = 10 # Define number of rows
    image_heigt = 150 # Height of the image
    image_width = 150 # Width of the image
    
    
    pixels = np.zeros((nrows*image_heigt,ncols*image_width)) # Create 
    for a in range(nrows):
        for b in range(ncols):
            pixels[a*image_heigt:a*image_heigt+image_heigt,b*image_heigt:b*image_heigt+image_heigt] = img
    plt.imshow(pixels,cmap='jet')
    plt.axis('off')
    plt.show()
    

    因此,您会收到:

    【讨论】:

      【解决方案3】:

      您也可以这样做:

      import matplotlib.pyplot as plt
      
      f, axarr = plt.subplots(1, len(imgs))
      for i, img in enumerate(imgs):
          axarr[i].imshow(img)
      
      plt.suptitle("Your title!")
      plt.show()
      

      【讨论】:

        【解决方案4】:

        基于How to display multiple images in one figure correctly? 的回答,这是另一种方法:

        import math
        import numpy as np
        import matplotlib.pyplot as plt
        
        def plot_images(np_images, titles = [], columns = 5, figure_size = (24, 18)):
            count = np_images.shape[0]
            rows = math.ceil(count / columns)
        
            fig = plt.figure(figsize=figure_size)
            subplots = []
            for index in range(count):
                subplots.append(fig.add_subplot(rows, columns, index + 1))
                if len(titles):
                    subplots[-1].set_title(str(titles[index]))
                plt.imshow(np_images[index])
        
            plt.show()
        

        【讨论】:

          【解决方案5】:

          您可以根据matplotlib.pyplotsubplots命令(注意末尾的s,与urinieto指向的subplot命令不同)定义一个函数。

          以下是基于您的功能的示例,允许在图中绘制多个轴。您可以在图形布局中定义所需的行数和列数。

          def plot_figures(figures, nrows = 1, ncols=1):
              """Plot a dictionary of figures.
          
              Parameters
              ----------
              figures : <title, figure> dictionary
              ncols : number of columns of subplots wanted in the display
              nrows : number of rows of subplots wanted in the figure
              """
          
              fig, axeslist = plt.subplots(ncols=ncols, nrows=nrows)
              for ind,title in enumerate(figures):
                  axeslist.ravel()[ind].imshow(figures[title], cmap=plt.gray())
                  axeslist.ravel()[ind].set_title(title)
                  axeslist.ravel()[ind].set_axis_off()
              plt.tight_layout() # optional
          

          基本上,该函数根据您想要的行数 (nrows) 和列数 (ncols) 在图中创建多个轴,然后遍历轴列表以绘制图像和为每个人添加标题。

          请注意,如果您的字典中只有一张图片,则您之前的语法 plot_figures(figures) 将有效,因为默认情况下 nrowsncols 设置为 1

          您可以获得的示例:

          import matplotlib.pyplot as plt
          import numpy as np
          
          # generation of a dictionary of (title, images)
          number_of_im = 6
          figures = {'im'+str(i): np.random.randn(100, 100) for i in range(number_of_im)}
          
          # plot of the images in a figure, with 2 rows and 3 columns
          plot_figures(figures, 2, 3)
          

          【讨论】:

          • 可读性稍有提升:将zip(range(len(figures)), figures)替换为enumerate(figures)
          【解决方案6】:

          你应该使用subplot

          在你的情况下,它会是这样的(如果你想让它们一个在另一个之上):

          fig = pl.figure(1)
          k = 1
          for title in figures:
              ax = fig.add_subplot(len(figures),1,k)
              ax.imshow(figures[title])
              ax.gray()
              ax.title(title)
              ax.axis('off')
              k += 1
          

          查看documentation 了解其他选项。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2018-01-01
            • 2021-07-27
            • 1970-01-01
            • 2018-03-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多