0
0
Matplotlibdata~5 mins

Multiple images in subplot grid in Matplotlib

Choose your learning style9 modes available
Introduction

We use multiple images in a subplot grid to compare pictures side by side easily. It helps us see differences or patterns quickly.

Comparing photos from different cameras or settings.
Showing steps of an image processing task.
Displaying different views of the same object.
Presenting multiple charts or heatmaps together.
Visualizing results from different experiments.
Syntax
Matplotlib
import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows, ncols)

for i, ax in enumerate(axes.flat):
    ax.imshow(image_list[i])
    ax.axis('off')

plt.show()

plt.subplots(nrows, ncols) creates a grid of plots.

Use axes.flat to loop through all subplot axes easily.

Examples
Two images side by side in one row.
Matplotlib
fig, axes = plt.subplots(1, 2)
axes[0].imshow(img1)
axes[1].imshow(img2)
plt.show()
Four images in a 2x2 grid with axes turned off.
Matplotlib
fig, axes = plt.subplots(2, 2)
for i, ax in enumerate(axes.flat):
    ax.imshow(images[i])
    ax.axis('off')
plt.show()
Sample Program

This code creates 4 colored square images and shows them in a 2x2 grid with titles and no axes.

Matplotlib
import matplotlib.pyplot as plt
import numpy as np

# Create 4 simple images with different colors
images = []
colors = [(1, 0, 0), (0, 1, 0), (0, 0, 1), (1, 1, 0)]  # Red, Green, Blue, Yellow
for color in colors:
    img = np.ones((10, 10, 3)) * color
    images.append(img)

fig, axes = plt.subplots(2, 2, figsize=(6, 6))
for i, ax in enumerate(axes.flat):
    ax.imshow(images[i])
    ax.axis('off')
    ax.set_title(f'Image {i+1}')

plt.tight_layout()
plt.show()
OutputSuccess
Important Notes

Use ax.axis('off') to hide axis ticks and labels for cleaner image display.

Adjust figsize to control the overall size of the subplot grid.

Use plt.tight_layout() to prevent overlapping titles or images.

Summary

Multiple images can be shown in a grid using plt.subplots().

Loop through axes with axes.flat to place images easily.

Turn off axes and add titles for better presentation.