Matplotlib Subplot

Welcome to The Coding College, where we simplify Python programming for learners of all levels. This tutorial covers Matplotlib Subplots, a feature that allows you to visualize multiple plots within a single figure. Subplots are essential for comparing datasets, showcasing trends, and presenting information concisely.

What Are Subplots?

A subplot is a small plot inside a larger figure. With subplots, you can arrange multiple charts side by side or stack them vertically to visualize data effectively.

Creating Subplots

In Matplotlib, subplots can be created using the plt.subplot() or plt.subplots() functions.

1. Using plt.subplot()

The plt.subplot() function creates one subplot at a time, arranged in a grid.

Syntax

plt.subplot(rows, cols, index)  
  • rows: Total number of rows in the grid.
  • cols: Total number of columns in the grid.
  • index: Position of the subplot (starting from 1).

Example

import matplotlib.pyplot as plt  

x = [1, 2, 3, 4, 5]  
y1 = [10, 20, 30, 40, 50]  
y2 = [15, 25, 35, 45, 55]  

plt.subplot(1, 2, 1)  # 1 row, 2 columns, 1st subplot  
plt.plot(x, y1)  
plt.title("Dataset 1")  

plt.subplot(1, 2, 2)  # 1 row, 2 columns, 2nd subplot  
plt.plot(x, y2)  
plt.title("Dataset 2")  

plt.tight_layout()  # Adjust spacing  
plt.show()  

Output: Two horizontally aligned subplots.

2. Using plt.subplots()

The plt.subplots() function creates a grid of subplots at once.

Syntax

fig, axs = plt.subplots(rows, cols)  
  • rows: Number of rows.
  • cols: Number of columns.
  • axs: An array or matrix of axes objects for individual subplots.

Example

fig, axs = plt.subplots(2, 1)  # 2 rows, 1 column  

x = [1, 2, 3, 4, 5]  
y1 = [10, 20, 30, 40, 50]  
y2 = [15, 25, 35, 45, 55]  

axs[0].plot(x, y1)  
axs[0].set_title("Dataset 1")  

axs[1].plot(x, y2)  
axs[1].set_title("Dataset 2")  

plt.tight_layout()  
plt.show()  

Output: Two vertically aligned subplots.

Customizing Subplots

1. Adjusting Space Between Subplots

Use plt.subplots_adjust() or plt.tight_layout() to manage spacing.

fig, axs = plt.subplots(2, 2)  

for i, ax in enumerate(axs.flat):  
    ax.plot(x, [n * val for val in x], label=f"Dataset {i+1}")  
    ax.set_title(f"Plot {i+1}")  
    ax.legend()  

plt.tight_layout()  # Automatically adjust spacing  
plt.show()  

2. Sharing Axes

When multiple subplots share the same data range, you can share their axes for better alignment.

fig, axs = plt.subplots(2, 2, sharex=True, sharey=True)  

for i, ax in enumerate(axs.flat):  
    ax.plot(x, [n * val for val in x])  
    ax.set_title(f"Plot {i+1}")  

plt.tight_layout()  
plt.show()  

3. Adding a Main Title

Use fig.suptitle() to add an overarching title to the figure.

fig, axs = plt.subplots(2, 1)  

axs[0].plot(x, y1)  
axs[0].set_title("Dataset 1")  

axs[1].plot(x, y2)  
axs[1].set_title("Dataset 2")  

fig.suptitle("Comparison of Datasets", fontsize=16)  
plt.tight_layout()  
plt.show()  

Subplot Grid with Different Sizes

Use gridspec for creating subplots with varying sizes.

import matplotlib.gridspec as gridspec  

fig = plt.figure()  
gs = gridspec.GridSpec(2, 2, width_ratios=[2, 1], height_ratios=[1, 2])  

ax1 = fig.add_subplot(gs[0, 0])  # Large plot  
ax2 = fig.add_subplot(gs[0, 1])  # Smaller plot  
ax3 = fig.add_subplot(gs[1, :])  # Wide plot  

ax1.plot(x, y1)  
ax2.plot(x, y2)  
ax3.plot(x, [val * 2 for val in y1])  

plt.tight_layout()  
plt.show()  

Practice Exercises

Exercise 1: Simple Subplots

Create a 2×2 grid of subplots. Plot different datasets in each subplot and add individual titles.

Exercise 2: Custom Grid

Create a figure with:

  • A large subplot on the left.
  • Two smaller subplots stacked on the right.

Common Issues and Solutions

  1. Subplots Overlap
    • Cause: Insufficient space between plots.
    • Solution: Use plt.tight_layout() or plt.subplots_adjust().
  2. Axes Not Aligned
    • Cause: Different scales.
    • Solution: Use sharex and sharey to synchronize axes.

Why Learn with The Coding College?

At The Coding College, we focus on practical and easy-to-follow tutorials. Mastering subplots in Matplotlib will allow you to present data comparisons effectively and professionally.

Conclusion

Subplots in Matplotlib provide a powerful way to visualize multiple datasets within a single figure. By learning to customize and arrange subplots, you can create clear, impactful visualizations tailored to your needs.

Leave a Comment