How to Display an Image in Matplotlib with imshow()

Show image files and NumPy arrays with imshow, display grayscale correctly, control aspect ratio, origin, extent, and interpolation, and save the result.

To display an image in Matplotlib, read it into an array with plt.imread() and draw it with ax.imshow(), then call ax.axis("off") to hide the ticks. imshow() also draws any 2D NumPy array as a grid of colored pixels.

Quick Example

This uses the portrait of computer scientist Grace Hopper that ships with Matplotlib's sample data. Replace the path with your own PNG or JPEG file.

import matplotlib.pyplot as plt
import numpy as np
from matplotlib import cbook

path = cbook.get_sample_data("grace_hopper.jpg", asfileobj=False)
photo = plt.imread(path)  # or plt.imread("my-photo.jpg")

fig, ax = plt.subplots(figsize=(3.6, 4.2), layout="constrained")
ax.imshow(photo)
ax.axis("off")
plt.show()

Photograph of Grace Hopper in Navy uniform displayed with Matplotlib imshow without axes

The code targets Matplotlib 3.11.

What imshow() Accepts

Array shape Values Shown as
(rows, cols) Any numbers Colored through cmap and a color scale
(rows, cols, 3) Floats 0 to 1, or integers 0 to 255 RGB color
(rows, cols, 4) Same ranges RGB with transparency

plt.imread() returns JPEG files as integers from 0 to 255 and PNG files as floats from 0 to 1. A PIL image can be passed to imshow() directly.

print(photo.shape, photo.dtype)  # (600, 512, 3) uint8

If you scale RGB data past the valid range, Matplotlib clips it and warns Clipping input data to the valid range for imshow with RGB data. To brighten a photo safely, clip it yourself: np.clip(photo * 1.3, 0, 255).astype(np.uint8).

Show a Grayscale Image

A 2D array is colored with the viridis colormap by default, so a grayscale photo comes out purple, green, and yellow. Pass cmap="gray", and set vmin and vmax to stop Matplotlib from stretching the contrast to the darkest and lightest pixels present.

gray = photo @ np.array([0.299, 0.587, 0.114])  # weighted average of R, G, B

fig, axes = plt.subplots(1, 3, figsize=(9, 3.7), layout="constrained")
axes[0].imshow(gray)
axes[0].set_title("default cmap")
axes[1].imshow(gray, cmap="gray", vmin=0, vmax=255)
axes[1].set_title('cmap="gray"')
axes[2].imshow(gray, cmap="gray_r", vmin=0, vmax=255)
axes[2].set_title('cmap="gray_r"')
for ax in axes:
    ax.axis("off")
plt.show()

The same grayscale portrait shown with the default viridis colormap, the gray colormap, and the reversed gray colormap

Crop, Flip, and Rotate with NumPy

An image is an array, so slicing edits it. The first index is the row, counted from the top, and the second is the column.

versions = {
    "photo[60:360, 130:390]": photo[60:360, 130:390],
    "photo[:, ::-1]": photo[:, ::-1],
    "np.rot90(photo)": np.rot90(photo),
}

fig, axes = plt.subplots(1, 3, figsize=(9, 3.4), layout="constrained")
for ax, (title, image) in zip(axes, versions.items()):
    ax.imshow(image)
    ax.set_title(title, family="monospace", fontsize=10)
    ax.axis("off")
plt.show()

The portrait cropped to the face, mirrored left to right, and rotated 90 degrees counterclockwise

Set Real Coordinates with extent and origin

imshow() puts row 0 at the top and numbers the axes by pixel. For maps and measurements, use origin="lower" to put row 0 at the bottom, and extent=[left, right, bottom, top] to label the axes in data units.

This elevation grid of the Jacksboro fault in Tennessee is also part of Matplotlib's sample data.

with np.load(cbook.get_sample_data("jacksboro_fault_dem.npz", asfileobj=False)) as dem:
    elevation = dem["elevation"]
    west, east = float(dem["xmin"]), float(dem["xmax"])
    south, north = sorted([float(dem["ymin"]), float(dem["ymax"])])

fig, ax = plt.subplots(figsize=(7.5, 5), layout="constrained")
im = ax.imshow(elevation, cmap="gist_earth", extent=[west, east, south, north],
               aspect=1 / np.cos(np.radians((south + north) / 2)))
fig.colorbar(im, ax=ax, label="Elevation (m)")
ax.set_xticks([-84.4, -84.3, -84.2, -84.1])
ax.set_xlabel("Longitude")
ax.set_ylabel("Latitude")
plt.show()

Elevation map of the Jacksboro fault with longitude and latitude axes and a colorbar in meters

This file stores the northernmost row first, so the default origin="upper" is correct. If your first row is the southern edge, or the bottom of a mathematical grid, add origin="lower". The colorbar guide covers sizing and labels.

Control the Aspect Ratio

The default aspect="equal" keeps pixels square, which is right for photos. For a data grid that is much wider than it is tall, aspect="auto" stretches it to fill the Axes.

rng = np.random.default_rng(12)
signal = np.sin(np.linspace(0, 40, 300) + np.linspace(0, 6, 24)[:, None])
signal += rng.normal(0, 0.25, signal.shape)

fig, axes = plt.subplots(2, 1, figsize=(8, 4.2), layout="constrained")
for ax, aspect in zip(axes, ["equal", "auto"]):
    ax.imshow(signal, cmap="coolwarm", aspect=aspect)
    ax.set_title(f'aspect="{aspect}" (array is 24 × 300)')
    ax.set_ylabel("Sensor")
plt.show()

A 24 by 300 sensor array drawn as a thin strip with equal aspect and filling the panel with auto aspect

Fix Blurry Pixels with interpolation

interpolation controls how array values map to screen pixels. Use "nearest" to see each value as a crisp square and "bilinear" or "bicubic" to smooth between them.

tiny = rng.random((8, 8))

fig, axes = plt.subplots(1, 3, figsize=(9, 3.3), layout="constrained")
for ax, method in zip(axes, ["nearest", "bilinear", "bicubic"]):
    ax.imshow(tiny, cmap="magma", interpolation=method)
    ax.set_title(f'interpolation="{method}"')
    ax.axis("off")
plt.show()

An 8 by 8 random array drawn with nearest, bilinear, and bicubic interpolation, from sharp squares to smooth gradients

The default, "auto", picks nearest-neighbor when the image is enlarged more than three times and an anti-aliasing filter when it is shrunk or enlarged only slightly.

Plot Points and Overlays on an Image

Draw the image first, then plot on the same Axes using pixel coordinates (x is the column, y is the row). An array drawn with alpha makes a translucent overlay.

yy, xx = np.mgrid[:600, :512]
heat = np.exp(-(((xx - 262) / 90) ** 2 + ((yy - 215) / 110) ** 2))

fig, axes = plt.subplots(1, 2, figsize=(7.2, 4.2), layout="constrained")
axes[0].imshow(photo)
axes[0].plot([215, 305], [190, 190], "o", ms=12, mfc="none", mec="#facc15", mew=2.5)
axes[0].set_title("Markers")
axes[1].imshow(photo)
axes[1].imshow(heat, cmap="inferno", alpha=0.55)
axes[1].set_title("Heat overlay")
for ax in axes:
    ax.axis("off")
plt.show()

Portrait with two circle markers over the eyes and the same portrait with a translucent heat overlay centered on the face

Save an Array as an Image File

plt.imsave() writes the array at one file pixel per array element, with no axes or margins. Use fig.savefig() when you want the chart around it.

plt.imsave("elevation.png", elevation, cmap="gist_earth")  # 403 × 344 pixels

For labeled grids with a number in each cell, see heatmaps in Matplotlib.

Similar Topics