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.
You draw a heatmap of a correlation matrix. Which set of arguments makes the colour scale comparable across different correlation matrices?
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?
You are drawing a heatmap of counts that range from 0 upward, with no negative values. Which colour map best matches the data?
Which seaborn function lets you split a scatter-plus-regression into a row of panels, one per level of a third column?
What is the difference between an axes-level and a figure-level seaborn function?
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?
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?
You want one colour-blind-safe scheme applied to every chart in the script, set a single time. Which call does this?
I can draw a multi-panel figure faceted by another column using catplot, relplot, or displot in a single line.
I can produce a correlation heatmap from a DataFrame and pin the colour scale so it means the same thing every time.
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.
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.
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.
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.00The 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 this snippet in the Python Scratchpad on the right.
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()

Three arguments make a heatmap easier to read:
annot=Truewrites the number in each square. Colours alone give only an approximate value.cmapsets 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,vmaxandcenterfix 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.

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 2Each 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 this snippet in the Python Scratchpad on the right.
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()

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.
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.

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,boxplotandhistplotare 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 androw=for the rows. The functionsrelplot,catplot,displotandlmplotare figure-level.

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) becomecatplot, for examplekind="box". - Relational plots (
scatterplot,lineplot) becomerelplot, for examplekind="scatter". - Distribution plots (
histplot,kdeplot) becomedisplot, for examplekind="hist".

Try this snippet in the Python Scratchpad on the right.
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 this snippet in the Python Scratchpad on the right.
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 this snippet in the Python Scratchpad on the right.
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 this snippet in the Python Scratchpad on the right.
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.
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 this snippet in the Python Scratchpad on the right.
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()

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 this snippet in the Python Scratchpad on the right.
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 this snippet in the Python Scratchpad on the right.
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()

Choose the function that answers your question:
catplot,relplotanddisplotsplit a plot into rows or columns.pairplotexplores a whole table of numeric columns.jointplotshows two columns in detail, with the distribution of each.- An axes-level function suits a plot you place yourself.

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:
stylesets the background, grid and axes. The options are"darkgrid","whitegrid","dark","white"and"ticks".contextscales the fonts and line widths for where the plot will be seen. The options are"paper","notebook","talk"and"poster".

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.

The exercise below uses a theme and a palette together:
Try this snippet in the Python Scratchpad on the right.
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()
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.
You draw a heatmap of a correlation matrix. Which set of arguments makes the colour scale comparable across different correlation matrices?
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?
You are drawing a heatmap of counts that range from 0 upward, with no negative values. Which colour map best matches the data?
Which seaborn function lets you split a scatter-plus-regression into a row of panels, one per level of a third column?
What is the difference between an axes-level and a figure-level seaborn function?
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?
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?
You want one colour-blind-safe scheme applied to every chart in the script, set a single time. Which call does this?
I can draw a multi-panel figure faceted by another column using catplot, relplot, or displot in a single line.
I can produce a correlation heatmap from a DataFrame and pin the colour scale so it means the same thing every time.
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.
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.
Submit the post-test to see your results.
What is the one thing from this module that is still unclear to you?