0
0
MatplotlibHow-ToBeginner ยท 3 min read

How to Use plt.subplots in Matplotlib: Simple Guide

Use plt.subplots() to create a figure and one or more axes (plots) in matplotlib. It returns a tuple with the figure and axes objects, which you can use to customize and display your plots.
๐Ÿ“

Syntax

The basic syntax of plt.subplots() is:

  • fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(width, height))
  • fig is the figure object that holds everything.
  • ax is the axes object or array of axes where you draw your plots.
  • nrows and ncols specify the grid layout of subplots.
  • figsize sets the size of the figure in inches.
python
fig, ax = plt.subplots(nrows=2, ncols=3, figsize=(10, 6))
๐Ÿ’ป

Example

This example creates a 2x2 grid of subplots and plots simple line charts on each.

python
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)

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

for i, ax in enumerate(axs.flat):
    ax.plot(x, np.sin(x + i))
    ax.set_title(f'Subplot {i+1}')

plt.tight_layout()
plt.show()
Output
A window with 4 line plots arranged in 2 rows and 2 columns, each showing a sine wave shifted by subplot index.
โš ๏ธ

Common Pitfalls

Common mistakes when using plt.subplots() include:

  • Not unpacking the returned tuple correctly, especially when creating multiple subplots.
  • For a single subplot, ax is not an array but a single object, so trying to iterate over it causes errors.
  • Not using plt.tight_layout() to avoid overlapping labels and titles.
python
import matplotlib.pyplot as plt

# Wrong: Trying to iterate over ax when only one subplot
fig, ax = plt.subplots()
for a in [ax]:
    a.plot([1, 2, 3], [4, 5, 6])  # This will not raise an error but is unnecessary

# Right: Use ax directly without iteration
fig, ax = plt.subplots()
ax.plot([1, 2, 3], [4, 5, 6])
plt.show()
Output
Error: 'AxesSubplot' object is not iterable for the wrong code; a single plot window for the right code.
๐Ÿ“Š

Quick Reference

ParameterDescriptionDefault
nrowsNumber of rows of subplots1
ncolsNumber of columns of subplots1
figsizeSize of the figure in inches (width, height)(6.4, 4.8)
sharexShare x-axis among subplots (True/False)False
shareyShare y-axis among subplots (True/False)False
squeezeReduce dimensions of returned axes arrayTrue
โœ…

Key Takeaways

Use plt.subplots() to create figure and axes objects together for easy plotting.
Unpack the returned tuple correctly: fig, ax = plt.subplots().
For multiple subplots, ax is an array; for one subplot, ax is a single object.
Use plt.tight_layout() to prevent overlapping plot elements.
Set nrows and ncols to arrange multiple plots in a grid.