imshow() (Matplotlib)

ax.imshow() displays a 2-D array (or an image) as a grid of colored pixels, mapping each value to a color via a colormap. It is the standard way to show matrices, heatmaps, and raster images.

Matplotlib

Given a 2-D array, imshow paints each cell as a pixel colored by its value, which makes it perfect for heatmaps of a matrix, correlation grids, or the output of a 2-D function. For an RGB or RGBA array it shows the image directly using the color channels.

A few defaults trip people up: imshow places the origin at the top-left (like image coordinates), so pass origin='lower' to put it at the bottom as in math plots. By default it interpolates between pixels; interpolation='nearest' keeps blocks crisp, which is usually what you want for data matrices.

Pair it with a colormap (cmap) and a colorbar to make the values readable, and set extent to map the pixel grid onto real x/y coordinates. For irregular grids, pcolormesh is the more flexible alternative.

Syntax

ax.imshow(array, cmap=None, origin='upper', interpolation=None)

Examples

Python

import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
im = ax.imshow(np.arange(9).reshape(3, 3))
print(type(im).__name__)

Output:

AxesImage

Learn it in a lesson

See also

Back to the Dictionary