0
0
Matplotlibdata~15 mins

Nested subplots with subfigures in Matplotlib - Deep Dive

Choose your learning style9 modes available
Overview - Nested Subplots With Subfigures
What is it?
Nested subplots with subfigures is a way to organize multiple plots inside a single figure using groups called subfigures. Each subfigure can contain its own grid of smaller plots, allowing complex layouts. This helps display related data side-by-side clearly. It is useful when you want to compare groups of plots within one overall figure.
Why it matters
Without nested subplots and subfigures, arranging many plots in a clear, organized way is hard and messy. You might end up with cluttered visuals that confuse the viewer. This concept solves the problem of showing multiple related charts in a structured way, making data stories easier to understand and compare. It saves time and improves communication in reports and presentations.
Where it fits
Before learning nested subplots with subfigures, you should know basic plotting with matplotlib and how to create simple subplots. After mastering this, you can explore advanced figure customization, interactive plotting, and dashboard creation. This topic fits in the middle of the matplotlib learning path, bridging simple plots and complex figure layouts.
Mental Model
Core Idea
Nested subplots with subfigures let you group and arrange multiple plots inside smaller figure sections within a main figure, creating clear, organized visual layouts.
Think of it like...
Imagine a photo album where each page (subfigure) holds several photos (subplots). Each page groups related photos together, and the album holds all pages in order. This helps you find and compare photos easily.
Main Figure
┌─────────────────────────────┐
│ Subfigure 1      Subfigure 2│
│ ┌─────┐        ┌─────┐      │
│ │Plot1│ Plot2  │Plot3│ Plot4│
│ └─────┘        └─────┘      │
│ Subfigure 3                │
│ ┌─────┬─────┐             │
│ │Plot5│Plot6│             │
│ └─────┴─────┘             │
└─────────────────────────────┘
Build-Up - 7 Steps
1
FoundationBasic Figure and Single Plot
🤔
Concept: Learn how to create a simple figure with one plot using matplotlib.
import matplotlib.pyplot as plt fig, ax = plt.subplots() ax.plot([1, 2, 3], [4, 5, 6]) plt.show()
Result
A single line plot appears in a window.
Understanding how to create a basic figure and plot is the foundation for building more complex layouts.
2
FoundationCreating Multiple Subplots
🤔
Concept: Learn how to create multiple plots arranged in a grid inside one figure.
fig, axs = plt.subplots(2, 2) # 2 rows, 2 columns axs[0, 0].plot([1, 2], [3, 4]) axs[0, 1].bar([1, 2], [5, 6]) axs[1, 0].scatter([1, 2], [7, 8]) axs[1, 1].hist([1, 2, 2, 3]) plt.show()
Result
A figure with 4 different plots arranged in 2 rows and 2 columns.
Knowing how to arrange multiple plots in a grid helps you compare different data visualizations side-by-side.
3
IntermediateIntroduction to Subfigures
🤔
Concept: Learn how to create subfigures inside a main figure to group plots logically.
fig = plt.figure(constrained_layout=True) subfigs = fig.subfigures(1, 2) # 1 row, 2 columns of subfigures ax1 = subfigs[0].subplots() ax2 = subfigs[1].subplots() ax1.plot([1, 2, 3], [3, 2, 1]) ax2.bar([1, 2, 3], [4, 5, 6]) plt.show()
Result
A figure with two subfigures side-by-side, each containing one plot.
Subfigures let you group related plots separately, improving organization and clarity.
4
IntermediateNested Subplots Inside Subfigures
🤔Before reading on: do you think subfigures can contain multiple subplots arranged in grids? Commit to your answer.
Concept: Learn how to create multiple subplots inside each subfigure to build nested layouts.
fig = plt.figure(constrained_layout=True) subfigs = fig.subfigures(1, 2) axs1 = subfigs[0].subplots(2, 1) # 2 rows, 1 column axs2 = subfigs[1].subplots(1, 2) # 1 row, 2 columns axs1[0].plot([1, 2], [3, 4]) axs1[1].bar([1, 2], [5, 6]) axs2[0].scatter([1, 2], [7, 8]) axs2[1].hist([1, 2, 2, 3]) plt.show()
Result
A figure with two subfigures; the first has two stacked plots, the second has two side-by-side plots.
Knowing that subfigures can hold multiple subplots allows you to create complex, nested visual layouts.
5
IntermediateCustomizing Nested Layouts
🤔Before reading on: do you think nested subplots can have independent titles and labels? Commit to your answer.
Concept: Learn how to add titles and labels to subfigures and subplots independently for clarity.
fig = plt.figure(constrained_layout=True) subfigs = fig.subfigures(1, 2) subfigs[0].suptitle('Group 1') subfigs[1].suptitle('Group 2') axs1 = subfigs[0].subplots(2, 1) axs2 = subfigs[1].subplots(1, 2) axs1[0].set_title('Line Plot') axs1[1].set_title('Bar Plot') axs2[0].set_title('Scatter Plot') axs2[1].set_title('Histogram') plt.show()
Result
Each subfigure and subplot has its own title, making the layout easy to understand.
Independent titles and labels help viewers quickly grasp the meaning of each plot group.
6
AdvancedHandling Complex Nested Layouts
🤔Before reading on: do you think nested subplots can be combined with gridspec for more control? Commit to your answer.
Concept: Learn how to use gridspec with subfigures to control spacing and size ratios in nested layouts.
import matplotlib.gridspec as gridspec fig = plt.figure(constrained_layout=True) gs = gridspec.GridSpec(1, 2, figure=fig, width_ratios=[2, 1]) subfig1 = fig.subfigures(1, 1, subplot_spec=gs[0]) subfig2 = fig.subfigures(1, 1, subplot_spec=gs[1]) axs1 = subfig1.subplots(2, 1) axs2 = subfig2.subplots(1, 1) axs1[0].plot([1, 2], [3, 4]) axs1[1].bar([1, 2], [5, 6]) axs2[0].scatter([1, 2], [7, 8]) plt.show()
Result
A figure with two subfigures sized differently, containing nested subplots arranged precisely.
Combining gridspec with subfigures gives fine control over complex figure layouts.
7
ExpertPerformance and Limitations of Nested Subfigures
🤔Before reading on: do you think deeply nested subfigures affect rendering speed or interactivity? Commit to your answer.
Concept: Understand the performance impact and limitations when using many nested subfigures and subplots.
When creating many nested subfigures and subplots, rendering can slow down, especially with interactive backends. Also, some matplotlib features like tight_layout may not work well with subfigures. Knowing these limits helps you design efficient, maintainable figures.
Result
Awareness of performance trade-offs and feature limitations when nesting subfigures deeply.
Understanding these limits prevents frustration and guides better figure design choices in real projects.
Under the Hood
Matplotlib's figure is a container for all plot elements. Subfigures are special containers inside a figure that can hold their own axes (plots). When you create subfigures, matplotlib internally manages separate coordinate systems and layout managers for each subfigure. This allows independent control of spacing and sizing. Nested subplots inside subfigures are axes objects arranged by layout managers like GridSpec within each subfigure. The rendering engine draws each subfigure and its axes in order, composing the final image.
Why designed this way?
Subfigures were introduced to solve the problem of organizing complex plot groups cleanly. Earlier, only flat grids of subplots existed, which became hard to manage for many plots. Subfigures allow logical grouping and independent control of plot groups. The design balances flexibility and simplicity, using existing layout tools like GridSpec internally. Alternatives like manual positioning were too error-prone and inflexible.
Figure
┌─────────────────────────────┐
│ Subfigure 1                 │
│ ┌───────────────┐          │
│ │ Subplots Grid │          │
│ │ ┌─────┬─────┐ │          │
│ │ │ Ax1 │ Ax2 │ │          │
│ │ └─────┴─────┘ │          │
│ └───────────────┘          │
│ Subfigure 2                 │
│ ┌───────────────┐          │
│ │ Subplots Grid │          │
│ │ ┌─────┐       │          │
│ │ │ Ax3 │       │          │
│ │ └─────┘       │          │
│ └───────────────┘          │
└─────────────────────────────┘
Myth Busters - 3 Common Misconceptions
Quick: Do you think subfigures are just the same as subplots arranged differently? Commit to yes or no.
Common Belief:Subfigures are just fancy subplots; they don't add new functionality.
Tap to reveal reality
Reality:Subfigures are containers that can hold multiple subplots and have independent layout and titles, unlike simple subplots which are just axes arranged in a grid.
Why it matters:Confusing subfigures with subplots limits your ability to organize complex figures and leads to cluttered, hard-to-read plots.
Quick: Do you think nested subplots always improve clarity? Commit to yes or no.
Common Belief:Adding more nested subplots always makes the figure clearer and better.
Tap to reveal reality
Reality:Too many nested subplots can overwhelm viewers and slow rendering, reducing clarity and usability.
Why it matters:Overusing nested layouts can confuse the audience and cause performance issues, defeating the purpose of organized visualization.
Quick: Do you think tight_layout works perfectly with subfigures? Commit to yes or no.
Common Belief:tight_layout automatically adjusts spacing for all nested subplots and subfigures.
Tap to reveal reality
Reality:tight_layout does not fully support subfigures; constrained_layout or manual adjustments are needed.
Why it matters:Relying on tight_layout with subfigures can cause overlapping labels and poor spacing, hurting figure readability.
Expert Zone
1
Subfigures maintain independent coordinate systems, allowing different aspect ratios and scales within the same figure.
2
Using constrained_layout with subfigures can sometimes conflict with manual adjustments, requiring careful tuning.
3
Nested subfigures can complicate event handling in interactive backends, affecting zoom and pan behavior.
When NOT to use
Avoid nested subfigures when your figure is simple or when performance is critical; use flat subplots or separate figures instead. For highly interactive dashboards, consider specialized tools like Plotly Dash or Bokeh.
Production Patterns
Professionals use nested subfigures to group related experiment results or different data categories in scientific papers. They combine subfigures with gridspec for precise control and add shared legends or annotations at the subfigure level for clarity.
Connections
Modular UI Design
Both organize complex interfaces into nested, manageable components.
Understanding nested subfigures helps grasp how modular UI frameworks break down screens into reusable parts.
Hierarchical File Systems
Both use nested containers (folders or subfigures) to organize many items logically.
Recognizing this similarity aids in understanding how to structure complex data visually.
Book Chapters and Sections
Subfigures are like chapters grouping related plots (sections) within a book (figure).
This connection shows how nested organization improves comprehension by grouping related content.
Common Pitfalls
#1Trying to use tight_layout with subfigures expecting automatic spacing.
Wrong approach:fig.tight_layout() # followed by creating subfigures and subplots
Correct approach:fig = plt.figure(constrained_layout=True) # then create subfigures and subplots
Root cause:tight_layout does not support subfigures well; constrained_layout is designed for this.
#2Creating too many nested subplots causing clutter and slow rendering.
Wrong approach:fig = plt.figure() subfigs = fig.subfigures(3, 3) for sf in subfigs.flatten(): axs = sf.subplots(3, 3) # plot many axes
Correct approach:Limit the number of nested subplots or split into multiple figures for clarity and performance.
Root cause:Misunderstanding the performance and readability limits of nested layouts.
#3Using subfigures but treating them like simple subplots without titles or grouping.
Wrong approach:fig = plt.figure() subfigs = fig.subfigures(1, 2) ax1 = subfigs[0].subplots() ax2 = subfigs[1].subplots() # no titles or labels on subfigures
Correct approach:subfigs[0].suptitle('Group 1') subfigs[1].suptitle('Group 2') # add titles to clarify groups
Root cause:Not leveraging subfigure features reduces their organizational benefit.
Key Takeaways
Nested subplots with subfigures let you organize complex figures by grouping related plots inside smaller figure sections.
Subfigures provide independent layout control, titles, and coordinate systems, improving clarity and flexibility.
Combining subfigures with layout tools like gridspec and constrained_layout enables precise, readable visualizations.
Overusing nested subfigures can harm performance and clarity; use them thoughtfully with attention to layout and audience.
Understanding subfigures bridges simple plotting and advanced figure design, essential for professional data visualization.