Plotting images side by side using matplotlib

后端 未结 5 1108
难免孤独
难免孤独 2020-12-23 09:36

I was wondering how I am able to plot images side by side using matplotlib for example something like this:

The closest I got is this:

相关标签:
5条回答
  • 2020-12-23 09:56

    The problem you face is that you try to assign the return of imshow (which is an matplotlib.image.AxesImage to an existing axes object.

    The correct way of plotting image data to the different axes in axarr would be

    f, axarr = plt.subplots(2,2)
    axarr[0,0].imshow(image_datas[0])
    axarr[0,1].imshow(image_datas[1])
    axarr[1,0].imshow(image_datas[2])
    axarr[1,1].imshow(image_datas[3])
    

    The concept is the same for all subplots, and in most cases the axes instance provide the same methods than the pyplot (plt) interface. E.g. if ax is one of your subplot axes, for plotting a normal line plot you'd use ax.plot(..) instead of plt.plot(). This can actually be found exactly in the source from the page you link to.

    0 讨论(0)
  • 2020-12-23 09:56

    One thing that I found quite helpful to use to print all images :

    _, axs = plt.subplots(n_row, n_col, figsize=(12, 12))
    axs = axs.flatten()
    for img, ax in zip(imgs, axs):
        ax.imshow(img)
    plt.show()
    
    0 讨论(0)
  • 2020-12-23 09:58

    If the images are in an array and you want to iterate through each element and print it, you can write the code as follows:

    plt.figure(figsize=(10,10)) # specifying the overall grid size
    
    for i in range(25):
        plt.subplot(5,5,i+1)    # the number of images in the grid is 5*5 (25)
        plt.imshow(the_array[i])
    
    plt.show()
    

    Also note that I used subplot and not subplots. They're both different

    0 讨论(0)
  • 2020-12-23 10:05

    You are plotting all your images on one axis. What you want ist to get a handle for each axis individually and plot your images there. Like so:

    fig = plt.figure()
    ax1 = fig.add_subplot(2,2,1)
    ax1.imshow(...)
    ax2 = fig.add_subplot(2,2,2)
    ax2.imshow(...)
    ax3 = fig.add_subplot(2,2,3)
    ax3.imshow(...)
    ax4 = fig.add_subplot(2,2,4)
    ax4.imshow(...)
    

    For more info have a look here: http://matplotlib.org/examples/pylab_examples/subplots_demo.html

    For complex layouts, you should consider using gridspec: http://matplotlib.org/users/gridspec.html

    0 讨论(0)
  • 2020-12-23 10:14

    As per matplotlib's suggestion for image grids:

    import matplotlib.pyplot as plt
    from mpl_toolkits.axes_grid1 import ImageGrid
    
    fig = plt.figure(figsize=(4., 4.))
    grid = ImageGrid(fig, 111,  # similar to subplot(111)
                     nrows_ncols=(2, 2),  # creates 2x2 grid of axes
                     axes_pad=0.1,  # pad between axes in inch.
                     )
    
    for ax, im in zip(grid, image_data):
        # Iterating over the grid returns the Axes.
        ax.imshow(im)
    
    plt.show()
    
    0 讨论(0)
提交回复
热议问题