Fig, ax = plt.subplots pattern in Matplotlib - Time & Space Complexity
We want to understand how the time it takes to create plots with plt.subplots changes as we increase the number of plots.
How does adding more subplots affect the work matplotlib does?
Analyze the time complexity of the following code snippet.
import matplotlib.pyplot as plt
fig, axs = plt.subplots(3, 3)
for i, ax in enumerate(axs.flat):
ax.plot([0, 1, 2], [i, i+1, i+2])
plt.show()
This code creates a 3 by 3 grid of plots and draws a simple line on each subplot.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping over each subplot to draw a line.
- How many times: Once for each subplot, here 9 times (3 rows x 3 columns).
As the number of subplots increases, the time to draw each line grows proportionally.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 subplots | 10 line plots drawn |
| 100 subplots | 100 line plots drawn |
| 1000 subplots | 1000 line plots drawn |
Pattern observation: The work grows directly with the number of subplots.
Time Complexity: O(n)
This means the time to create and draw on subplots grows linearly with how many subplots you have.
[X] Wrong: "Creating multiple subplots happens instantly no matter how many there are."
[OK] Correct: Each subplot requires drawing operations, so more subplots mean more work and more time.
Understanding how plotting scales helps you write efficient code when working with many charts or dashboards.
"What if we added nested loops to plot multiple lines per subplot? How would the time complexity change?"