0
0
Matplotlibdata~5 mins

Small multiples (facet grid) in Matplotlib

Choose your learning style9 modes available
Introduction

Small multiples help you compare many similar charts side by side. They make it easy to see patterns across groups.

You want to compare sales trends for different products over time.
You need to show temperature changes for multiple cities in one view.
You want to explore how different groups behave in a dataset.
You want to spot differences or similarities across categories quickly.
Syntax
Matplotlib
import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows, ncols, figsize=(width, height))

for ax, data_subset in zip(axes.flat, data_groups):
    ax.plot(x_values, y_values_for_subset)
    ax.set_title('Group name')

plt.tight_layout()
plt.show()

You create a grid of plots using plt.subplots().

Loop over each subplot and plot data for each group.

Examples
Creates a 2x2 grid of simple line plots.
Matplotlib
fig, axes = plt.subplots(2, 2)

for ax in axes.flat:
    ax.plot([1, 2, 3], [1, 4, 9])

plt.show()
Creates 3 bar charts side by side with titles.
Matplotlib
fig, axes = plt.subplots(1, 3, figsize=(9, 3))

for i, ax in enumerate(axes):
    ax.bar([1, 2, 3], [i+1, i+2, i+3])
    ax.set_title(f'Group {i+1}')

plt.tight_layout()
plt.show()
Sample Program

This code creates a 2x2 grid of line charts. Each chart shows sales over months for one product. This helps compare sales trends side by side.

Matplotlib
import matplotlib.pyplot as plt
import pandas as pd

# Sample data: sales for 4 products over 4 months
sales_data = pd.DataFrame({
    'Month': ['Jan', 'Jan', 'Jan', 'Jan', 'Feb', 'Feb', 'Feb', 'Feb', 'Mar', 'Mar', 'Mar', 'Mar', 'Apr', 'Apr', 'Apr', 'Apr'],
    'Product': ['A', 'B', 'C', 'D'] * 4,
    'Sales': [10, 15, 7, 12, 12, 18, 9, 14, 14, 20, 11, 16, 13, 22, 12, 18]
})

# Prepare figure with 2 rows and 2 columns
fig, axes = plt.subplots(2, 2, figsize=(10, 6))

# Get unique products
products = sales_data['Product'].unique()

# Plot sales for each product in its own subplot
for ax, product in zip(axes.flat, products):
    data = sales_data[sales_data['Product'] == product]
    ax.plot(data['Month'], data['Sales'], marker='o')
    ax.set_title(f'Product {product}')
    ax.set_xlabel('Month')
    ax.set_ylabel('Sales')

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

Use plt.tight_layout() to avoid overlapping labels.

Make sure the number of subplots matches the number of groups.

You can customize each subplot independently inside the loop.

Summary

Small multiples show many charts side by side for easy comparison.

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

Loop over each subplot to plot data for each group separately.