0
0
Matplotlibdata~30 mins

Nested subplots with subfigures in Matplotlib - Mini Project: Build & Apply

Choose your learning style9 modes available
Nested subplots with subfigures
📖 Scenario: You are preparing a report with multiple charts. You want to organize these charts neatly using nested subplots and subfigures in matplotlib. This will help you compare different data groups side by side.
🎯 Goal: Create a figure with two subfigures arranged horizontally. Each subfigure contains two vertically stacked subplots showing simple line plots.
📋 What You'll Learn
Create a figure with matplotlib.pyplot.figure() using constrained_layout=True
Create two subfigures arranged in one row and two columns using fig.subfigures()
Each subfigure should have two subplots arranged vertically using subfig.subplots()
Plot simple line plots in each subplot with different data
Display the final figure with plt.show()
💡 Why This Matters
🌍 Real World
Nested subplots with subfigures help organize multiple related charts in reports or presentations, making it easier to compare data groups side by side.
💼 Career
Data scientists and analysts often create complex visualizations to communicate insights clearly. Knowing how to use nested subplots and subfigures is valuable for producing professional-quality charts.
Progress0 / 4 steps
1
Create the main figure with constrained layout
Create a figure called fig using plt.figure() with constrained_layout=True.
Matplotlib
Need a hint?

Use plt.figure(constrained_layout=True) to create the figure.

2
Add two subfigures side by side
Using the figure fig, create two subfigures called subfig1 and subfig2 arranged in 1 row and 2 columns using fig.subfigures(1, 2).
Matplotlib
Need a hint?

Use fig.subfigures(1, 2) to create two subfigures in one row and two columns.

3
Create two vertical subplots in each subfigure and plot lines
For each subfigure subfig1 and subfig2, create two subplots arranged vertically using subfig.subplots(2, 1). Then plot simple line plots on each subplot using ax.plot() with these data: for subfig1 use [1, 2, 3] and [3, 2, 1], for subfig2 use [4, 5, 6] and [6, 5, 4].
Matplotlib
Need a hint?

Use subfig.subplots(2, 1) to create two vertical subplots. Use ax.plot() to draw lines.

4
Display the figure with nested subplots
Use plt.show() to display the figure with the nested subplots and subfigures.
Matplotlib
Need a hint?

Call plt.show() to display the figure.