Multiple images in subplot grid in Matplotlib - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
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?"
Practice
plt.subplots when displaying multiple images in a grid?Solution
Step 1: Understand the role of
plt.subplotsplt.subplotscreates a figure and a grid of axes (subplots) to place multiple plots or images.Step 2: Connect to displaying images
Each axis in the grid can show one image, so it helps organize multiple images neatly.Final Answer:
To create a grid of axes where each image can be shown separately -> Option CQuick Check:
plt.subplots = grid for images [OK]
- Thinking plt.subplots loads or saves images
- Confusing plt.subplots with image display functions
- Assuming plt.subplots changes image colors
Solution
Step 1: Identify the axes object type
Whenplt.subplotscreates multiple axes, they are stored in an array or matrix.Step 2: Use
axes.flatto flatten the array for loopingaxes.flatlets you loop over all axes in a simple 1D way.Final Answer:
for ax in axes.flat: -> Option AQuick Check:
axes.flat loops all axes [OK]
- Using non-existent methods like axes.grid()
- Trying to loop axes directly without flattening
- Confusing axes with image objects
import matplotlib.pyplot as plt
import numpy as np
images = [np.random.rand(5,5) for _ in range(4)]
fig, axes = plt.subplots(2, 2)
for ax, img in zip(axes.flat, images):
ax.imshow(img, cmap='gray')
ax.axis('off')
plt.show()Solution
Step 1: Understand the code flow
Four random 5x5 images are created and stored in a list. A 2x2 subplot grid is created.Step 2: Loop through axes and images
Each axis in the 2x2 grid shows one image with grayscale colormap and axes turned off.Final Answer:
A 2x2 grid showing 4 random grayscale images without axes -> Option BQuick Check:
Loop + imshow + axis off = grid of images [OK]
- Expecting only one image to show
- Thinking axes.flat is not iterable
- Forgetting to turn axes off
fig, axes = plt.subplots(2, 2)
images = [img1, img2, img3]
for i in range(3):
axes[i].imshow(images[i])
axes[i].axis('off')Solution
Step 1: Check the type of axes
plt.subplots(2, 2)returns a 2D array of axes, so axes[i] is invalid indexing.Step 2: Correct way to access axes
Useaxes.flat[i]or flatten axes before indexing to access each subplot.Final Answer:
axes is a 2D array, so axes[i] causes an error -> Option DQuick Check:
axes 2D array needs flat for 1D access [OK]
- Indexing 2D axes array as 1D
- Assuming images list is empty
- Misusing axis('off') method
Solution
Step 1: Create correct subplot grid
plt.subplots(2, 3)creates 2 rows and 3 columns, perfect for 6 images.Step 2: Loop through axes.flat and images with index
Usingaxes.flatflattens the 2D axes array for easy looping. Adding index withrange(6)helps set titles.Step 3: Set image, title, and turn off axes
Each axis shows one image, sets a title with number, and hides axis ticks.Final Answer:
fig, axes = plt.subplots(2, 3) for ax, img, i in zip(axes.flat, images, range(6)): ax.imshow(img) ax.set_title(f'Image {i+1}') ax.axis('off') -> Option AQuick Check:
axes.flat + set_title + axis off = correct grid [OK]
- Indexing 2D axes as 1D without flat
- Using wrong subplot shape for 6 images
- Calling non-existent title() method
