import matplotlib.pyplot as plt import numpy as np img = np.array([[1, 2], [3, 4]]) plt.imshow(img, extent=[0, 4, 0, 2], aspect='auto') plt.axis('on') plt.show()
Setting aspect='auto' allows the image to stretch to fill the entire extent rectangle, ignoring the original pixel aspect ratio. This means the image shape on the plot matches the extent dimensions exactly.
import matplotlib.pyplot as plt import numpy as np img = np.array([[1, 2], [3, 4]]) plt.imshow(img, extent=[0, 4, 0, 2], aspect='equal') plt.axis('on') plt.show()
With aspect='equal', matplotlib keeps pixels square. Since the extent rectangle is wider than tall (4 units wide, 2 units tall), the image will not stretch to fill it fully. Instead, it fits with square pixels, leaving empty space.
import matplotlib.pyplot as plt import numpy as np img = np.arange(6).reshape(3, 2) fig, axs = plt.subplots(1, 2, figsize=(10, 5)) # Left plot axs[0].imshow(img, extent=[0, 6, 0, 4], aspect='auto') axs[0].set_title('aspect=auto') # Right plot axs[1].imshow(img, extent=[0, 6, 0, 4], aspect='equal') axs[1].set_title('aspect=equal') plt.show()
The left image with aspect='auto' stretches to fill the entire extent area, distorting pixels. The right image with aspect='equal' keeps pixels square, so it fits inside the extent without distortion, leaving empty space.
import matplotlib.pyplot as plt import numpy as np img = np.ones((3,3)) plt.imshow(img, extent=[0, 2, 3]) plt.show()
The extent parameter must have exactly 4 values: [xmin, xmax, ymin, ymax]. Here, only 3 values are given, causing a ValueError.
The extent width is 8 units and the image has 4 pixels horizontally. With aspect='equal', pixels are square, so each pixel is 8/4 = 2 units wide.