Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 57 ยท Core Chart Types

Heatmaps and Images

Draw heatmaps and images in Matplotlib with imshow and pcolormesh, annotate cells, plot a correlation matrix, and add contour, quiver and streamplot.

A heatmap turns a grid of numbers into a grid of colors. It is the right chart for correlation matrices, confusion matrices, calendars of activity, and any table that is too big to read as digits. The same machinery draws photographs, because an image is just a grid of numbers too.

In this lesson you will draw arrays with imshow and pcolormesh, control orientation and extent, write the values into the cells, plot a correlation matrix, and finish with contour lines and vector fields, which show functions of two variables. Colors depend on colormaps; Arrays as Images and Plots covers the pixel side.

Three ways to draw a grid

imshow Regular pixel grids and images.
pcolormesh Cells with uneven edges.
contourf Smooth filled levels.
1 / 2

imshow: an array as pixels

ax.imshow(array) draws a 2D array as colored pixels. Each element becomes one cell, its value is mapped through the colormap, and the origin is the top-left corner: row 0 is drawn at the top, which matches how matrices and images are written.

Key arguments:

  • cmap: the colormap; vmin and vmax set the value range that maps to the ends of the colormap.
  • origin="upper" (default) or "lower": where row 0 is drawn. Use "lower" for data whose y grows upward, such as a function on a grid.
  • extent=(left, right, bottom, top): the data coordinates the image covers. Without it, axes show pixel indexes.
  • interpolation: how pixels are resampled. "nearest" keeps sharp blocks, "bilinear" or "bicubic" smooth them. Use "nearest" for heatmaps where each cell is a real value, because smoothing invents values between cells.
  • aspect: "equal" (default) gives square pixels; "auto" stretches to fill the axes.
Python imshow: origin, extent and interpolation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The first panel puts large y values at the bottom, because row 0 of the array is drawn at the top. Panels two and three use origin="lower" with extent, so up means larger y and the ticks are real coordinates. The third panel looks smoother, but those in-between colors do not exist in the data, which is why heatmaps use "nearest".

pcolormesh: cells with edges

imshow assumes equal-sized cells. When the grid is uneven (log-spaced bins, irregular times) use ax.pcolormesh(x_edges, y_edges, values). It takes the edges of the cells, so for values of shape (ny, nx) you pass nx + 1 x edges and ny + 1 y edges (or the cell centers with shading="nearest" or "auto"). Its y axis points up, like a normal plot, not down like imshow.

Python pcolormesh with uneven cells

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The edge arrays are one longer than the values in each direction. If you get a shape error mentioning "dimensions", that is almost always the cause.

Annotating the cells

For small matrices, print the number in each cell. Matplotlib has no built-in flag for it, so loop over the cells and call ax.text. Pick a text color that stays readable on dark and light cells, for example white below the midpoint and black above it.

Python An annotated heatmap

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Cell (i, j) is at x = j (column) and y = i (row). It is easy to swap them. If the text appears in the wrong place, check that x is the column index.

A correlation matrix

A very common heatmap is the correlation matrix: np.corrcoef of the columns gives a symmetric table of numbers between -1 and 1. Because the values are centered on zero, use a diverging colormap such as "coolwarm" and fix vmin=-1, vmax=1, so that zero is always neutral and colors are comparable between charts.

Python Correlation matrix with a diverging colormap

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The diagonal is always 1 (each variable matches itself) and the matrix is symmetric, so half of it is redundant. For bigger matrices people often mask the upper triangle. Correlation measures straight-line association only, so confirm important pairs with a scatter plot.

A triangle heatmap and colorbars that fit

Because a correlation matrix mirrors itself, the upper triangle only repeats the lower one. Hiding it makes the chart half as busy and the cell values easier to read. Build a boolean mask with np.triu(...), wrap the matrix in a masked array, and imshow leaves the masked cells empty.

A second small annoyance: fig.colorbar(im, ax=ax) makes the bar as tall as the Axes box, but an image with a fixed aspect ratio can be shorter than that box, so the bar and the image do not line up (see the left panel below). The fix lives in a Matplotlib toolkit: make_axes_locatable(ax) returns a divider, and divider.append_axes("right", size="5%", pad=0.1) adds a slim new Axes beside the plot, exactly as tall as the plot. Pass that Axes to fig.colorbar(im, cax=cax).

Python Lower-triangle correlation heatmap with a fitted colorbar

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

np.triu(m, k=1) keeps the entries above the diagonal that sits k=1 steps up, so the diagonal itself stays visible. Use np.tril to hide the lower half instead. In the right panel the colorbar is exactly as tall as the heatmap, which is what you want for publication figures. If you use constrained_layout=True, fig.colorbar(im, ax=ax, fraction=0.046, pad=0.04) gives a similar fit without the toolkit.

Contour plots

When values are a function of two variables, such as height over a map or an error surface, contour lines connect points of equal value, just like a topographic map. ax.contour(X, Y, Z) draws the lines; ax.contourf fills the bands between them. Generate the grid with np.meshgrid, label the lines with ax.clabel, and add a colorbar for the filled version.

Python contour and contourf

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The surface has one hill and one valley. Closely spaced contour lines mean a steep slope, widely spaced lines a gentle one. The levels argument is either a count or the list of values you want.

Vector fields: quiver and streamplot

When each point has a direction and size, such as wind or flow, draw arrows. ax.quiver(X, Y, U, V) puts one arrow at every grid point (U is the x component, V the y component). With a dense grid it gets cluttered, so thin it out with slicing such as X[::5, ::5]. ax.streamplot(x, y, U, V) instead draws continuous flow lines that follow the field, which usually reads better for smooth flows. Both expect a regular grid; for streamplot, x and y are 1D arrays.

Python quiver and streamplot of a swirl

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Both charts show the same rotation: arrows tangent to circles, faster farther from the center. The color of the arrows and lines carries the speed.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Where does ax.imshow(array) draw row 0 by default?

    The default origin is 'upper', matching how matrices and images are written. Use origin='lower' for y-up data.
  2. 2. Why use interpolation='nearest' for a heatmap of a table?

    Each cell is a real measurement. Smoother interpolation blends neighbours and suggests values that were never measured.
  3. 3. pcolormesh gets values of shape (3, 5). How many x edges and y edges does it need?

    Edges are one more than cells: 5 columns need 6 x edges and 3 rows need 4 y edges.
  4. 4. Which colormap setup suits a correlation matrix?

    Correlations are centered on zero, so a diverging map with fixed symmetric limits keeps zero neutral and charts comparable.
  5. 5. What is the difference between contour and contourf?

    contour draws the lines of equal value; contourf fills the regions between levels with colors.

Summary

  • ax.imshow(arr) draws a 2D array as pixels with row 0 at the top; control it with cmap, vmin/vmax, origin, extent and interpolation.
  • ax.pcolormesh(x_edges, y_edges, values) draws uneven cells; the edge arrays are one longer than the data.
  • Write cell values with a double loop and ax.text (x is the column, y the row); always add a colorbar and tick labels.
  • Use a diverging colormap with fixed limits for correlations; sequential maps for counts.
  • contour and contourf show functions of two variables; quiver and streamplot show vector fields.

Next, show uncertainty properly in Error Bars and Uncertainty.