We use image extent and aspect ratio to control how an image fits inside a plot. This helps show the image clearly without stretching or squishing it.
Image extent and aspect ratio in Matplotlib
plt.imshow(image, extent=[xmin, xmax, ymin, ymax], aspect='auto'|'equal'|number)
extent sets the bounding box of the image in data coordinates.
aspect controls the shape ratio: 'auto' stretches, 'equal' keeps original ratio, or a number sets height/width ratio.
plt.imshow(img, extent=[0, 10, 0, 5], aspect='auto')
plt.imshow(img, extent=[0, 10, 0, 5], aspect='equal')
plt.imshow(img, extent=[-1, 1, -1, 1], aspect=0.5)
This code creates a simple 5x5 gradient image. It shows the image twice: once stretched to fit the extent box, and once keeping the original shape. You can see how aspect changes the image look.
import matplotlib.pyplot as plt import numpy as np # Create a simple 5x5 image with gradient img = np.arange(25).reshape(5,5) plt.figure(figsize=(8,4)) # Show image with extent and auto aspect plt.subplot(1,2,1) plt.title('aspect="auto"') plt.imshow(img, extent=[0, 10, 0, 5], aspect='auto') plt.xlabel('X axis') plt.ylabel('Y axis') # Show image with extent and equal aspect plt.subplot(1,2,2) plt.title('aspect="equal"') plt.imshow(img, extent=[0, 10, 0, 5], aspect='equal') plt.xlabel('X axis') plt.ylabel('Y axis') plt.tight_layout() plt.show()
If you don't set extent, the image uses pixel coordinates by default.
Setting aspect='equal' is useful to avoid distortion in images like maps or photos.
You can use numbers for aspect to fine-tune the height-to-width ratio.
Image extent sets where the image appears on the plot in data units.
Aspect ratio controls if the image is stretched or keeps its shape.
Use these to make your images look right and fit well with other plot parts.