Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 38 ยท Regression and Matrices

Heatmaps with sns.heatmap

Turn a table of numbers into a colour grid with sns.heatmap: annotations, number formats, colormaps, centering, masks, frames and colorbar control.

A heatmap turns a table into a picture. Each cell becomes a coloured square, so you can spot the high values, the low values and the patterns at a glance, where a table of 84 numbers would make you read every one. Seaborn's heatmap() does this in a single call, and a handful of arguments handle almost everything you will want to change.

This lesson covers how to prepare data, how to annotate and format cells, how to pick a colormap, how to centre a scale on a meaningful value, and how to tidy the frame and colour bar.

Data shape: a rectangular table

heatmap() wants a 2D rectangle: a DataFrame (or array) where rows and columns are the two categories and the cell value is the number to colour. If your data is in "long" form (one row per observation), reshape it with pivot_table():

Python From long data to a 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.

Notice reindex(days): pivot_table sorts rows alphabetically, which would put Friday first. Order your categories deliberately.

Annotations and number formats

annot=True prints each value inside its cell. fmt controls the format (a Python format spec such as ".1f", "d" or ".0%"), and annot_kws styles the text, which is how you change the size of the annotations:

Python annot, fmt and annot_kws

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.

linewidths and linecolor draw thin gaps between cells, which makes a grid easier to read. Seaborn picks black or white text automatically for contrast against the cell colour.

Colormaps and centring

The colormap (cmap) maps values to colours. The right choice depends on what the numbers mean:

Data Colormap type Examples
Low to high, all positive Sequential "viridis", "rocket", "Blues", "mako"
Above/below a midpoint Diverging "coolwarm", "vlag", "RdBu_r"
Categories (not numbers) Do not use a heatmap use a bar or count plot

Diverging maps need a meaningful centre. center=0 forces the neutral colour to sit at zero, otherwise it sits at the middle of the data range, which may be misleading. vmin and vmax fix the ends of the scale, which matters when you compare several heatmaps:

Python Diverging colormap centred on zero

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 right panel is honest: red is growth, blue is decline, white is unchanged. The left panel colours a +2 as pale blue or red depending on the data, which can confuse readers.

Prefer perceptually uniform maps (viridis, rocket, mako) for sequential data. Rainbow maps such as jet create false boundaries where there are none.

Masks, frames and the colour bar

  • mask takes a boolean array; cells where it is True are left blank. You will use it to hide the redundant half of a symmetric table in correlation heatmaps.
  • square=True makes cells square.
  • cbar=False removes the colour bar; cbar_kws styles it (label, orientation, shrink).
  • xticklabels and yticklabels accept an integer step (show every nth label) or False.
  • heatmap() returns the Matplotlib Axes, so you can add a frame by turning on the spines.
Python Frame, square cells and no colour bar

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.

Seaborn hides the spines in its default heatmap, so each one needs set_visible(True). Matplotlib then draws the border like any other axes.

Common mistakes

  • Unsorted categories. Reindex rows and columns into a meaningful order.
  • Comparing heatmaps with different scales. Pass the same vmin and vmax to each.
  • Too many cells to annotate. Past roughly 15 by 15, numbers become unreadable; drop annot and rely on colour.
  • Using a heatmap for nominal values. Colours imply order and magnitude.

Next, heatmaps meet statistics with the most famous use: the correlation matrix.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Your data has one row per observation. What do you do before heatmap()?

    heatmap() wants a 2D table where rows and columns are categories and cells are values.
  2. 2. How do you show values rounded to a whole percent in each cell?

    annot=True prints the numbers and fmt takes a format spec; '.0%' multiplies by 100 and adds a percent sign.
  3. 3. Why use center=0 with a diverging colormap?

    Without center, the neutral colour sits at the middle of the data range, not at zero.
  4. 4. How do you enlarge the annotation text?

    annot_kws passes keyword arguments to the text of each cell.

Summary

  • heatmap() needs a rectangular table; use pivot_table() and reindex() to prepare it.
  • annot, fmt and annot_kws control the numbers; cmap, center, vmin, vmax control the colours.
  • linewidths, square, cbar and the returned Axes handle gaps, shape, colour bar and frame.
  • Sequential data gets a sequential map; data around a midpoint gets a diverging map with center.

Next: Correlation Heatmaps