Multiple images in subplot grid in Matplotlib - Time & Space Complexity
When showing many images in a grid using matplotlib, we want to know how the time to draw grows as we add more images.
We ask: How does adding more images affect the total work matplotlib does?
Analyze the time complexity of the following code snippet.
import matplotlib.pyplot as plt
import numpy as np
fig, axes = plt.subplots(3, 3)
for i, ax in enumerate(axes.flat):
img = np.random.rand(10, 10)
ax.imshow(img)
plt.show()
This code creates a 3 by 3 grid of images, each showing a small random 10x10 picture.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Loop over each subplot to draw an image.
- How many times: Once for each image in the grid (rows x columns).
As we add more images, the work grows roughly in direct proportion to the number of images.
| Input Size (n images) | Approx. Operations |
|---|---|
| 9 (3x3) | 9 image draws |
| 100 (10x10) | 100 image draws |
| 1024 (32x32) | 1024 image draws |
Pattern observation: Doubling the number of images roughly doubles the work.
Time Complexity: O(n)
This means the time to draw grows linearly with the number of images shown.
[X] Wrong: "Adding more images won't affect time much because each image is small."
[OK] Correct: Even small images require drawing work, so more images add up and increase total time.
Understanding how drawing many images scales helps you explain performance in data visualization tasks clearly and confidently.
"What if we changed the image size from 10x10 to 100x100 pixels? How would the time complexity change?"