Figure creation with plt.figure in Matplotlib - Time & Space Complexity
When we create a figure using plt.figure(), it takes some time to set up the drawing space.
We want to know how this setup time changes as we create more figures.
Analyze the time complexity of the following code snippet.
import matplotlib.pyplot as plt
for i in range(n):
fig = plt.figure()
plt.close(fig)
This code creates and closes n figures one after another.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Creating a figure with
plt.figure()inside a loop. - How many times: Exactly
ntimes, once per loop iteration.
Each figure creation takes roughly the same time, so total time grows directly with n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 figure creations |
| 100 | 100 figure creations |
| 1000 | 1000 figure creations |
Pattern observation: Doubling n doubles the total work.
Time Complexity: O(n)
This means the time to create n figures grows in a straight line as n increases.
[X] Wrong: "Creating multiple figures at once is instant and does not add up."
[OK] Correct: Each figure requires setup, so time adds up linearly with the number of figures.
Understanding how repeated figure creation scales helps you reason about performance in data visualization tasks.
What if we reused the same figure instead of creating a new one each time? How would the time complexity change?