Small multiples help you compare many similar charts side by side. They make it easy to see patterns across groups.
Small multiples (facet grid) in Matplotlib
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
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
Matplotlib
fig, axes = plt.subplots(2, 2) for ax in axes.flat: ax.plot([1, 2, 3], [1, 4, 9]) plt.show()
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()
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.
Practice
1. What is the main purpose of using small multiples (facet grid) in matplotlib?
easy
Solution
Step 1: Understand the concept of small multiples
Small multiples are multiple small charts arranged in a grid to compare different groups or categories easily.Step 2: Identify the purpose in matplotlib
Matplotlib uses small multiples to show many charts side by side, making it easier to compare data visually.Final Answer:
To display multiple related charts side by side for easy comparison -> Option AQuick Check:
Small multiples = multiple charts side by side [OK]
Hint: Small multiples = many small charts for comparison [OK]
Common Mistakes:
- Confusing small multiples with animations
- Thinking it changes colors only
- Assuming it creates one big plot
2. Which of the following is the correct way to create a 2x2 grid of subplots in matplotlib?
easy
Solution
Step 1: Recall plt.subplots() syntax
plt.subplots(rows, columns) creates a grid of subplots with given rows and columns.Step 2: Match the grid size
To create a 2x2 grid, use plt.subplots(2, 2).Final Answer:
fig, axes = plt.subplots(2, 2) -> Option CQuick Check:
plt.subplots(2, 2) = 2 rows and 2 columns [OK]
Hint: Use plt.subplots(rows, columns) for grid size [OK]
Common Mistakes:
- Using single number for grid shape
- Confusing rows and columns
- Missing one dimension in arguments
3. What will be the output of this code snippet?
import matplotlib.pyplot as plt
fig, axes = plt.subplots(1, 3)
data = [1, 2, 3]
for i, ax in enumerate(axes):
ax.plot([data[i]] * 3)
plt.show()medium
Solution
Step 1: Understand plt.subplots(1, 3)
This creates 1 row and 3 columns of subplots, so axes is an array of 3 axes objects.Step 2: Loop plots each subplot
For each axis, it plots a line with three points all equal to data[i] (1, then 2, then 3).Final Answer:
Three line plots each with three points of the same value 1, 2, and 3 respectively -> Option AQuick Check:
Loop over axes plots lines with repeated values [OK]
Hint: Loop over axes to plot each subplot separately [OK]
Common Mistakes:
- Thinking axes is a single plot
- Assuming error due to axes type
- Confusing line plot with scatter plot
4. Identify the error in this code for creating a 2x2 grid of plots:
fig, axes = plt.subplots(2, 2)
for i in range(4):
axes[i].plot([1, 2, 3])
plt.show()medium
Solution
Step 1: Understand axes shape from plt.subplots(2, 2)
axes is a 2x2 numpy array of Axes objects, not a flat list.Step 2: Identify indexing error
axes[i] tries to index a 2D array with one index, causing an error. Correct is axes[row, col] or flatten axes first.Final Answer:
axes is a 2D array, so axes[i] indexing causes an error -> Option DQuick Check:
2D axes need two indices or flatten before looping [OK]
Hint: 2D axes need two indices or flatten before indexing [OK]
Common Mistakes:
- Assuming axes is 1D array
- Ignoring error from wrong indexing
- Thinking plt.show() is missing
5. You have a dataset with sales data for 3 regions. How would you create a 1-row, 3-column grid of plots showing sales trends for each region separately using matplotlib?
hard
Solution
Step 1: Create a 1x3 grid for three regions
Use plt.subplots(1, 3) to create one row and three columns of plots.Step 2: Loop over axes and plot each region's data
Loop through each axis and plot the sales data for each region separately to compare trends side by side.Final Answer:
Use plt.subplots(1, 3), loop over axes, and plot each region's data on each subplot -> Option BQuick Check:
One row, three columns, loop to plot each region [OK]
Hint: Create grid then loop axes to plot groups separately [OK]
Common Mistakes:
- Plotting all data on one plot
- Using wrong grid shape
- Not looping over axes
