Nested subplots with subfigures in Matplotlib - Time & Space Complexity
When creating nested subplots with subfigures in matplotlib, the time to draw the figure depends on how many plots we make.
We want to know how the drawing time grows as we add more subplots inside subfigures.
Analyze the time complexity of the following code snippet.
import matplotlib.pyplot as plt
fig = plt.figure(constrained_layout=True)
subfigs = fig.subfigures(2, 1)
for subfig in subfigs:
axs = subfig.subplots(2, 2)
for ax in axs.flat:
ax.plot([1, 2, 3], [1, 4, 9])
plt.show()
This code creates a figure with 2 subfigures stacked vertically. Each subfigure has a 2x2 grid of subplots, and each subplot draws a simple line plot.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Plotting on each subplot inside nested loops.
- How many times: Outer loop runs 2 times (for subfigures), inner loop runs 4 times (for subplots), total 8 plots.
As the number of subfigures and subplots per subfigure increases, the total plots grow by multiplying these counts.
| Input Size (n = subplots per subfigure) | Approx. Operations (plots) |
|---|---|
| 2 subfigures, 2x2 subplots (4) | 8 |
| 2 subfigures, 10x10 subplots (100) | 200 |
| 3 subfigures, 20x20 subplots (400) | 1200 |
Pattern observation: Total plots grow by multiplying number of subfigures and number of subplots per subfigure.
Time Complexity: O(m * n^2)
This means the time grows proportionally to the number of subfigures (m) times the square of the number of subplots per subfigure (n), since subplots are arranged in an n x n grid.
[X] Wrong: "Adding more subplots inside subfigures only adds a small fixed time, so complexity stays the same."
[OK] Correct: Each subplot requires drawing operations, so total time grows with the total number of subplots, not fixed.
Understanding how nested plotting scales helps you reason about performance in data visualization tasks, a useful skill in many projects.
"What if we changed the number of subfigures dynamically based on data size? How would the time complexity change?"