How to Create Subplots in Matplotlib: Simple Guide
Use
matplotlib.pyplot.subplots() to create multiple plots in one figure. It returns a figure and axes array where you can plot individually. Customize layout by specifying rows and columns in subplots().Syntax
The basic syntax to create subplots is:
fig, axes = plt.subplots(nrows, ncols, figsize=(width, height))nrowsandncolsdefine the grid size of subplots.figsizesets the figure size in inches.figis the overall figure object.axesis an array or single Axes object to plot on.
python
fig, axes = 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 subplot.
python
import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 10, 100) fig, axes = plt.subplots(2, 2, figsize=(8, 6)) axes[0, 0].plot(x, np.sin(x)) axes[0, 0].set_title('Sine Wave') axes[0, 1].plot(x, np.cos(x), 'r') axes[0, 1].set_title('Cosine Wave') axes[1, 0].plot(x, np.tan(x), 'g') axes[1, 0].set_ylim(-10, 10) # Limit y-axis for tan axes[1, 0].set_title('Tangent Wave') axes[1, 1].plot(x, x**2, 'm') axes[1, 1].set_title('Quadratic') plt.tight_layout() plt.show()
Output
A window with 4 plots arranged in 2 rows and 2 columns showing sine, cosine, tangent (limited y-axis), and quadratic curves.
Common Pitfalls
Common mistakes when creating subplots include:
- Not unpacking
axescorrectly when only one subplot is created (it returns a single Axes, not an array). - Indexing
axesincorrectly whennrowsorncolsis 1 (axes can be 1D array or single object). - Forgetting to call
plt.tight_layout()to avoid overlapping labels.
python
import matplotlib.pyplot as plt # Wrong: axes is not an array if only one subplot fig, axes = plt.subplots(1, 1) # axes[0].plot([1, 2, 3]) # This will cause an error # Right: fig, ax = plt.subplots(1, 1) ax.plot([1, 2, 3]) plt.show()
Output
A single plot showing points connected by lines without error.
Quick Reference
Tips for using plt.subplots():
- Use
fig, axes = plt.subplots()to create multiple plots. - Access subplots with
axes[row, col]for 2D grids oraxes[index]for 1D. - Use
figsizeto control figure size. - Call
plt.tight_layout()to prevent overlap. - For a single subplot,
axesis a single Axes object, not an array.
Key Takeaways
Use plt.subplots(nrows, ncols) to create a grid of subplots in one figure.
Access each subplot via the axes array to plot different data.
Remember plt.tight_layout() to avoid overlapping plot elements.
For a single subplot, axes is not an array but a single object.
Set figsize to control the overall size of the subplot figure.