Complete Guide to Plotting Images Side by Side Using Matplotlib

Nov 21, 2025 · Programming · 10 views · 7.8

Keywords: Matplotlib | Subplots | Image Display | Python Visualization | Data Visualization

Abstract: This article provides a comprehensive guide to correctly displaying multiple images side by side using the Matplotlib library. By analyzing common error cases, it explains the proper usage of subplots function, including two efficient methods: 2D array indexing and flattened iteration. The article delves into the differences between Axes objects and pyplot interfaces, offering complete code examples and best practice recommendations to help readers master the core techniques of side-by-side image display.

Introduction

In the fields of data visualization and image processing, there is often a need to display multiple images side by side for comparative analysis. Matplotlib, as the most popular plotting library in Python, provides powerful subplot functionality to meet this requirement. However, many beginners encounter issues with images not displaying correctly. This article systematically introduces the correct implementation methods.

Common Error Analysis

In the original problem, the user attempted to implement side-by-side image display using the following code:

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

The fundamental issue with this approach lies in misunderstanding the return value of the plt.imshow() function. plt.imshow() returns a matplotlib.image.AxesImage object, not an Axes object. When attempting to assign this return value to elements in the axarr array, it actually overwrites the original subplot Axes objects, causing subsequent images to fail to display correctly.

Correct Implementation Methods

Method 1: Direct Indexing Access

The most straightforward method is to use the imshow method of Axes objects:

import matplotlib.pyplot as plt

# Create a 2x2 subplot grid
fig, axarr = plt.subplots(2, 2)

# Display images on each subplot
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])

plt.show()

The key to this method is understanding Matplotlib's object hierarchy. When calling plt.subplots(2, 2), the returned axarr is a 2x2 NumPy array where each element is an Axes object. These Axes objects provide the same plotting methods as the pyplot module, including imshow, plot, scatter, etc.

Method 2: Flattened Iteration

For scenarios involving a large number of images, the flattened iteration approach is more efficient:

import matplotlib.pyplot as plt

# Assuming there are 4 images
n_row, n_col = 2, 2
fig, axs = plt.subplots(n_row, n_col, figsize=(12, 12))

# Flatten the 2D array into 1D
axs_flat = axs.flatten()

# Use zip to iterate over images and corresponding Axes objects simultaneously
for img, ax in zip(image_datas, axs_flat):
    ax.imshow(img)

plt.show()

This method offers better scalability. When the number of images changes, only the n_row and n_col parameters need adjustment, without manual index management.

Deep Understanding of Axes Objects

Matplotlib employs an object-oriented design pattern where Figure objects represent the entire canvas and Axes objects represent specific subplot regions. Understanding this hierarchy is crucial for proper Matplotlib usage.

The pyplot module provides a convenient MATLAB-style interface, but when dealing with complex graphics, directly manipulating Axes objects is more flexible and powerful. Each Axes object contains a complete set of plotting methods, such as:

# Line plot
ax.plot(x, y)

# Scatter plot
ax.scatter(x, y)

# Bar chart
ax.bar(x, height)

# Image display
ax.imshow(image_data)

This design makes it very simple to use different plot types on different subplots.

Advanced Configuration Techniques

Adjusting Subplot Spacing

Use plt.subplots_adjust for fine control over spacing between subplots:

fig, axs = plt.subplots(2, 2, figsize=(10, 10))
plt.subplots_adjust(wspace=0.3, hspace=0.3)  # Adjust horizontal and vertical spacing

Adding Titles and Labels

Add independent titles for each subplot:

fig, axs = plt.subplots(2, 2)
axs[0, 0].imshow(image1)
axs[0, 0].set_title("Image 1")
axs[0, 1].imshow(image2)
axs[0, 1].set_title("Image 2")
# Continue with other subplots...

Hiding Axes

For pure image display, hide axes for a cleaner visual effect:

for ax in axs.flat:
    ax.set_xticks([])
    ax.set_yticks([])
    ax.set_xlabel("")
    ax.set_ylabel("")

Practical Application Example

Suppose we need to compare the effects of different filtering algorithms on images:

import matplotlib.pyplot as plt
import numpy as np
from skimage import data, filters

# Load sample image
original_image = data.camera()

# Apply different filters
sobel_image = filters.sobel(original_image)
prewitt_image = filters.prewitt(original_image)
roberts_image = filters.roberts(original_image)

images = [original_image, sobel_image, prewitt_image, roberts_image]
titles = ["Original", "Sobel", "Prewitt", "Roberts"]

# Create subplots
fig, axs = plt.subplots(2, 2, figsize=(10, 8))
axs_flat = axs.flatten()

for img, title, ax in zip(images, titles, axs_flat):
    ax.imshow(img, cmap="gray")
    ax.set_title(title)
    ax.set_xticks([])
    ax.set_yticks([])

plt.tight_layout()
plt.show()

Best Practices Summary

1. Understand Object Hierarchy: Clarify the relationships between Figure, Axes, Axis objects

2. Use Axes Methods: Use ax.imshow() instead of plt.imshow() when plotting on subplots

3. Flexible Index Selection: Choose between direct indexing or flattened iteration based on image count

4. Reasonable Layout Configuration: Use tight_layout() or subplots_adjust() to optimize display

5. Consider Performance: Flattened iteration method offers advantages when handling large numbers of images

Conclusion

Mastering the correct usage of Matplotlib subplots is essential for effective data visualization. By understanding how Axes objects work and adopting appropriate programming patterns, complex multi-image side-by-side display requirements can be easily achieved. The methods introduced in this article are not only applicable to image display but can also be extended to other types of charts, providing powerful visualization support for scientific computing and data analysis.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.