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 have a DataFrame with columns clinic and patient_id and want a chart of how many patients are at each clinic. Which call is right?
In sns.barplot(data=df, x="clinic", y="glucose"), what does the height of each bar represent by default?
Which seaborn call shows the shape of a single numeric column, with the option to overlay a smooth density curve?
You want to compare the shapes of the glucose distribution for clinic A versus clinic B as two smooth curves overlaid on the same axes. Which call fits best?
You want to compare the distribution of bmi across three clinics in one chart, and you need to see whether any clinic has a bimodal distribution (two separate peaks). Which plot is the best choice?
With only about 15 patients per clinic, you want to show every individual bmi point on top of a boxplot, arranged so the dots never overlap. Which call adds those points?
You want a scatter of age vs bmi with a fitted regression line and a 95% confidence band. Which one-line call does this on a single set of axes?
You want a scatter of age vs bmi where the point colour shows sex and the point size reflects bmi. Which call does this?
I can pick the right seaborn plot for a given question about a DataFrame — counts per category, distribution shape, or the relationship between two numeric columns.
I can choose between a histogram, KDE, boxplot, and violin plot to show a distribution, and overlay a stripplot or swarmplot to show the individual points.
2 Introduction
A chart can show patterns that a long table of readings hides.
Seaborn is a Python library that draws a chart from a pandas DataFrame in one line of code. It is built on matplotlib, which you used in the last two lessons.

Each family of Seaborn plots answers one kind of question. This lesson covers the first three families in the picture below: categorical, distribution and relationship plots.

Each plotting script starts with import seaborn as sns and import matplotlib.pyplot as plt. Then plt.show() displays the figure.
Try every example in the Python Scratchpad on the right.
3 Categorical plots (count, bar)
A categorical column holds labels, such as ward names, sexes or blood types. Two questions come up often. How many rows belong to each category? What is the average of a number within each category?
Seaborn answers the first question with countplot and the second question with barplot.
3.1 sns.countplot
The function sns.countplot is the simpler of the two. It works like a histogram for categories. You pass the DataFrame as data and the category column as x. Seaborn draws one bar for each category. The height of the bar is the number of rows in that category. To see these numbers, count the rows of a column with value_counts:
import pandas as pd
labs = pd.DataFrame({
"sample_id": ["S01", "S02", "S03", "S04", "S05", "S06", "S07"],
"ward": ["5A", "7B", "5A", "7B", "7B", "5A", "7B"],
})
print(labs["ward"].value_counts())
# ward
# 7B 4
# 5A 3
# Name: count, dtype: int64Ward 7B has 4 rows and ward 5A has 3 rows. So a countplot of the ward column draws one bar of height 4 and one bar of height 3.
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({
"patient_id": ["P001", "P002", "P003", "P004", "P005", "P006"],
"clinic": ["A", "B", "A", "B", "B", "A"],
"sex": ["F", "M", "F", "F", "M", "M"],
"glucose": [5.4, 6.1, 4.9, 5.8, 6.7, 5.1],
})
sns.countplot(data=df, x="clinic")
plt.show()
The picture shows how countplot counts the rows one at a time.

The hue argument breaks the count in each category down by a second column. For example, the function pd.crosstab counts the samples of each ward by 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 ward has one count for each shift. With hue="shift", a countplot draws one bar for each of these counts.
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({
"patient_id": ["P001", "P002", "P003", "P004", "P005", "P006"],
"clinic": ["A", "B", "A", "B", "B", "A"],
"sex": ["F", "M", "F", "F", "M", "M"],
"glucose": [5.4, 6.1, 4.9, 5.8, 6.7, 5.1],
})
sns.countplot(data=df, x="clinic", hue="sex")
plt.show()
Now each category has two bars side by side instead of one. The counts of the two groups are separate. So you can compare the groups within each category.
The name that you pass as x must match a column of the DataFrame exactly. If it does not, Seaborn reports an error:
import pandas as pd
import seaborn as sns
labs = pd.DataFrame({
"ward": ["5A", "7B", "5A", "7B", "7B", "5A", "7B"],
})
sns.countplot(data=labs, x="wards")
# ValueError: Could not interpret value `wards` for `x`. An entry with this name does not appear in `data`.The message names the value that Seaborn could not find. Check the spelling and the capital letters of the column name.
3.2 sns.barplot
When you want an average instead of a count, use sns.barplot.
Pass a category column as x and a numeric column as y. Seaborn calculates the mean of y for each category and draws one bar for each mean. The thin vertical line on each bar is an error bar. It shows the 95% confidence interval of that mean. A longer line means the mean is less certain. To see the means, group the potassium results by ward:
import pandas as pd
labs = pd.DataFrame({
"ward": ["5A", "7B", "5A", "7B", "7B", "5A", "7B"],
"potassium": [4.2, 4.8, 5.4, 5.2, 5.6, 5.1, 6.0],
})
print(labs.groupby("ward")["potassium"].mean())
# ward
# 5A 4.9
# 7B 5.4
# Name: potassium, dtype: float64A barplot with x="ward" and y="potassium" draws a bar of height 4.9 for ward 5A and a bar of height 5.4 for ward 7B.
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"],
"glucose": [5.4, 4.9, 5.1, 6.1, 5.8, 6.7],
})
sns.barplot(data=df, x="clinic", y="glucose")
plt.show()
The picture shows how each bar is built from the rows of one category.

As in countplot, the hue argument splits each category by a second column.
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", "A", "B", "B", "B", "B"],
"sex": ["F", "F", "M", "M", "F", "F", "M", "M"],
"glucose": [5.4, 4.9, 5.1, 5.0, 6.1, 5.8, 6.7, 6.4],
})
sns.barplot(data=df, x="clinic", y="glucose", hue="sex")
plt.show()
Seaborn draws one bar for each value of the hue column, side by side within each category. A legend names the colours. So one chart compares two groupings at once.

Two more arguments change a barplot.
The order argument sets the order of the bars along the x-axis. For example, order=["B", "A"] puts category B first. This suits categories with a natural order, such as days of the week.
The estimator argument changes the calculation. The default is the mean. You can pass "sum" for totals, np.median for medians (after import numpy as np), or any function that takes an array and returns one number. This table shows two summaries of the potassium results:
import pandas as pd
labs = pd.DataFrame({
"ward": ["5A", "7B", "5A", "7B", "7B", "5A", "7B"],
"potassium": [4.2, 4.8, 5.4, 5.2, 5.6, 5.1, 6.0],
})
print(labs.groupby("ward")["potassium"].agg(["mean", "median"]))
# mean median
# ward
# 5A 4.9 5.1
# 7B 5.4 5.4With the default estimator, each bar is as tall as the mean column. With estimator=np.median, each bar is as tall as the median column.
Try this snippet in the Python Scratchpad on the right.
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
df = pd.DataFrame({
"clinic": ["A", "A", "B", "B", "B"],
"glucose": [5.0, 6.0, 7.0, 8.0, 9.0],
})
sns.barplot(data=df, x="clinic", y="glucose", order=["B", "A"], estimator="sum")
plt.show()

A countplot and a barplot can look alike, but they answer different questions.
The height of a countplot bar is a count of rows. The height of a barplot bar is a summary of a numeric y column, such as its mean. So a countplot needs only the category column. If you pass a y column as well, Seaborn reports an error:
import pandas as pd
import seaborn as sns
labs = pd.DataFrame({
"ward": ["5A", "7B", "5A", "7B", "7B", "5A", "7B"],
"potassium": [4.2, 4.8, 5.4, 5.2, 5.6, 5.1, 6.0],
})
sns.countplot(data=labs, x="ward", y="potassium")
# TypeError: Cannot pass values for both `x` and `y`.To summarise potassium for each ward, use barplot instead.

4 Distribution plots (histogram, KDE, box, violin)
A distribution plot shows the shape of one numeric column. Are the values bunched around one peak, or split into two?
Seaborn has four common plots for these shapes.
The first is sns.histplot. Like plt.hist, it divides the values into bins and draws one bar for each bin. You pass the numeric column as x.
Two arguments change the plot:
bins=sets the number of bars. Too few bars hide the shape of the data. Too many bars make the shape jagged.kde=Truedraws a smooth curve over the bars.
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],
})
sns.histplot(data=df, x="glucose", bins=8, kde=True)
plt.show()

The function sns.displot takes the same arguments as histplot and draws the same kind of chart. It is a figure-level function, which means it creates a new figure of its own. The function histplot draws into the axes that are already open. Run displot on the same data as above:
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],
})
sns.displot(data=df, x="glucose", bins=8, kde=True)
plt.show()
To see only the smooth curve, use sns.kdeplot. KDE is short for kernel density estimate, which is a smooth estimate of how the values are spread out. A KDE plot suits two or three distributions that you want to compare on one chart. The hue= argument draws one curve for each group.
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,
"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],
})
sns.kdeplot(data=df, x="glucose", hue="clinic")
plt.show()

Use sns.boxplot to compare distributions across many groups. Put a category column on the x axis and a numeric column on the y axis. Each group gets one box.
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"]*6 + ["B"]*6 + ["C"]*6,
"bmi": [27.3, 24.1, 31.2, 22.8, 26.5, 28.0,
29.5, 30.1, 27.8, 32.4, 28.9, 31.7,
24.2, 25.8, 23.7, 26.1, 24.9, 25.4],
})
sns.boxplot(data=df, x="clinic", y="bmi")
plt.show()
The box runs from the 25th percentile to the 75th percentile, with a line at the median. The whiskers reach the lowest and highest values that are not outliers. A value is an outlier if it lies more than 1.5 times the height of the box beyond the box. The plot draws each outlier as a separate point.

The function sns.violinplot draws a small box in the middle. Around the box, it draws a mirrored KDE curve. A wide part of the curve means that many values lie near that height. A narrow part means that few values lie there. To see why this matters, compare the heart rates of eight patients on each of two wards:
import numpy as np
ward_5a = [58, 60, 62, 64, 92, 94, 96, 98]
ward_7b = [72, 74, 76, 77, 78, 80, 82, 84]
print(np.median(ward_5a)) # 78.0
print(np.median(ward_7b)) # 77.5The two medians are almost equal. But the patients on ward 5A form two clusters. No patient has a heart rate near 78. A boxplot of ward 5A draws one tall box with the median line in the gap. A violin plot draws two wider parts with a narrower waist between them.
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],
})
sns.violinplot(data=df, x="clinic", y="bmi")
plt.show()

Choose the plot that answers your question:
- A histogram shows how many values fall in each bin of one column.
- A KDE plot shows the shapes of overlapping distributions, for example one curve for each group.
- A boxplot summarises many groups side by side, with the median, the quartiles and the outliers.
- A violin plot gives the same side-by-side view and also shows the shape of each group.

The functions boxplot and violinplot also have a figure-level version, sns.catplot. Its kind= argument chooses the plot. The value kind="box" draws a boxplot. The value kind="violin" draws a violin plot like the one above:
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],
})
sns.catplot(data=df, x="clinic", y="bmi", kind="violin")
plt.show()
5 Showing individual points with stripplot and swarmplot
Boxplots and violin plots hide individual values. With a small sample, you can draw every value as a dot.
Seaborn has two plots for this:
sns.stripplotdraws one dot for each row, with a small random sideways shift called jitter to spread the dots out.sns.swarmplotalso draws one dot for each row. It places dots sideways to avoid overlaps. With many rows, Seaborn warns that some dots cannot be placed.
Call either plot right after a boxplot to put the dots on top of the box.
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"]*5 + ["B"]*5 + ["C"]*5,
"bmi": [27.4, 29.0, 25.2, 28.1, 26.8,
31.1, 30.5, 32.8, 29.9, 33.2,
24.8, 26.1, 23.9, 25.5, 24.2],
})
sns.boxplot(data=df, x="clinic", y="bmi", color="lightgrey")
sns.stripplot(data=df, x="clinic", y="bmi", color="black")
plt.show()

6 Relationship plots (scatter, regression)
A relationship plot shows how two numeric columns relate to each other. For example, does drug dose rise with body weight?
The function sns.scatterplot draws a scatter plot. You pass two numeric columns as x and y. Seaborn draws one dot for each row. Three more arguments add information from other columns. The argument hue colours the dots by a column. The argument size scales the dots by a column. The argument style changes the dot shape by a column.
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, 24.1, 31.2, 22.8, 29.5, 26.0,
28.4, 23.5, 30.1, 25.7],
"sex": ["F", "M", "F", "M", "F", "M", "F", "M", "F", "M"],
})
sns.scatterplot(data=df, x="age", y="bmi", hue="sex", size="bmi", style="sex")
plt.show()

A scatter plot raises the question of whether the dots follow a trend. The function sns.regplot draws the dots and a regression line, which is the line that best fits them. A see-through band around the line shows the 95% confidence interval. The line is straight by default. If the dots do not follow a straight line, order=2 fits a quadratic curve. The argument lowess=True fits a line that bends with the data.
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],
})
sns.regplot(data=df, x="age", y="bmi")
plt.show()

To compare the trends of different groups, use sns.lmplot. It draws the same dots and line as regplot. It is a figure-level function. So it can split the data into several panels, called small multiples. The argument col= makes one panel for each value of a column. All panels share the same axes. So you can compare them directly. The hue argument draws a separate line for each group inside one panel.
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", "F", "M", "F", "M",
"F", "M", "F", "M", "F", "M"],
})
sns.lmplot(data=df, x="age", y="bmi", col="sex")
plt.show()

The line and the band look reliable even when they are not. A straight line fits well only if the dots follow a straight line with an even spread. Look at the dots first. If the dots fan out, curve or include a far outlier, the line can mislead you. The lists y_linear and y_curved hold the y values of two datasets. They have the same mean and the same standard deviation:
import numpy as np
y_linear = [8.04, 6.95, 7.58, 8.81, 8.33, 9.96, 7.24, 4.26, 10.84, 4.82, 5.68]
y_curved = [9.14, 8.14, 8.74, 8.77, 9.26, 8.10, 6.13, 3.10, 9.13, 7.26, 4.74]
print(round(np.mean(y_linear), 2), round(np.mean(y_curved), 2)) # 7.5 7.5
print(round(np.std(y_linear), 2), round(np.std(y_curved), 2)) # 1.94 1.94Both datasets belong to Anscombe's quartet. The data in y_linear follow a straight trend. The data in y_curved follow a curve. Yet all four datasets of the quartet have almost the same regression line. The picture shows them.

Use scatterplot when you want only the points. Use regplot when you want the points and one trend line on one chart. Use lmplot when you want to split the same relationship into panels by another column.
7 Wrapping up Part I
The picture below shows the three plot families of this lesson. Each family answers one kind of question about a DataFrame.

8 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 have a DataFrame with columns clinic and patient_id and want a chart of how many patients are at each clinic. Which call is right?
In sns.barplot(data=df, x="clinic", y="glucose"), what does the height of each bar represent by default?
Which seaborn call shows the shape of a single numeric column, with the option to overlay a smooth density curve?
You want to compare the shapes of the glucose distribution for clinic A versus clinic B as two smooth curves overlaid on the same axes. Which call fits best?
You want to compare the distribution of bmi across three clinics in one chart, and you need to see whether any clinic has a bimodal distribution (two separate peaks). Which plot is the best choice?
With only about 15 patients per clinic, you want to show every individual bmi point on top of a boxplot, arranged so the dots never overlap. Which call adds those points?
You want a scatter of age vs bmi with a fitted regression line and a 95% confidence band. Which one-line call does this on a single set of axes?
You want a scatter of age vs bmi where the point colour shows sex and the point size reflects bmi. Which call does this?
I can pick the right seaborn plot for a given question about a DataFrame — counts per category, distribution shape, or the relationship between two numeric columns.
I can choose between a histogram, KDE, boxplot, and violin plot to show a distribution, and overlay a stripplot or swarmplot to show the individual points.
9 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?