0
0
Matplotlibdata~5 mins

Image extent and aspect ratio in Matplotlib

Choose your learning style9 modes available
Introduction

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.

When you want to place an image inside a graph with specific coordinates.
When you want to keep the image's original shape without distortion.
When you want to compare images or data side by side with correct scaling.
When you want to zoom or crop a part of an image in a plot.
When you want to make sure the image fits well with other plot elements.
Syntax
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.

Examples
Image stretched to fit the box from x=0 to 10 and y=0 to 5.
Matplotlib
plt.imshow(img, extent=[0, 10, 0, 5], aspect='auto')
Image keeps its original shape inside the box, no stretching.
Matplotlib
plt.imshow(img, extent=[0, 10, 0, 5], aspect='equal')
Image height is half the width, controlled by aspect ratio number.
Matplotlib
plt.imshow(img, extent=[-1, 1, -1, 1], aspect=0.5)
Sample Program

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.

Matplotlib
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()
OutputSuccess
Important Notes

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.

Summary

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.