0
0
Data Analysis Pythondata~5 mins

Subplots for multiple charts in Data Analysis Python

Choose your learning style9 modes available
Introduction

Subplots let you show many charts in one picture. This helps compare data easily.

You want to compare sales data from different months side by side.
You need to show temperature and rainfall charts for the same city.
You want to display different parts of a dataset in separate small charts.
You are preparing a report and want all charts in one image for easy viewing.
Syntax
Data Analysis Python
import matplotlib.pyplot as plt

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

axs[row, col].plot(data)
plt.show()

fig is the whole figure holding all charts.

axs is an array of charts you can fill with data.

Examples
Creates 1 row and 2 columns of charts side by side.
Data Analysis Python
fig, axs = plt.subplots(1, 2)
axs[0].plot([1, 2, 3])
axs[1].plot([3, 2, 1])
plt.show()
Creates 2 rows and 2 columns of charts in a grid.
Data Analysis Python
fig, axs = plt.subplots(2, 2)
axs[0, 0].plot([1, 2])
axs[0, 1].plot([2, 3])
axs[1, 0].plot([3, 4])
axs[1, 1].plot([4, 5])
plt.show()
Sample Program

This code creates a 2x2 grid of charts showing squares, cubes, linear, and reverse squares.

Data Analysis Python
import matplotlib.pyplot as plt

# Create 2 rows and 2 columns of charts
fig, axs = plt.subplots(2, 2)

# Data for each chart
x = [1, 2, 3, 4]

# Plot different lines in each subplot
axs[0, 0].plot(x, [1, 4, 9, 16])
axs[0, 0].set_title('Squares')

axs[0, 1].plot(x, [1, 8, 27, 64])
axs[0, 1].set_title('Cubes')

axs[1, 0].plot(x, [1, 2, 3, 4])
axs[1, 0].set_title('Linear')

axs[1, 1].plot(x, [16, 9, 4, 1])
axs[1, 1].set_title('Reverse Squares')

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

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

Indexing in axs depends on the shape: 1D array if one row or column, 2D array if multiple rows and columns.

You can add titles and labels to each subplot for clarity.

Summary

Subplots help show many charts in one figure for easy comparison.

Use plt.subplots(rows, cols) to create a grid of charts.

Access each chart with axs[row, col] and plot your data.