Python Matplotlib Subplot – A Complete Guide

Last updated 4 weeks, 1 day ago | 93 views 75     5

When working with multiple plots, displaying them in a grid layout helps present related data in a clean and organized way. This is where Matplotlib’s subplot() and subplots() functions come into play.

This guide walks you through creating subplots, customizing their appearance, sharing axes, and avoiding common mistakes.


What Is a Subplot?

A subplot is a single plot inside a larger figure that contains multiple plots. For example, if you want to display a line chart and a bar chart side by side, you can use subplots.

Matplotlib provides two primary ways to create subplots:

  1. plt.subplot() – older, index-based method

  2. plt.subplots() – preferred, more flexible method using object-oriented approach


Method 1: Using plt.subplot()

Syntax:

plt.subplot(nrows, ncols, index)
  • nrows: number of rows

  • ncols: number of columns

  • index: position (starts from 1)

Example

import matplotlib.pyplot as plt

x = [1, 2, 3, 4]
y1 = [10, 20, 15, 25]
y2 = [5, 15, 10, 20]

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

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

plt.tight_layout()
plt.show()

❗ Limitation:

  • Hard to scale for large subplot grids

  • Doesn’t return axes objects for further customization


Method 2: Using plt.subplots() (Recommended)

Syntax:

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

Returns a Figure and an array of Axes objects.

Example: 2x1 layout

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

x = [1, 2, 3, 4]
y1 = [10, 20, 15, 25]
y2 = [5, 15, 10, 20]

axs[0].plot(x, y1)
axs[0].set_title("Top Plot")

axs[1].plot(x, y2)
axs[1].set_title("Bottom Plot")

plt.tight_layout()
plt.show()

Customizing Subplots

Figure Size

fig, axs = plt.subplots(1, 2, figsize=(10, 4))

Titles and Labels

axs[0].set_title("Line Plot")
axs[1].set_xlabel("X Axis")
axs[1].set_ylabel("Y Axis")

Adding Grids

for ax in axs:
    ax.grid(True)

Shared Axes

fig, axs = plt.subplots(2, 1, sharex=True)
  • sharex=True or sharey=True reduces clutter


Accessing Axes in Multi-Dimensional Layouts

In a grid like 2x2, axs is a 2D NumPy array.

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

axs[0, 0].plot([1, 2, 3], [3, 2, 1])
axs[0, 0].set_title("Top Left")

axs[1, 1].plot([1, 2, 3], [1, 2, 3])
axs[1, 1].set_title("Bottom Right")

You can also flatten the array:

axs = axs.flatten()

Full Example with Custom Layout

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y1 = [10, 20, 15, 25, 30]
y2 = [5, 10, 8, 20, 18]
y3 = [2, 4, 6, 8, 10]
y4 = [30, 25, 20, 15, 10]

fig, axs = plt.subplots(2, 2, figsize=(10, 6))

axs[0, 0].plot(x, y1, color='blue')
axs[0, 0].set_title("Sales")

axs[0, 1].bar(x, y2, color='green')
axs[0, 1].set_title("Revenue")

axs[1, 0].scatter(x, y3, color='red')
axs[1, 0].set_title("Units Sold")

axs[1, 1].plot(x, y4, linestyle='--', marker='o')
axs[1, 1].set_title("Decline Rate")

for ax in axs.flatten():
    ax.set_xlabel("Days")
    ax.set_ylabel("Values")
    ax.grid(True)

plt.tight_layout()
plt.suptitle("Company Metrics", fontsize=16, y=1.02)
plt.show()

Tips for Working with Subplots

Tip Benefit
Use plt.tight_layout() Prevents label overlap
Use sharex and sharey Makes comparison easier
Flatten the axs array Simplifies iteration
Adjust figsize Makes all subplots readable
Use plt.suptitle() Adds a global title

⚠️ Common Pitfalls

Pitfall Solution
Subplots overlap Use plt.tight_layout() or constrained_layout=True
Wrong subplot access Ensure correct indexing (e.g., axs[0, 1] vs axs[1])
Titles/labels clipped Use plt.tight_layout() and plt.suptitle() with y spacing
All plots look the same Customize each subplot individually

Summary Table

Feature Code Example
Create subplot (old) plt.subplot(2, 1, 1)
Create subplot (new) fig, axs = plt.subplots(2, 2)
Set title ax.set_title("...")
Add label ax.set_xlabel("...")
Add grid ax.grid(True)
Share axes sharex=True, sharey=True
Global title plt.suptitle("...")
Layout adjustment plt.tight_layout()

Conclusion

Subplots are a powerful tool in Matplotlib that allow you to present multiple visualizations in one figure. Whether you're comparing metrics, plotting time series, or displaying grouped categories, subplots help you keep your figures clean, organized, and insightful.


What’s Next?

  • Explore GridSpec for advanced subplot layout control

  • Add interactive elements to subplots using matplotlib.widgets

  • Embed subplots in Tkinter GUIs or Dash dashboards