Heatmaps and Array Displays

Display a two-dimensional array as a grid whose rows and columns preserve array axes and whose colors encode values. Choose a color scale from the numerical meaning, use shared limits for comparisons, and verify orientation, transposition, and important cells from the underlying array.

A heatmap represents values in a two-dimensional array with colors. The row and column positions preserve the array's two axes, while a color scale represents the numerical value at each position.

Heatmaps are useful for inspecting feature tables, image arrays, confusion matrices, attention weights, parameter matrices, and other numerical grids. Color provides a compact overview, but the axes and color scale must be stated before the pattern can be interpreted.

Map array positions to a visible grid

Matplotlib commonly displays an array with imshow:

plt.imshow(matrix)

For a matrix with shape (rows, columns):

matrix[row, column]
        |     |
        |     +-- horizontal position
        +-------- vertical position

By default, row 0 appears at the top and column 0 appears at the left. This top-down row order is familiar for images and tables, but it differs from a Cartesian graph, where larger vertical coordinates appear higher.

Inspect values, shape, and color together

The following matrix contains four examples in rows and three standardized features in columns. A standardized value near 0 is close to that feature's reference center; positive and negative values lie on opposite sides.

Inspect a standardized feature table

The diverging color scale is centered at zero. Edit one value and compare its printed position with the changed cell.

Ready to run.

The colorbar converts color back into a numerical value. The fixed limits -2 and 2 also make zero the center of the scale. Without a colorbar and known limits, “red” or “blue” has no stable numerical meaning.

interpolation="nearest" shows each array cell without blending it into its neighbors. aspect="auto" lets a non-square matrix use the available plotting area. This can make cells rectangular, so use equal cell proportions when physical geometry matters.

Choose a color scale from the value meaning

A sequential color scale moves from low to high. It suits values with an ordered magnitude, such as counts, probabilities, or nonnegative intensity:

plt.imshow(counts, cmap="viridis", vmin=0)

A diverging color scale uses two directions around a meaningful center. It suits signed values such as residuals, correlations, or standardized features:

plt.imshow(residuals, cmap="coolwarm", vmin=-2, vmax=2)

For a zero-centered diverging scale, use limits with equal magnitude when the positive and negative sides should receive equal visual emphasis. A value range from -1 to 8 may need different treatment because forcing symmetric limits would leave much of the negative side unused.

Color choice should follow numerical meaning. It should not imply a center or boundary that the data does not have.

Compare arrays with one shared color scale

Matplotlib chooses color limits separately for each imshow call unless limits are supplied. Separate automatic limits can make two different arrays look similar.

Suppose these matrices contain residuals before and after a model change:

Compare residual matrices with shared limits

Both panels use the same limits, so the same color represents the same residual. Change one limit to see how an unfair comparison can arise.

Ready to run.

The second matrix has smaller residual magnitudes. Shared limits allow the lighter colors to represent that numerical reduction. If each panel chose its own limits, both could use the full color range and appear equally variable.

Name the real meaning of both axes

Index labels are sufficient while debugging a small anonymous matrix. A figure intended for explanation should name the represented quantities.

For a feature table:

vertical axis -> examples
horizontal axis -> features
color -> feature value

For one common confusion-matrix convention:

vertical axis -> actual class
horizontal axis -> predicted class
color -> number of examples

For an attention matrix:

vertical axis -> query position
horizontal axis -> key position
color -> attention weight

The row and column meanings come from the data contract, not from imshow. Write them in labels, tick labels, the title, or the surrounding explanation.

Detect transposition and orientation mistakes

Transposing an array exchanges its row and column axes:

plt.imshow(matrix.T)

The call may produce a reasonable-looking heatmap even when the transpose is wrong. Check shape and axis meaning before using it:

Also decide where row 0 should appear. Use

plt.imshow(matrix, origin="lower")

only when placing row 0 at the bottom matches the coordinate system being represented. Do not change orientation merely because one version looks more familiar.

Know when color is not enough

A heatmap is good for overall structure, but it does not provide exact values efficiently. For a small matrix, print the array or annotate selected cells. For a large matrix, combine the display with minimum, maximum, row or column summaries, and checks for missing or non-finite values.

Color perception also differs between readers and display conditions. Prefer well-tested perceptually ordered color maps, include a labeled colorbar, and do not rely on color alone when an exact threshold or category must be identified.

Exercise: Choose an array-display function

Which Matplotlib function commonly displays a two-dimensional numerical array as a color grid?

Answer it first, then check.

HintShow an image-like grid

The function can display numerical matrices even when they are not photographs.

SolutionUse imshow

plt.imshow(matrix) displays a two-dimensional array as a grid of colored cells.

Exercise: Map a matrix axis to the display

For plt.imshow(matrix), which array index changes as you move horizontally across the displayed grid?

Choose the index

Select one choice, then check.

HintRead the second index

In matrix[row, column], the second index selects horizontal position.

SolutionColumns move horizontally

Moving left to right changes the column index while the row index remains fixed.

Exercise: Recover the numerical color meaning

What figure component shows which numerical values correspond to the heatmap's colors?

Answer it first, then check.

HintLook for a scale beside the grid

Its name combines color and bar.

SolutionUse a colorbar

A colorbar displays the color scale and should be labeled with the represented quantity or unit.

Exercise: Make two heatmaps comparable

Two residual matrices must be compared by color. Which settings should their imshow calls share?

Choose the shared settings

Select one choice, then check.

HintShare the complete color mapping

The colormap chooses colors, while vmin and vmax assign their numerical limits.

SolutionShare colormap and limits

Use the same colormap, vmin, and vmax. Then matching colors represent matching numerical values.

Exercise: Interpret a feature column

A feature table stores examples in rows and features in columns. What does one vertical stripe in its heatmap represent?

Answer it first, then check.

HintHold the column fixed

The column selects one feature; the rows select different examples.

SolutionOne feature across examples

A vertical stripe contains the values of one feature for all displayed examples.

Read axes, values, and colors as one contract

Before interpreting a heatmap, state the row meaning, column meaning, color quantity, color limits, and orientation. Use shared scales for comparisons, verify important cells numerically, and treat a visually plausible transpose as a possible axis error until the data contract confirms it.