AlgoInsight

Q&A

What is the pyplot.imshow() method?

By AlgoInsight Team2026-06-07arrayspython

Overview

imshow ("image show") maps array values to colors and draws them as a pixel grid. A 2-D array becomes a heatmap colored by a colormap; a 3-D array (height × width × 3 or × 4) is shown as a real color image. It's ubiquitous in data science and image processing for visualizing matrices, model outputs, correlation heatmaps, and pictures.

graph LR
    A[2-D array → heatmap via colormap] --> C["plt.imshow(data)"]
    B[3-D array H×W×3 → RGB image] --> C
    C --> D[Rendered pixel grid]
    D --> E["plt.colorbar() adds a scale"]
    style C fill:#1e1b4b,color:#fff

Displaying a 2-D Array (heatmap)

import matplotlib.pyplot as plt
import numpy as np

data = np.random.rand(10, 10)        # 10x10 of values in [0,1]
plt.imshow(data, cmap="viridis")     # map values → colors
plt.colorbar()                        # show the value→color scale
plt.title("Random Heatmap")
plt.show()

Each array cell becomes a pixel; the cmap translates its value to a color. colorbar() adds the legend mapping colors back to values.

Displaying an Actual Image (3-D array)

import matplotlib.image as mpimg
img = mpimg.imread("photo.png")      # shape (H, W, 3) or (H, W, 4)
plt.imshow(img)                       # shown as a true color image
plt.axis("off")                       # hide axis ticks for photos
plt.show()

For 3-channel (RGB) or 4-channel (RGBA) arrays, imshow interprets the last axis as color and no colormap is used.

Key Parameters

Parameter Purpose
cmap Colormap for 2-D data: viridis, gray, hot, coolwarm
vmin, vmax Clip/normalize the value range mapped to colors
interpolation Pixel smoothing: nearest (blocky, honest), bilinear (smooth)
aspect equal (square pixels) or auto (fill axes)
origin upper (default, row 0 at top) or lower (row 0 at bottom)
extent Map the image to data coordinates [left, right, bottom, top]
plt.imshow(matrix, cmap="hot", vmin=0, vmax=1, interpolation="nearest")

The origin Gotcha

By default imshow puts row 0 at the top (origin="upper"), matching how images are stored. For mathematical plots where you want the y-axis increasing upward, use origin="lower". Mixing these up flips your visualization vertically - a frequent confusion.

imshow vs Related Functions

Practical Uses

Why This Matters in Interviews

Data-science/visualization interviews use imshow to test plotting fluency. Key points: it renders a 2-D array as a colormapped heatmap or a 3-D array as an RGB image; cmap + colorbar() make values interpretable; vmin/vmax control the scale; and the origin default (row 0 at top) is a classic gotcha. Knowing interpolation="nearest" for honest pixel display (vs smoothing) and the matrix-oriented matshow shows depth.

Common Pitfalls

References

More answers