How to Display Multiple Images in One Figure Correctly in Matplotlib?

The easiest way to display multiple images in one figure is use figure(), add_subplot(), and imshow() methods of Matplotlib. The approach which is used to follow is first initiating fig object by calling fig=plt.figure() and then add an axes object to the fig by calling add_subplot() method. Then will display the image using imshow() method.
Syntax: add_subplot(rows, columns, i)
Here rows and columns are the total number of rows and columns in the figure and i is the position at which new subplot must be placed.
Steps:
- Import required libraries
- Create a figure
- Set values of rows and column variables
- Read images
- Add subplot and display image one by one
Consider below Images used as input:
Image1
Image2
Image3
Image4
Below is the implementation :
Python3
# code for displaying multiple images in one figure #import librariesimport cv2from matplotlib import pyplot as plt # create figurefig = plt.figure(figsize=(10, 7)) # setting values to rows and column variablesrows = 2columns = 2 # reading imagesImage1 = cv2.imread('Image1.jpg')Image2 = cv2.imread('Image2.jpg')Image3 = cv2.imread('Image3.jpg')Image4 = cv2.imread('Image4.jpg') # Adds a subplot at the 1st positionfig.add_subplot(rows, columns, 1) # showing imageplt.imshow(Image1)plt.axis('off')plt.title("First") # Adds a subplot at the 2nd positionfig.add_subplot(rows, columns, 2) # showing imageplt.imshow(Image2)plt.axis('off')plt.title("Second") # Adds a subplot at the 3rd positionfig.add_subplot(rows, columns, 3) # showing imageplt.imshow(Image3)plt.axis('off')plt.title("Third") # Adds a subplot at the 4th positionfig.add_subplot(rows, columns, 4) # showing imageplt.imshow(Image4)plt.axis('off')plt.title("Fourth") |
Output:



