Search code examples
pythonimagematplotlibsubplotsuptitle

Plot three images horizontally in python


I'm trying to plot three images with their subtitles above them but nothing is showing right now.

import cv2
from matplotlib import pyplot as plt

img = cv2.imread('kids.tif')

# Averaged environment
avg_blur = cv2.blur(img,(5,5))
# Gaussian filter
gauss_blur = cv2.GaussianBlur(img,(0,0),5)
# Median filter
median_blur = cv2.medianBlur(img,5)

f, axarr = plt.subplots(nrows=1,ncols=3)
axarr[0].imshow(img)
axarr[1].imshow(avg_blur)
axarr[2].imshow(gauss_blur)

"""
plt.subplot(121),plt.imshow(img),plt.title('Original')
plt.xticks([]), plt.yticks([])
plt.subplot(122),plt.imshow(avg_blur),plt.title('Averaged environment')
plt.xticks([]), plt.yticks([])
plt.show()
"""

Solution

  • Solution

    import numpy as np
    import matplotlib.pyplot as plt
    
    %matplotlib inline
    %config InlineBackend.figure_format = 'svg' # 'svg', 'retina'
    plt.style.use('seaborn-white')
    
    # Make dummy data for the image
    a = np.arange(25**2).reshape(25,25)
    
    # Show subplots | shape: (1,3) 
    fig, axs = plt.subplots(nrows=1, ncols=3, figsize=(12,4))
    for i, ax in enumerate(axs.flatten()):
        plt.sca(ax)
        plt.imshow(a**(i+1), cmap=plt.cm.jet)
        #plt.colorbar()
        plt.title('Image: {}'.format(i+1))
    
    #plt.tight_layout()
    plt.suptitle('Overall Title')
    plt.show()
    

    Output:
    enter image description here

    Code Similar to Your Implementation

    It is easier to just set the current axis plt.sca(ax) and then plot as if you have just one subplot to deal with. This makes your code easy to modify and if need be, swiftly move into a loop.

    f, axarr = plt.subplots(nrows=1,ncols=3)
    plt.sca(axarr[0]); 
    plt.imshow(img); plt.title('title 1')
    plt.sca(axarr[1]); 
    plt.imshow(avg_blur); plt.title('title 2')
    plt.sca(axarr[2]); 
    plt.imshow(gauss_blur); plt.title('title 3')
    plt.show()
    

    References