0
0
Pandasdata~5 mins

Subplots for multiple charts in Pandas

Choose your learning style9 modes available
Introduction

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

You want to compare sales data for different products side by side.
You need to show temperature changes for multiple cities in one image.
You want to display different parts of a dataset separately but together.
You are presenting data trends for several groups in one report.
Syntax
Pandas
import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows=number_of_rows, ncols=number_of_columns)

# Use axes[row, col] to plot each chart
axes[0, 0].plot(data1)
axes[0, 1].plot(data2)

plt.show()

plt.subplots() creates a grid of plots.

axes is an array of plot areas you fill with charts.

Examples
Creates 1 row and 2 columns of plots side by side.
Pandas
fig, axes = plt.subplots(1, 2)
axes[0].plot([1, 2, 3])
axes[1].plot([3, 2, 1])
plt.show()
Creates 2 rows and 1 column of bar charts stacked vertically.
Pandas
fig, axes = plt.subplots(2, 1)
axes[0].bar([1, 2, 3], [4, 5, 6])
axes[1].bar([1, 2, 3], [6, 5, 4])
plt.show()
Creates a 2x2 grid of different charts.
Pandas
fig, axes = plt.subplots(2, 2)
axes[0, 0].plot([1, 2, 3])
axes[0, 1].plot([3, 2, 1])
axes[1, 0].bar([1, 2], [5, 7])
axes[1, 1].bar([1, 2], [7, 5])
plt.show()
Sample Program

This code shows sales trends for 4 products in a 2 by 2 grid of line charts. Each chart has a title and markers on points.

Pandas
import pandas as pd
import matplotlib.pyplot as plt

# Create sample data
sales = pd.DataFrame({
    'Product A': [10, 15, 20, 25],
    'Product B': [5, 7, 12, 18],
    'Product C': [8, 12, 15, 22],
    'Product D': [3, 5, 7, 10]
}, index=['Q1', 'Q2', 'Q3', 'Q4'])

# Create 2x2 subplots
fig, axes = plt.subplots(2, 2, figsize=(10, 8))

# Plot each product sales in a subplot
axes[0, 0].plot(sales.index, sales['Product A'], marker='o')
axes[0, 0].set_title('Product A Sales')

axes[0, 1].plot(sales.index, sales['Product B'], marker='o')
axes[0, 1].set_title('Product B Sales')

axes[1, 0].plot(sales.index, sales['Product C'], marker='o')
axes[1, 0].set_title('Product C Sales')

axes[1, 1].plot(sales.index, sales['Product D'], marker='o')
axes[1, 1].set_title('Product D Sales')

# Improve layout
plt.tight_layout()
plt.show()
OutputSuccess
Important Notes

Use figsize to control the size of the whole plot area.

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

Access subplots with axes[row, col] for grids or axes[index] for 1D arrays.

Summary

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

Use plt.subplots() to create a grid of plots.

Fill each subplot by selecting it from the axes array.