Bird
Raised Fist0
Matplotlibdata~10 mins

Image extent and aspect ratio in Matplotlib - Step-by-Step Execution

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
Concept Flow - Image extent and aspect ratio
Create image data
Call imshow() with extent
Set aspect ratio
Render image on plot
Display axes with adjusted limits and ratio
This flow shows how image data is created, displayed with a specified extent, and how the aspect ratio controls the shape of the image on the plot.
Execution Sample
Matplotlib
import matplotlib.pyplot as plt
import numpy as np
img = np.arange(16).reshape(4,4)
plt.imshow(img, extent=[0,4,0,2], aspect='auto')
plt.show()
This code creates a 4x4 image and displays it stretched to fit the extent [0,4] in x and [0,2] in y with automatic aspect ratio.
Execution Table
StepActionParameter/ValueEffect on PlotResult
1Create image data4x4 array with values 0 to 15Image data readyImage array created
2Call imshow()img, extent=[0,4,0,2], aspect='auto'Image placed with x from 0 to 4, y from 0 to 2Image stretched to fit extent
3Set aspect ratio'auto'Image pixels scaled to fill extent areaImage shape distorted to fit axes limits
4Render imageN/AImage displayed on plotImage visible with stretched shape
5Show plotplt.show()Plot window opensUser sees image with specified extent and aspect
💡 Execution stops after plot window is displayed and user closes it.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
imgundefined4x4 numpy array with values 0-15Same array passed to imshowSame array displayed with extentDisplayed image data unchanged
extentundefinedundefined[0,4,0,2]Used to set axes limitsAxes limits set to extent
aspectundefinedundefined'auto'Controls pixel scalingAspect ratio applied
Key Moments - 2 Insights
Why does the image look stretched when using extent with aspect='auto'?
Because aspect='auto' scales the image to fill the axes limits set by extent, the pixels are not forced to be square, causing stretching as shown in execution_table step 3.
What does the extent parameter control in imshow?
Extent sets the data limits for the image axes (x and y ranges), changing where the image is placed and how large it appears, as seen in execution_table step 2.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the extent value used in step 2?
A[0,4,0,2]
B[0,2,0,4]
C[0,1,0,1]
D[1,4,1,2]
💡 Hint
Check the 'Parameter/Value' column in step 2 of the execution_table.
At which step does the image get stretched to fit the axes limits?
AStep 1
BStep 3
CStep 4
DStep 5
💡 Hint
Look at the 'Effect on Plot' column describing aspect ratio application.
If aspect='equal' was used instead of 'auto', how would the image shape change?
AImage would be stretched more
BImage would disappear
CImage pixels would be square, preserving shape
DExtent would be ignored
💡 Hint
Aspect ratio controls pixel scaling; 'equal' keeps pixels square.
Concept Snapshot
imshow(image, extent=[xmin,xmax,ymin,ymax], aspect='auto'|'equal')
- extent sets image axes limits
- aspect='auto' stretches image to fill extent
- aspect='equal' keeps pixel shape square
- Changing extent changes image size on plot
- Aspect ratio controls image distortion
Full Transcript
This lesson shows how matplotlib's imshow function uses the extent parameter to set the image's position and size on the plot axes. The aspect parameter controls whether the image pixels keep their shape or stretch to fill the axes. We create a 4x4 image array, display it with extent [0,4,0,2], and aspect='auto', which stretches the image to fill the rectangular area. The execution table traces each step from data creation to rendering. Key moments clarify why the image stretches and what extent does. The quiz tests understanding of extent values, when stretching happens, and the effect of aspect ratio settings.

Practice

(1/5)
1. What does the extent parameter control when displaying an image with matplotlib.pyplot.imshow()?
easy
A. The color map used for the image
B. The position and size of the image on the plot axes
C. The resolution of the image
D. The file format of the image

Solution

  1. Step 1: Understand the role of extent

    The extent parameter defines the bounding box in data coordinates that the image will fill on the axes.
  2. Step 2: Compare with other options

    Color map, resolution, and file format are unrelated to extent. They control different aspects of image display or file handling.
  3. Final Answer:

    The position and size of the image on the plot axes -> Option B
  4. Quick Check:

    Extent = position and size [OK]
Hint: Extent sets image box on axes, not colors or file type [OK]
Common Mistakes:
  • Confusing extent with color map
  • Thinking extent changes image resolution
  • Assuming extent controls file format
2. Which of the following is the correct way to keep the image aspect ratio fixed when using imshow()?
easy
A. plt.imshow(img, aspect='equal')
B. plt.imshow(img, cmap='gray')
C. plt.imshow(img, extent=[0,1,0,1])
D. plt.imshow(img, aspect='auto')

Solution

  1. Step 1: Identify aspect ratio options

    The aspect parameter controls image stretching. 'equal' keeps the aspect ratio fixed.
  2. Step 2: Check other options

    'auto' allows stretching, extent sets position, and cmap sets colors, not aspect ratio.
  3. Final Answer:

    plt.imshow(img, aspect='equal') -> Option A
  4. Quick Check:

    Aspect='equal' fixes ratio [OK]
Hint: Use aspect='equal' to keep image shape correct [OK]
Common Mistakes:
  • Using aspect='auto' which stretches image
  • Confusing extent with aspect ratio
  • Setting cmap instead of aspect
3. What will be the effect of this code snippet?
import matplotlib.pyplot as plt
import numpy as np
img = np.ones((10, 20))
plt.imshow(img, extent=[0, 5, 0, 10], aspect='auto')
plt.show()
medium
A. Image will be shown with default extent and fixed aspect ratio
B. Image will keep original shape and size ignoring extent
C. Code will raise an error due to wrong extent format
D. Image will stretch to fill x from 0 to 5 and y from 0 to 10, possibly distorted

Solution

  1. Step 1: Analyze extent parameter

    The extent=[0,5,0,10] sets the image to cover x-axis 0 to 5 and y-axis 0 to 10 on the plot.
  2. Step 2: Analyze aspect='auto'

    Aspect='auto' allows the image to stretch to fill the extent box, so the image shape may distort.
  3. Final Answer:

    Image will stretch to fill x from 0 to 5 and y from 0 to 10, possibly distorted -> Option D
  4. Quick Check:

    Extent sets size, aspect='auto' allows stretch [OK]
Hint: Extent sets size; aspect='auto' allows distortion [OK]
Common Mistakes:
  • Assuming extent is ignored
  • Expecting fixed aspect ratio with aspect='auto'
  • Thinking code raises error
4. Identify the error in this code that tries to display an image with fixed aspect ratio:
import matplotlib.pyplot as plt
import numpy as np
img = np.random.rand(5,5)
plt.imshow(img, extent=[0,5,0], aspect='equal')
plt.show()
medium
A. The aspect='equal' is invalid and causes error
B. The image array shape is incompatible with imshow
C. The extent list has incorrect length; it should have 4 values
D. Missing plt.axis('equal') to fix aspect ratio

Solution

  1. Step 1: Check extent parameter format

    Extent must be a list of 4 numbers: [xmin, xmax, ymin, ymax]. Here it has only 3 values, causing an error.
  2. Step 2: Verify other parameters

    Aspect='equal' is valid. Image shape is fine. plt.axis('equal') is optional when aspect is set.
  3. Final Answer:

    The extent list has incorrect length; it should have 4 values -> Option C
  4. Quick Check:

    Extent needs 4 numbers [OK]
Hint: Extent must have 4 numbers: xmin, xmax, ymin, ymax [OK]
Common Mistakes:
  • Using extent with less than 4 values
  • Confusing aspect parameter validity
  • Thinking plt.axis('equal') is required
5. You want to overlay a heatmap image on a scatter plot with x values from 0 to 10 and y values from 0 to 5. Which extent and aspect settings correctly align the image without distortion?
hard
A. extent=[0,10,0,5], aspect='equal'
B. extent=[0,5,0,10], aspect='auto'
C. extent=[0,10,0,5], aspect='auto'
D. extent=[0,5,0,10], aspect='equal'

Solution

  1. Step 1: Match extent to data range

    The scatter plot x ranges 0-10 and y ranges 0-5, so extent must be [0,10,0,5] to align image correctly.
  2. Step 2: Choose aspect to avoid distortion

    Aspect='equal' keeps the image shape correct, preventing distortion when overlaying.
  3. Final Answer:

    extent=[0,10,0,5], aspect='equal' -> Option A
  4. Quick Check:

    Extent matches data, aspect='equal' fixes shape [OK]
Hint: Match extent to data limits and use aspect='equal' [OK]
Common Mistakes:
  • Swapping x and y in extent
  • Using aspect='auto' causing distortion
  • Ignoring data range when setting extent