Why multiple plots per figure matter in Matplotlib - Performance Analysis
When we create multiple plots in one figure using matplotlib, the time it takes to draw them can change. We want to understand how adding more plots affects the work the computer does.
How does the time to draw grow as we add more plots?
Analyze the time complexity of the following code snippet.
import matplotlib.pyplot as plt
fig, axs = plt.subplots(nrows=3, ncols=3)
for ax in axs.flat:
ax.plot([1, 2, 3], [1, 4, 9])
plt.show()
This code creates a 3 by 3 grid of plots and draws the same simple line plot in each subplot.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Drawing a plot inside each subplot.
- How many times: Once for each subplot, here 9 times (3 rows x 3 columns).
Each new subplot adds a similar amount of work to draw its plot.
| Input Size (number of plots) | Approx. Operations |
|---|---|
| 1 | 1 unit of drawing work |
| 10 | 10 units of drawing work |
| 100 | 100 units of drawing work |
Pattern observation: The total work grows directly with the number of plots added.
Time Complexity: O(n)
This means if you double the number of plots, the time to draw roughly doubles too.
[X] Wrong: "Adding more plots won't affect drawing time much because each plot is small."
[OK] Correct: Each plot requires separate drawing steps, so more plots add more work linearly.
Understanding how adding plots affects drawing time helps you write efficient visualization code. This skill shows you can think about performance, not just making plots.
What if we changed the plots to be more complex with many lines each? How would the time complexity change?