0
0
Matplotlibdata~5 mins

Axes creation with add_subplot in Matplotlib

Choose your learning style9 modes available
Introduction

We use add_subplot to add one or more plots inside a figure. It helps organize multiple graphs in rows and columns.

When you want to show multiple charts in one window.
When comparing different data sets side by side.
When you want to create a grid of plots for better visualization.
When you want to add a single plot to an existing figure.
When you want to control the position of each plot inside the figure.
Syntax
Matplotlib
ax = fig.add_subplot(nrows, ncols, index)

# or using a 3-digit code
ax = fig.add_subplot(abc)  # where a=nrows, b=ncols, c=index

nrows and ncols define the grid size.

index is the position of the subplot (starts at 1).

Examples
This creates a 2x2 grid and adds two subplots in the first and second positions.
Matplotlib
fig = plt.figure()
ax1 = fig.add_subplot(2, 2, 1)  # top-left plot
ax2 = fig.add_subplot(2, 2, 2)  # top-right plot
Using the 3-digit code 111 means 1 row, 1 column, 1st plot (just one plot).
Matplotlib
fig = plt.figure()
ax = fig.add_subplot(111)  # single plot in 1x1 grid
This adds a subplot in the middle of a vertical stack of 3 plots.
Matplotlib
fig = plt.figure()
ax = fig.add_subplot(3, 1, 2)  # middle plot in 3 rows, 1 column
Sample Program

This code creates a figure with 4 plots arranged in 2 rows and 2 columns. Each plot shows a simple line graph with a title.

Matplotlib
import matplotlib.pyplot as plt

fig = plt.figure(figsize=(6, 4))

# Create a 2x2 grid of plots
ax1 = fig.add_subplot(2, 2, 1)
ax2 = fig.add_subplot(2, 2, 2)
ax3 = fig.add_subplot(2, 2, 3)
ax4 = fig.add_subplot(2, 2, 4)

# Plot simple lines in each subplot
ax1.plot([1, 2, 3], [1, 4, 9])
ax1.set_title('Plot 1')

ax2.plot([1, 2, 3], [2, 3, 4])
ax2.set_title('Plot 2')

ax3.plot([1, 2, 3], [5, 2, 1])
ax3.set_title('Plot 3')

ax4.plot([1, 2, 3], [3, 6, 9])
ax4.set_title('Plot 4')

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

The index in add_subplot starts at 1, not 0.

You can use plt.subplots() for a simpler way to create multiple axes, but add_subplot gives more control.

Remember to call plt.show() to display the figure.

Summary

add_subplot helps add one or more plots inside a figure in a grid layout.

You specify the grid size and position to control where each plot appears.

This is useful for comparing multiple charts in one window.