0
0
Matplotlibdata~5 mins

Plt.subplots with rows and columns in Matplotlib

Choose your learning style9 modes available
Introduction

We use plt.subplots to create multiple plots in one figure easily. It helps us compare data side by side.

When you want to show different charts together for comparison.
When you have several related datasets to visualize at once.
When you want to organize plots in a grid layout.
When you want to save space by combining plots in one image.
Syntax
Matplotlib
fig, axes = plt.subplots(nrows=number_of_rows, ncols=number_of_columns)

fig is the whole figure (the window or image).

axes is an array of plots arranged in rows and columns.

Examples
This creates a 2 by 2 grid of plots (4 plots total).
Matplotlib
fig, axes = plt.subplots(nrows=2, ncols=2)
This creates 1 row and 3 columns of plots (3 plots in a row).
Matplotlib
fig, axes = plt.subplots(1, 3)
This creates a single plot (1 row, 1 column by default).
Matplotlib
fig, axes = plt.subplots()
Sample Program

This code creates a 2x2 grid of plots showing different math functions. Each plot has a title. The tight_layout() makes sure plots don't overlap.

Matplotlib
import matplotlib.pyplot as plt
import numpy as np

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

fig, axes = plt.subplots(nrows=2, ncols=2)

axes[0, 0].plot(x, np.sin(x))
axes[0, 0].set_title('sin(x)')

axes[0, 1].plot(x, np.cos(x), 'r')
axes[0, 1].set_title('cos(x)')

axes[1, 0].plot(x, np.tan(x), 'g')
axes[1, 0].set_title('tan(x)')
axes[1, 0].set_ylim(-10, 10)  # limit y to avoid extreme values

axes[1, 1].plot(x, np.log1p(x), 'm')
axes[1, 1].set_title('log1p(x)')

plt.tight_layout()
plt.show()
OutputSuccess
Important Notes

If you create only one plot, axes is not an array but a single object.

You can access each plot by axes[row, column] when you have multiple rows and columns.

Use plt.tight_layout() to avoid overlapping labels and titles.

Summary

plt.subplots helps create multiple plots in a grid.

You get a figure and an array of axes to draw on.

Use rows and columns to organize your plots clearly.