Section 1

1 Before you start

This is not graded, and it does not count towards anything. Answer every question even if you are only guessing — having a go at something before you have been taught it is one of the best ways to remember it afterwards. The lesson ends with another short check, and there you will be shown the correct answer for anything you missed. Choose an option for every question and confidence rating, then click Submit answers.

Pre-test

You draw a heatmap of a correlation matrix. Which set of arguments makes the colour scale comparable across different correlation matrices?

Pre-test

You have two categorical columns and want a heatmap of how many records fall into each combination, with whole-number labels in the cells. Which approach is correct?

Pre-test

You are drawing a heatmap of counts that range from 0 upward, with no negative values. Which colour map best matches the data?

Pre-test

Which seaborn function lets you split a scatter-plus-regression into a row of panels, one per level of a third column?

Pre-test

What is the difference between an axes-level and a figure-level seaborn function?

Pre-test

You just loaded a dataset with six numeric columns and want a quick first look at every pairwise relationship at once. Which function fits best?

Pre-test

You want every seaborn chart in your script to share a white-grid background with larger, slide-friendly fonts, set once at the top. Which call does this?

Pre-test

You want one colour-blind-safe scheme applied to every chart in the script, set a single time. Which call does this?

Pre-confidence

I can draw a multi-panel figure faceted by another column using catplot, relplot, or displot in a single line.

Not at all confident
Fully confident
Pre-confidence

I can produce a correlation heatmap from a DataFrame and pin the colour scale so it means the same thing every time.

Not at all confident
Fully confident
Pre-confidence

I can explain the difference between an axes-level and a figure-level seaborn function, and use pairplot or jointplot to explore several numeric columns at once.

Not at all confident
Fully confident
Section 2

2 Introduction

In Part I, each plot answered one question. This lesson draws tables as heatmaps, splits a plot into panels and sets the look of every plot.

A plotting script starts with import seaborn as sns and import matplotlib.pyplot as plt. Then plt.show() displays the figure.

Most plots in this lesson need a long-form table, with one row for each observation and one column for each variable. So x=, y= and hue= can each name a column. Reshape a wide table with melt first (lesson 1.11c).

Try every example in the Python Scratchpad on the right.

Section 3

3 Heatmaps for correlation and contingency tables

A table of numbers is hard to read when it has many cells. Two such tables are common. One holds the correlation between every pair of columns. The other holds counts, such as the number of samples for each ward and shift.

Section 3.1

3.1 Heatmap

A heatmap draws a table as a grid of coloured squares, one for each cell. The colour of each square shows the size of its number. Unlike most plots in this lesson, a heatmap does not need a long-form table.

A common use is a correlation matrix. For a table of numeric columns, the method df.corr() returns a square table with the correlation of every pair of columns. You pass that table to sns.heatmap. The example below prints the correlation matrix of four columns for eight patients:

import pandas as pd

labs = pd.DataFrame({
    "age": [34, 41, 48, 55, 62, 69, 76, 83],
    "creatinine": [68, 72, 70, 85, 90, 98, 104, 112],
    "egfr": [112, 104, 101, 82, 74, 64, 58, 49],
    "weight_kg": [71, 82, 64, 77, 90, 68, 73, 80],
})
print(labs.corr().round(2))
# age creatinine egfr weight_kg
# age 1.00 0.98 -0.99 0.15
# creatinine 0.98 1.00 -0.99 0.22
# egfr -0.99 -0.99 1.00 -0.20
# weight_kg 0.15 0.22 -0.20 1.00

The columns are age (years), creatinine (µmol/L), eGFR (mL/min/1.73 m²) and weight (kg). Each number is one square of the heatmap. The diagonal is 1.00. This is because each column correlates perfectly with itself. In these patients, creatinine rises with age. So their correlation is close to 1. The eGFR falls as age and creatinine rise. So its correlations with them are close to -1.

Try it out

Try this snippet in the Python Scratchpad on the right.

Try this snippet
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame({
    "age": [54, 61, 47, 72, 38, 55, 49, 67, 41, 58],
    "bmi": [27.3, 28.4, 26.1, 30.2, 24.5, 27.0,
             25.8, 29.7, 24.0, 28.1],
    "glucose": [5.4, 6.1, 4.9, 6.8, 4.5, 5.5, 5.0, 6.4, 4.7, 5.7],
    "chol": [4.8, 5.5, 4.6, 6.2, 4.0, 5.0, 4.5, 5.9, 4.2, 5.1],
})
corr = df.corr()
sns.heatmap(corr, annot=True, cmap="coolwarm", vmin=-1, vmax=1, center=0)
plt.show()
sns.heatmap on a correlation matrix encodes every pairwise correlation as a colour, so the strength and direction of relationships across all numeric columns becomes visible at a glance.
sns.heatmap on a correlation matrix encodes every pairwise correlation as a colour, so the strength and direction of relationships across all numeric columns becomes visible at a glance.

Three arguments make a heatmap easier to read:

  • annot=True writes the number in each square. Colours alone give only an approximate value.
  • cmap sets the colour map. A sequential map such as "viridis" runs from low to high. A diverging map such as "coolwarm" has a middle value, with one colour on each side.
  • vmin, vmax and center fix the ends and the middle of the colour scale. Without them, the scale follows the data. So one colour can mean different numbers in two heatmaps.
A heatmap reads correctly when annot=True shows the cell values, cmap matches the data shape (viridis for sequential, coolwarm for diverging), and vmin/vmax/center pins the scale so colors mean the same thing across plots.
A heatmap reads correctly when annot=True shows the cell values, cmap matches the data shape (viridis for sequential, coolwarm for diverging), and vmin/vmax/center pins the scale so colors mean the same thing across plots.
Section 3.2

3.2 Contingency table

A contingency table counts how often each pair of values from two columns occurs. The function pd.crosstab builds it, as in lesson 1.11c. The example below counts seven samples by ward and shift:

import pandas as pd

labs = pd.DataFrame({
    "ward": ["5A", "7B", "5A", "7B", "7B", "5A", "7B"],
    "shift": ["day", "night", "day", "day", "night", "night", "day"],
})
print(pd.crosstab(labs["ward"], labs["shift"]))
# shift day night
# ward
# 5A 2 1
# 7B 2 2

Each count becomes one coloured square when you pass this table to sns.heatmap. For example, ward 7B has 2 samples from the day shift and 2 samples from the night shift.

Try it out

Try this snippet in the Python Scratchpad on the right.

Try this snippet
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame({
    "clinic": ["A", "A", "A", "B", "B", "B", "C", "C"],
    "sex": ["F", "F", "M", "M", "F", "M", "F", "M"],
})
table = pd.crosstab(df["clinic"], df["sex"])
sns.heatmap(table, annot=True, cmap="viridis", fmt="d")
plt.show()
A heatmap of a contingency table places every record into its (row, column) cell, then uses colour intensity to make the joint distribution readable at a glance.
A heatmap of a contingency table places every record into its (row, column) cell, then uses colour intensity to make the joint distribution readable at a glance.

The exercise above uses fmt="d". The fmt argument sets how each number in a square is written. It takes the same codes as an f-string. By default, annot=True uses .2g, which keeps two significant digits. So a count of 120 is written as 1.2e+02:

count = 120
print(f"{count:.2g}")  # 1.2e+02
print(f"{count:d}")  # 120
print(f"{count:g}")  # 120
print(f"{2.5:g}")  # 2.5
print(f"{2.5:d}")
# ValueError: Unknown format code 'd' for object of type 'float'

The code d works only for integers. If a cell holds a float, even 2.0, Python raises an error, as the last line shows.

The code g writes an integer or a float. It also drops trailing zeros. So g is safer when a table may hold floats. You can use other codes too, such as .2f for two decimal places and .0% for a percentage.

sns.heatmap does not calculate anything. It draws the table that you give it. All the calculation happens in pandas before you call seaborn.

Section 4

4 Combining and faceting plots

Often you want the same plot for each group in a column, such as one histogram for each ward. Seaborn does this in one call.

Faceting repeats one plot for each category of a column, and puts the panels side by side. So you can compare the groups directly.

Faceting turns one chart into a grid of aligned panels, one per category, so distributions can be compared at a glance across one or two grouping variables.
Faceting turns one chart into a grid of aligned panels, one per category, so distributions can be compared at a glance across one or two grouping variables.
Section 4.1

4.1 Core rules in faceting

To use faceting, you need to know the two kinds of seaborn function:

  • An axes-level function draws a single chart. The functions scatterplot, boxplot and histplot are axes-level.
  • A figure-level function creates the whole figure itself. It can split the figure into a grid of panels, with col= for the columns and row= for the rows. The functions relplot, catplot, displot and lmplot are figure-level.
Figure-level functions like displot own the whole canvas and can subdivide it with col= for faceting, while axes-level functions like histplot only draw a single chart and reject col= entirely.
Figure-level functions like displot own the whole canvas and can subdivide it with col= for faceting, while axes-level functions like histplot only draw a single chart and reject col= entirely.

An axes-level function cannot make panels. If you pass col= to one, matplotlib reports an error:

import pandas as pd
import seaborn as sns

labs = pd.DataFrame({
    "ward": ["5A", "7B", "5A", "7B", "7B", "5A", "7B", "5A"],
    "potassium": [4.2, 4.8, 5.4, 5.2, 5.6, 5.1, 6.0, 4.4],
})
sns.histplot(data=labs, x="potassium", col="ward")
# AttributeError: 'Rectangle' object has no property 'col'

The message does not mention faceting. This is because histplot passes extra arguments to matplotlib. Matplotlib does not know col. To make panels, use a figure-level function.

Think of each figure-level function as a family of plots. To facet, call the family function and choose the chart with kind=:

  • Categorical plots (boxplot, barplot) become catplot, for example kind="box".
  • Relational plots (scatterplot, lineplot) become relplot, for example kind="scatter".
  • Distribution plots (histplot, kdeplot) become displot, for example kind="hist".
A figure-level function is one family that draws many chart types, and the kind= argument is the switch that picks which one.
A figure-level function is one family that draws many chart types, and the kind= argument is the switch that picks which one.
Try it out

Try this snippet in the Python Scratchpad on the right.

Try this snippet
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame({
    "clinic": ["A"]*8 + ["B"]*8,
    "sex": (["F"]*4 + ["M"]*4) * 2,
    "bmi": [22.5, 23.0, 24.0, 25.5, 28.0, 29.0, 30.5, 31.0,
             24.0, 25.0, 26.5, 27.0, 28.5, 29.5, 30.0, 31.5],
})
sns.catplot(data=df, x="clinic", y="bmi", col="sex", kind="box")
plt.show()

This one line draws two boxplots side by side, one for female patients and one for male patients. Each compares clinics A and B.

If you pass both row= and col=, you get a full grid, with one panel for each combination of the two columns. The argument height sets the height of each panel in inches. The argument aspect is the width divided by the height.

Try it out

Try this snippet in the Python Scratchpad on the right.

Try this snippet
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame({
    "age": [54, 61, 47, 72, 38, 55, 49, 67, 41, 58, 63, 45],
    "bmi": [27.3, 28.4, 26.1, 30.2, 24.5, 27.0,
             25.8, 29.7, 24.0, 28.1, 29.5, 25.5],
    "sex": ["F", "M"] * 6,
    "clinic": ["A", "A", "B", "B"] * 3,
})
sns.relplot(data=df, x="age", y="bmi", col="sex", row="clinic", kind="scatter")
plt.show()

The function displot facets in the same way as catplot and relplot. You pass a numeric column as x, and split it into panels with col= and row=.

Try it out

Try this snippet in the Python Scratchpad on the right.

Try this snippet
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame({
    "glucose": [5.4, 4.9, 5.1, 6.1, 5.8, 6.7, 5.9, 5.2,
                  6.3, 5.6, 4.8, 7.1, 5.5, 6.0, 5.7, 6.4],
    "sex": ["F", "M"] * 8,
    "clinic": ["A"]*8 + ["B"]*8,
})
sns.displot(data=df, x="glucose", col="sex", row="clinic", kind="hist", kde=True)
plt.show()

Faceting repeats one plot. Sometimes you want two different plots side by side, such as a boxplot next to a histogram. That is not faceting. For this, use matplotlib subplots, as in lesson 1.12b. Every axes-level function draws into the axes that you give it with ax=.

Try it out

Try this snippet in the Python Scratchpad on the right.

Try this snippet
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame({
    "clinic": ["A"]*8 + ["B"]*8,
    "bmi": [22.0, 23.1, 24.0, 23.5, 31.0, 32.1, 30.8, 31.5,
             27.0, 28.0, 27.5, 28.5, 27.2, 28.3, 27.8, 28.1],
    "glucose": [5.4, 4.9, 5.1, 5.0, 5.5, 5.2, 4.8, 5.3,
                 6.1, 5.8, 6.7, 6.3, 5.9, 6.0, 6.4, 6.2],
})

fig, axes = plt.subplots(1, 2, figsize=(10, 4))
sns.boxplot(data=df, x="clinic", y="bmi", ax=axes[0])
sns.histplot(data=df, x="glucose", kde=True, ax=axes[1])
plt.show()

The call plt.subplots(1, 2, figsize=(10, 4)) creates one figure with two empty axes. It returns them as axes[0] and axes[1]. The argument ax=axes[0] tells sns.boxplot where to draw. The argument ax=axes[1] does the same for sns.histplot. The function sns.heatmap takes ax= in the same way.

A figure-level function does not draw into axes that you give it. This is because it always creates its own figure. For example, lmplot raises an error if you pass ax=:

import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns

labs = pd.DataFrame({
    "creatinine": [78, 92, 85, 101, 96, 88, 110, 74],
    "potassium": [4.2, 4.8, 5.4, 5.2, 5.6, 5.1, 6.0, 4.4],
})
fig, axes = plt.subplots(1, 2)
sns.lmplot(data=labs, x="creatinine", y="potassium", ax=axes[0])
# TypeError: lmplot() got an unexpected keyword argument 'ax'

The functions displot, catplot and relplot do not raise an error. They ignore ax= and show a warning. So use an axes-level function when you arrange the panels yourself. Use a figure-level function with col= and row= when you want seaborn to arrange them.

Section 4.2

4.2 Two essential explorers

Two figure-level functions are built for exploring data: pairplot and jointplot.

The function sns.pairplot draws a scatterplot for every pair of numeric columns. The diagonal shows each column on its own. This is a histogram, or a smooth curve if you use hue=. Use it to explore a table that is new to you.

Try it out

Try this snippet in the Python Scratchpad on the right.

Try this snippet
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from pyodide.http import open_url

url = "https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv"
iris = pd.read_csv(open_url(url))

sns.pairplot(iris, hue="species")
plt.show()
sns.pairplot lays every pair of numeric columns into an N×N grid where the off-diagonals are scatterplots, the diagonal shows each column's distribution, and hue colors the points by a categorical column so cluster separation is visible at a glance.
sns.pairplot lays every pair of numeric columns into an N×N grid where the off-diagonals are scatterplots, the diagonal shows each column's distribution, and hue colors the points by a categorical column so cluster separation is visible at a glance.

The grid has a row and a column for each numeric column. Four columns make 16 panels. Twenty columns make 400 panels, which are mostly too small to read. Select the columns you need before you call pairplot.

Try it out

Try this snippet in the Python Scratchpad on the right.

Try this snippet
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd

df = pd.read_csv("patients.csv")
cols = ["age", "bmi", "glucose", "chol", "diagnosis"]
sns.pairplot(df[cols], hue="diagnosis")
plt.show()

The function sns.jointplot shows one pair of columns in detail. It draws a scatterplot in the centre. It draws the distribution of each column along the top and the right edge.

With kind="reg", it adds a regression line. With kind="hex", it draws hexagons that are darker where more points fall. Hexagons suit data with so many points they overlap in a scatterplot.

Try it out

Try this snippet in the Python Scratchpad on the right.

Try this snippet
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame({
 "bmi": [25.0, 27.2, 24.1, 28.5, 29.0, 26.3],
 "glucose": [5.4, 6.1, 4.9, 5.8, 6.7, 5.1],
})
sns.jointplot(data=df, x="bmi", y="glucose", kind="reg")
plt.show()
sns.jointplot shows one pair of variables as a central scatter with marginal histograms on the top and right, where kind="reg" adds a regression line and kind="hex" replaces dots with density-coloured hex bins when the data is too crowded for individual points to read.
sns.jointplot shows one pair of variables as a central scatter with marginal histograms on the top and right, where kind="reg" adds a regression line and kind="hex" replaces dots with density-coloured hex bins when the data is too crowded for individual points to read.

Choose the function that answers your question:

  • catplot, relplot and displot split a plot into rows or columns.
  • pairplot explores a whole table of numeric columns.
  • jointplot shows two columns in detail, with the distribution of each.
  • An axes-level function suits a plot you place yourself.
Different seaborn functions answer different questions, so the choice between catplot/relplot/displot (faceting), pairplot (broad first look), jointplot (two-variable deep-dive) and the axes-level functions (custom matplotlib work) is driven by what you are trying to see, not by personal preference.
Different seaborn functions answer different questions, so the choice between catplot/relplot/displot (faceting), pairplot (broad first look), jointplot (two-variable deep-dive) and the axes-level functions (custom matplotlib work) is driven by what you are trying to see, not by personal preference.
Section 5

5 Themes and palettes

The default look suits exploring your data. Change the theme for a report or presentation.

A theme sets the background, grid, fonts and line widths. The call sns.set_theme() changes the look of every plot that follows. It has two main arguments:

  • style sets the background, grid and axes. The options are "darkgrid", "whitegrid", "dark", "white" and "ticks".
  • context scales the fonts and line widths for where the plot will be seen. The options are "paper", "notebook", "talk" and "poster".
sns.set_theme() takes two main arguments — style swaps the background, grid, and axes, while context proportionally scales fonts and line widths inside a fixed figure, with poster so large it crowds out the plot area itself.
sns.set_theme() takes two main arguments — style swaps the background, grid, and axes, while context proportionally scales fonts and line widths inside a fixed figure, with poster so large it crowds out the plot area itself.

A palette is the set of colours a plot uses. The call sns.set_palette() sets the palette for every plot that follows. The argument palette= sets it for one plot. It colours the groups of the hue column. The palettes "viridis" and "colorblind" are designed to stay readable for people with colour-vision deficiency.

Colours in seaborn can be set globally with sns.set_palette() or for one plot only via the palette= argument, and "viridis" and "colorblind" are two accessible defaults that work with either method.
Colours in seaborn can be set globally with sns.set_palette() or for one plot only via the palette= argument, and "viridis" and "colorblind" are two accessible defaults that work with either method.

The exercise below uses a theme and a palette together:

Try it out

Try this snippet in the Python Scratchpad on the right.

Try this snippet
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd

sns.set_theme(style="whitegrid", context="talk")

df = pd.DataFrame({
    "clinic": ["A", "A", "B", "B", "C", "C"],
    "sex": ["F", "M", "F", "M", "F", "M"],
    "bmi": [27.4, 29.0, 31.1, 30.5, 24.8, 26.1],
})
sns.barplot(data=df, x="clinic", y="bmi", hue="sex", palette="colorblind")
plt.show()
Section 6

6 Check your understanding

You have reached the end of the module. Try the same questions again — your answers here, paired with your pre-test answers, are how we measure what the module taught you. Answer every question and confidence rating, then click Submit and see results to view your score.

Post-test

You draw a heatmap of a correlation matrix. Which set of arguments makes the colour scale comparable across different correlation matrices?

Post-test

You have two categorical columns and want a heatmap of how many records fall into each combination, with whole-number labels in the cells. Which approach is correct?

Post-test

You are drawing a heatmap of counts that range from 0 upward, with no negative values. Which colour map best matches the data?

Post-test

Which seaborn function lets you split a scatter-plus-regression into a row of panels, one per level of a third column?

Post-test

What is the difference between an axes-level and a figure-level seaborn function?

Post-test

You just loaded a dataset with six numeric columns and want a quick first look at every pairwise relationship at once. Which function fits best?

Post-test

You want every seaborn chart in your script to share a white-grid background with larger, slide-friendly fonts, set once at the top. Which call does this?

Post-test

You want one colour-blind-safe scheme applied to every chart in the script, set a single time. Which call does this?

Post-confidence

I can draw a multi-panel figure faceted by another column using catplot, relplot, or displot in a single line.

Not at all confident
Fully confident
Post-confidence

I can produce a correlation heatmap from a DataFrame and pin the colour scale so it means the same thing every time.

Not at all confident
Fully confident
Post-confidence

I can explain the difference between an axes-level and a figure-level seaborn function, and use pairplot or jointplot to explore several numeric columns at once.

Not at all confident
Fully confident
Section 7

7 Your results

Here is how your post-test answers compare with your pre-test answers. The pre/post pairing is the most reliable way to see what this module actually taught you.

Your score

Submit the post-test to see your results.

Muddiest point

What is the one thing from this module that is still unclear to you?

Rate this module

Overall, how would you rate this module?

How likely are you to recommend this module to a peer? (0 = not at all, 10 = extremely likely)