Bird
Raised Fist0
Matplotlibdata~20 mins

Multiple images in subplot grid in Matplotlib - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
Subplot Grid Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of subplot grid with 2 images
What will be the output of this code that plots two images side by side using matplotlib subplots?
Matplotlib
import matplotlib.pyplot as plt
import numpy as np

img1 = np.ones((5,5))
img2 = np.zeros((5,5))

fig, axs = plt.subplots(1, 2)
axs[0].imshow(img1, cmap='gray')
axs[1].imshow(img2, cmap='gray')
plt.show()
AA figure with two images: left is a white square, right is a black square.
BAn error because axs is not iterable.
CA single image showing a gradient from black to white.
DA figure with two images stacked vertically.
Attempts:
2 left
💡 Hint
Check how subplots are arranged and how images are assigned to axes.
data_output
intermediate
1:00remaining
Number of axes in a 3x3 subplot grid
How many axes objects are created when you run this code?
Matplotlib
import matplotlib.pyplot as plt
fig, axs = plt.subplots(3, 3)
print(len(axs.flatten()))
A1
B3
C9
D6
Attempts:
2 left
💡 Hint
Count rows times columns in the subplot grid.
visualization
advanced
2:30remaining
Identify the subplot layout from the image
Given a figure with 4 images arranged in a 2x2 grid, which code snippet correctly creates this layout?
A
fig, axs = plt.subplots(1, 4)
for i, ax in enumerate(axs):
    ax.imshow(np.full((3,3), i))
B
fig, axs = plt.subplots(2, 2)
for i, ax in enumerate(axs.flatten()):
    ax.imshow(np.full((3,3), i))
C
fig, axs = plt.subplots(4, 1)
for i, ax in enumerate(axs):
    ax.imshow(np.full((3,3), i))
D
fig, axs = plt.subplots(3, 3)
for i, ax in enumerate(axs.flatten()[:4]):
    ax.imshow(np.full((3,3), i))
Attempts:
2 left
💡 Hint
Check the shape of the subplot grid and how images are assigned.
🔧 Debug
advanced
1:30remaining
Why does this subplot code raise an error?
This code raises an error. What is the cause?
Matplotlib
import matplotlib.pyplot as plt
fig, axs = plt.subplots(1, 1)
axs.imshow([[1, 2], [3, 4]])
plt.show()
A'AxesSubplot' object has no attribute 'imshow'
BTypeError because axs is not an array but a single Axes object
CIndexError because axs is not subscriptable
DNo error, the code runs fine
Attempts:
2 left
💡 Hint
Check the type of axs when subplots(1,1) is used.
🚀 Application
expert
3:00remaining
Arrange 6 images in a 2x3 grid with shared axes
You want to plot 6 images in a 2 rows by 3 columns grid using matplotlib. You want all subplots to share the same x and y axes to compare images easily. Which code snippet achieves this?
A
fig, axs = plt.subplots(2, 3, sharex=True, sharey=True)
for ax in axs.flatten():
    ax.imshow(np.random.rand(5,5))
plt.show()
B
fig, axs = plt.subplots(2, 3)
for ax in axs.flatten():
    ax.imshow(np.random.rand(5,5))
plt.show()
C
fig, axs = plt.subplots(6, 1, sharex=True, sharey=True)
for ax in axs:
    ax.imshow(np.random.rand(5,5))
plt.show()
D
fig, axs = plt.subplots(3, 2, sharex=True, sharey=True)
for ax in axs.flatten():
    ax.imshow(np.random.rand(5,5))
plt.show()
Attempts:
2 left
💡 Hint
Check the shape of the grid and the sharex/sharey parameters.

Practice

(1/5)
1. What is the main purpose of using plt.subplots when displaying multiple images in a grid?
easy
A. To change the color of images
B. To load images from files automatically
C. To create a grid of axes where each image can be shown separately
D. To save images to disk

Solution

  1. Step 1: Understand the role of plt.subplots

    plt.subplots creates a figure and a grid of axes (subplots) to place multiple plots or images.
  2. Step 2: Connect to displaying images

    Each axis in the grid can show one image, so it helps organize multiple images neatly.
  3. Final Answer:

    To create a grid of axes where each image can be shown separately -> Option C
  4. Quick Check:

    plt.subplots = grid for images [OK]
Hint: Remember: plt.subplots makes the grid for multiple images [OK]
Common Mistakes:
  • Thinking plt.subplots loads or saves images
  • Confusing plt.subplots with image display functions
  • Assuming plt.subplots changes image colors
2. Which of the following is the correct way to loop through all axes in a subplot grid to plot images?
easy
A. for ax in axes.flat:
B. for ax in axes.grid():
C. for ax in axes.loop():
D. for ax in axes.images():

Solution

  1. Step 1: Identify the axes object type

    When plt.subplots creates multiple axes, they are stored in an array or matrix.
  2. Step 2: Use axes.flat to flatten the array for looping

    axes.flat lets you loop over all axes in a simple 1D way.
  3. Final Answer:

    for ax in axes.flat: -> Option A
  4. Quick Check:

    axes.flat loops all axes [OK]
Hint: Use axes.flat to loop all subplot axes easily [OK]
Common Mistakes:
  • Using non-existent methods like axes.grid()
  • Trying to loop axes directly without flattening
  • Confusing axes with image objects
3. What will be the output of this code snippet?
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()
medium
A. A single image shown in one plot
B. A 2x2 grid showing 4 random grayscale images without axes
C. An error because axes.flat is not iterable
D. A 2x2 grid with empty plots and no images

Solution

  1. Step 1: Understand the code flow

    Four random 5x5 images are created and stored in a list. A 2x2 subplot grid is created.
  2. Step 2: Loop through axes and images

    Each axis in the 2x2 grid shows one image with grayscale colormap and axes turned off.
  3. Final Answer:

    A 2x2 grid showing 4 random grayscale images without axes -> Option B
  4. Quick Check:

    Loop + imshow + axis off = grid of images [OK]
Hint: Loop axes.flat with images to plot all in grid [OK]
Common Mistakes:
  • Expecting only one image to show
  • Thinking axes.flat is not iterable
  • Forgetting to turn axes off
4. Identify the error in this code that tries to display 3 images in a 2x2 grid:
fig, axes = plt.subplots(2, 2)
images = [img1, img2, img3]
for i in range(3):
    axes[i].imshow(images[i])
    axes[i].axis('off')
medium
A. axis('off') is not a valid method
B. images list is empty
C. imshow cannot display images in subplots
D. axes is a 2D array, so axes[i] causes an error

Solution

  1. Step 1: Check the type of axes

    plt.subplots(2, 2) returns a 2D array of axes, so axes[i] is invalid indexing.
  2. Step 2: Correct way to access axes

    Use axes.flat[i] or flatten axes before indexing to access each subplot.
  3. Final Answer:

    axes is a 2D array, so axes[i] causes an error -> Option D
  4. Quick Check:

    axes 2D array needs flat for 1D access [OK]
Hint: Use axes.flat to index subplots in 1D [OK]
Common Mistakes:
  • Indexing 2D axes array as 1D
  • Assuming images list is empty
  • Misusing axis('off') method
5. You want to display 6 images in a 2x3 grid with titles on each subplot. Which code snippet correctly does this?
hard
A. 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')
B. fig, axes = plt.subplots(3, 2) for i in range(6): axes[i].imshow(images[i]) axes[i].title(f'Image {i}') axes[i].axis('off')
C. fig, axes = plt.subplots(2, 3) for i in range(6): axes[i].imshow(images[i]) axes[i].set_title('Image') axes[i].axis('off')
D. fig, axes = plt.subplots(2, 3) for ax, img in zip(axes, images): ax.imshow(img) ax.set_title('Image') ax.axis('off')

Solution

  1. Step 1: Create correct subplot grid

    plt.subplots(2, 3) creates 2 rows and 3 columns, perfect for 6 images.
  2. Step 2: Loop through axes.flat and images with index

    Using axes.flat flattens the 2D axes array for easy looping. Adding index with range(6) helps set titles.
  3. Step 3: Set image, title, and turn off axes

    Each axis shows one image, sets a title with number, and hides axis ticks.
  4. 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 A
  5. Quick Check:

    axes.flat + set_title + axis off = correct grid [OK]
Hint: Use axes.flat and zip(images, range) for titles [OK]
Common Mistakes:
  • Indexing 2D axes as 1D without flat
  • Using wrong subplot shape for 6 images
  • Calling non-existent title() method