Data Visualization

Efficiently Displaying Multiple Images in Matplotlib

Spread the love

Matplotlib is a powerful Python library for creating visualizations. A common task is displaying multiple images within a single figure for comparison or to illustrate different aspects of the same data. This article presents two efficient methods for achieving this: using add_subplot() iteratively and creating a reusable function.

Table of Contents

Iterative Subplot Creation with add_subplot()

This approach is ideal when the number of images is dynamic. add_subplot(nrows, ncols, index) creates subplots within a figure, specifying the number of rows, columns, and the current subplot’s index.

import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import os

image_dir = "path/to/your/images"  # Replace with your image directory

image_files = [f for f in os.listdir(image_dir) if os.path.isfile(os.path.join(image_dir, f))]

if not image_files:
    print("No images found in the specified directory.")
else:
    num_images = len(image_files)
    nrows = int(num_images**0.5)
    ncols = (num_images + nrows - 1) // nrows

    fig, axes = plt.subplots(nrows, ncols, figsize=(15, 10))
    axes = axes.ravel()

    for i, image_file in enumerate(image_files):
        image_path = os.path.join(image_dir, image_file)
        img = mpimg.imread(image_path)
        axes[i].imshow(img)
        axes[i].set_title(image_file)
        axes[i].axis('off')

    #Remove any extra subplots
    for j in range(i + 1, len(axes)):
        fig.delaxes(axes[j])


    plt.tight_layout()
    plt.show()

This code iterates through images, reads them using mpimg.imread(), and displays them in subplots. plt.tight_layout() prevents overlap. Remember to replace `”path/to/your/images”` with your directory. The code dynamically adjusts rows and columns for optimal layout and removes empty subplots.

Reusable Function for Image Display

For better code organization and reusability, encapsulate the image display logic within a function:

import matplotlib.pyplot as plt
import matplotlib.image as mpimg

def display_images(image_paths, titles=None, cols=3, figsize=(15, 10)):
    """Displays multiple images in a single figure.

    Args:
        image_paths: A list of image paths.
        titles: (Optional) A list of titles.
        cols: Number of columns in the subplot grid.
        figsize: Figure size.
    """
    num_images = len(image_paths)
    rows = (num_images + cols - 1) // cols
    fig, axes = plt.subplots(rows, cols, figsize=figsize)
    axes = axes.ravel()

    for i, image_path in enumerate(image_paths):
        img = mpimg.imread(image_path)
        axes[i].imshow(img)
        if titles:
            axes[i].set_title(titles[i])
        axes[i].axis('off')

    #Remove any extra subplots
    for j in range(i + 1, len(axes)):
        fig.delaxes(axes[j])

    plt.tight_layout()
    plt.show()

# Example usage:
image_paths = ["path/to/image1.jpg", "path/to/image2.png", "path/to/image3.jpeg"]  # Replace with your image paths
titles = ["Image 1", "Image 2", "Image 3"]
display_images(image_paths, titles)

This function accepts image paths and optional titles, dynamically calculates the subplot grid, and displays the images. It’s more flexible and reusable than the iterative approach. Remember to install Matplotlib: pip install matplotlib.

Leave a Reply

Your email address will not be published. Required fields are marked *