SyntaxPilot
Courses/Data Analytics with Python/Lesson 33
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

Data Analytics with Python · Lesson 33 of 90

Charts 4: seaborn for statistical plots

seabornhistplotkdeplotkernel density estimate (KDE)boxplotviolinplotcountplotbarplot with confidence intervalscatterplotlineplothuepairplotheatmapFacetGrid

These are the notes for Data Analytics with Python, episode 33. You can draw any chart with matplotlib and you know which chart answers which question, but some charts took a loop and ten lines. seaborn is a library built on top of matplotlib that draws statistical charts straight from a pandas DataFrame, usually in one line. Some seaborn charts quietly compute statistics (a mean, a confidence interval, a density), so here you learn exactly what each one computes. Covered: the data=, x=, y=, hue= pattern, histplot, kdeplot and the kernel density estimate (KDE), boxplot vs violinplot, countplot, barplot with a confidence interval, scatterplot, lineplot, pairplot, heatmap, the figure-level relplot, catplot and FacetGrid, and themes. Every term is defined the first time it appears and collected in the Glossary.

Every program below was run for real (Python 3.13, pandas 3.0.5, matplotlib 3.11.2, seaborn 0.13.2, on a server with no screen); the images are the files those exact programs saved. The orders are made-up data generated with a fixed seed.

The data: 600 orders in a tidy DataFrame

import sys; sys.tracebacklimit = 0
import numpy as np, pandas as pd
import matplotlib.pyplot as plt, seaborn as sns
rng = np.random.default_rng(33); n = 600
stall = rng.choice(["Pune", "Nashik", "Mumbai"], n)
office = (stall == "Mumbai") & (rng.random(n) < 0.5)      # Mumbai: office lunches
bill = np.where(office, rng.normal(260, 30, n), rng.gamma(4, 28, n)).round()
wait = rng.uniform(1, 15, n).round(1)
df = pd.DataFrame({"stall": stall, "bill": bill, "wait": wait,
    "day": rng.choice(["weekday", "weekend"], n, p=[0.7, 0.3]),
    "pay": rng.choice(["UPI", "Cash", "Card"], n, p=[0.6, 0.3, 0.1]),
    "rating": (5 - 0.18 * wait + rng.normal(0, 0.4, n)).clip(1, 5).round(1)})
print(df.head(3))
print(df.shape)
    stall   bill  wait      day   pay  rating
0  Mumbai  265.0   1.7  weekday   UPI     4.6
1  Nashik   35.0  14.1  weekday   UPI     2.7
2  Nashik   93.0   8.4  weekday  Card     4.2
(600, 6)
  • rng.choice(list, n, p=[...]) picks n values with the given probabilities (70% weekday, 30% weekend).
  • office is a boolean mask: True for about half of Mumbai's orders. np.where(office, a, b) takes the office-lunch bill (around 260 rupees) where the mask is True and an ordinary bill otherwise. So Mumbai has two kinds of orders, which will matter later.
  • seaborn is imported as sns by convention.
  • One row per order and one column per variable is tidy data (also called long-form data, episode 2). seaborn is designed for exactly this shape.

The seaborn pattern: data=, x=, hue=

The question: how do bills differ by stall? The obvious attempt is matplotlib:

fig, ax = plt.subplots()
for name in ["Pune", "Nashik", "Mumbai"]:
    part = df[df["stall"] == name]
    ax.hist(part["bill"], bins=30, alpha=0.5, label=name)
ax.set(xlabel="bill", ylabel="Count")
ax.legend(title="stall")
fig.savefig("mpl_hist.png")
print("8 lines of matplotlib")
8 lines of matplotlib

It works, but you wrote the grouping, the colours, the labels and the legend by hand. The fix:

ax = sns.histplot(data=df, x="bill", hue="stall")
ax.figure.savefig("histplot.png")
print(type(ax).__name__)
Axes
matplotlib (8 lines) seaborn (1 line)
mpl_hist.png histplot.png
  • data=df: the DataFrame. x="bill": a column name (text), not the values.
  • hue="stall": split the rows by this column and give each group its own colour, with a legend. ("Hue" means colour.)
  • seaborn labels the axes from the column names and returns a normal matplotlib Axes, so set_title, annotate and everything from episodes 30-32 still work.
  • Mumbai's bars already show a second hump around 250-300 rupees: the office lunches.

Most common error: column names are case sensitive.

sns.histplot(data=df, x="Bill")
ValueError: Could not interpret value `Bill` for `x`. An entry with this name does not appear in `data`.

Check df.columns and use exactly "bill".

kdeplot: the kernel density estimate

Histograms are blocky, and the shape depends on the bin edges (stacking bricks into boxes). Instead, pour a small pile of sand on every single value: each pile is a smooth bump called a kernel. Where many values are close, the piles merge into a tall hill. Adding up all the bumps gives one smooth curve, the kernel density estimate (KDE): an estimate of the distribution's shape. The y axis is density: taller means more values packed there, and the total area under a single KDE is 1.

ax = sns.kdeplot(data=df, x="bill", hue="stall", fill=True)
ax.figure.savefig("kde.png")
print("saved kde.png")
saved kde.png

kde.png

  • fill=True shades the area under each curve.
  • Nashik and Pune have one peak near 100 rupees; Mumbai has two peaks (about 100 and 260). A distribution with two peaks is bimodal.
  • With hue, by default all the curves together have area 1 (common_norm=True), so a group with fewer rows gets a lower curve. common_norm=False gives each group area 1.
  • Cautions: a KDE is smooth by design, so it can spill below 0 rupees where no bill exists; pass cut=0 to stop at the data. bw_adjust changes the smoothness (bandwidth): smaller is wigglier, larger is smoother. Like bins, compare with a histogram before trusting it.

boxplot vs violinplot

fig, axs = plt.subplots(1, 2, figsize=(11, 4.5), sharey=True)
sns.boxplot(data=df, x="stall", y="bill", ax=axs[0])
sns.violinplot(data=df, x="stall", y="bill", ax=axs[1])
fig.savefig("box_violin.png")
print(df.groupby("stall")["bill"].median())
stall
Mumbai    196.0
Nashik    106.0
Pune      105.0
Name: bill, dtype: float64

box_violin.png

  • x= the group column, y= the number. ax=axs[0] tells an axes-level seaborn function which Axes to draw on.
  • The box plot misleads here: Mumbai's median is 196 rupees, but almost no order is near 196: orders are around 100 or around 260. Five numbers (episode 31) can't show two humps.
  • A violin plot is a KDE drawn on both sides, like a mirror; its width shows how many values are at each height. Mumbai's violin is fat at the bottom and fat at the top: two kinds of orders. A tiny box plot is drawn inside. Use violins when the shape matters.

barplot: a mean with a confidence interval

ax = sns.barplot(data=df, x="stall", y="bill")
ax.figure.savefig("barplot.png")
print(df.groupby("stall")["bill"].agg(["mean", "sum"]).round(1))
         mean      sum
stall                 
Mumbai  182.8  34549.0
Nashik  114.6  24062.0
Pune    112.5  22621.0

barplot.png

  • The trap: the bar heights are means (182.8 for Mumbai), not totals (34,549). seaborn's barplot draws an estimate, the mean by default. For totals: estimator="sum".
  • The thin black line is an error bar showing a 95% confidence interval (CI). Our 600 orders are a sample; another month would give a slightly different average. The confidence interval is a range that, by a standard method, is likely to contain the true average.
  • seaborn computes it by bootstrapping: it resamples the data (draws the same number of rows again, with replacement) 1,000 times, computes the mean each time, and keeps the middle 95% of those means. A short line means a precise estimate; a long line means uncertain. Mumbai's is longest because its bills vary most.
  • errorbar=None removes the error bar; errorbar="sd" shows the standard deviation instead (a measure of spread, covered in the statistics episodes).

countplot and scatterplot

fig, axs = plt.subplots(1, 2, figsize=(11, 4.5))
sns.countplot(data=df, x="pay", hue="day", ax=axs[0])
sns.scatterplot(data=df, x="wait", y="rating", hue="stall", alpha=0.6, ax=axs[1])
fig.tight_layout()
fig.savefig("count_scatter.png")
print(df["pay"].value_counts())
pay
UPI     361
Cash    180
Card     59
Name: count, dtype: int64

count_scatter.png

  • countplot counts rows per category: value_counts, drawn. hue="day" splits each bar into weekday and weekend.
  • scatterplot is ax.scatter with hue handled for you. Every stall's dots slope down the same way: longer wait, lower rating.

lineplot: averages with a confidence band

df["mins"] = df["wait"].round()
ax = sns.lineplot(data=df, x="mins", y="rating", hue="day")
ax.figure.savefig("lineplot.png")
print(df.groupby("mins").size().tolist())
[12, 44, 30, 48, 40, 44, 34, 54, 42, 51, 36, 60, 34, 49, 22]

lineplot.png

  • Many orders share each whole minute (12 orders at 1 minute, 44 at 2 ...). When x values repeat, lineplot averages y for each x and draws a shaded confidence band (the 95% CI) around the mean line.
  • Mean rating falls from about 4.7 at 2 minutes to about 2.3 at 15. Weekday and weekend overlap almost completely.
  • errorbar=None turns the band off; estimator=None plots every point unaggregated.

pairplot: every pair of columns

g = sns.pairplot(df, vars=["bill", "wait", "rating"], hue="stall")
g.savefig("pairplot.png")
print(type(g).__name__)
PairGrid

pairplot.png

  • A pair plot draws a scatter for every pair of numeric columns, with each column's own distribution (a KDE when hue is set) on the diagonal. 3 columns → a 3 × 3 grid.
  • Wait vs rating slopes clearly; bill vs wait is a shapeless cloud (no relationship). The fastest first look at a new dataset.
  • It returns a PairGrid (a figure with a grid of axes); save it with g.savefig.

heatmap with annotations

table = pd.crosstab(df["stall"], df["pay"])
print(table)
ax = sns.heatmap(table, annot=True, fmt="d", cmap="Blues")
ax.figure.savefig("heatmap.png")
pay     Card  Cash  UPI
stall                  
Mumbai    20    63  106
Nashik    24    57  129
Pune      15    60  126

heatmap.png

  • pd.crosstab(a, b) counts each combination of two categorical columns (a contingency table).
  • sns.heatmap colours each cell and takes the row and column labels from the DataFrame. annot=True writes the number in each cell; fmt="d" formats them as whole numbers (".1f" for one decimal). UPI is darkest at every stall; Nashik has the most UPI orders (129).

Axes-level vs figure-level functions

The obvious attempt: one scatter per stall, so give relplot our own axes like we did with boxplot:

fig, ax = plt.subplots()
sns.relplot(data=df, x="wait", y="rating", col="stall", ax=ax)
UserWarning: relplot is a figure-level function and does not accept the `ax` parameter. You may wish to try scatterplot

It's only a warning (the program continues), but our ax is ignored.

seaborn has two kinds of functions (think: printing one photo vs making a whole album page):

Axes-level (one photo) Figure-level (an album page)
histplot, kdeplot, boxplot, violinplot, countplot, barplot, scatterplot, lineplot, heatmap relplot (scatter/line), displot (hist/kde), catplot (box/violin/bar/count ...), pairplot
draws into one Axes; accepts ax= builds its own figure; splits data into panels with col= and row=
returns an Axes returns a FacetGrid (or PairGrid)
g = sns.relplot(data=df, x="wait", y="rating", col="stall", hue="day", height=3.5)
g.savefig("relplot.png")
print(type(g).__name__, g.axes.shape)
FacetGrid (1, 3)

relplot.png

  • col="stall": one panel (column) per stall; row= adds rows. height=3.5 is each panel's height in inches.
  • A FacetGrid holds the figure and its grid of axes (g.axes). A facet is one subset of the data shown in its own panel; this is the small multiples idea from episode 32 in one call.

catplot and FacetGrid

g = sns.catplot(data=df, x="stall", y="bill", col="day", kind="violin", height=3.5)
g.savefig("catplot.png")
print(type(g).__name__)
FacetGrid
g = sns.FacetGrid(df, row="day", col="stall", height=2.6)
g.map_dataframe(sns.histplot, x="bill", bins=20)
g.savefig("facetgrid.png")
print(g.axes.shape)
(2, 3)
catplot(kind="violin", col="day") FacetGrid(row="day", col="stall")
catplot.png facetgrid.png
  • catplot(kind=...) = the figure-level version of the category plots: "strip" (default), "box", "violin", "bar", "count", "point".
  • sns.FacetGrid(df, row=, col=) builds an empty grid; g.map_dataframe(func, x=...) runs a plotting function once per subset. Mumbai's two humps appear on weekdays and weekends; every stall has fewer weekend orders.

Themes

sns.set_theme(style="whitegrid", palette="colorblind")
g = sns.displot(data=df, x="bill", hue="stall", kind="kde", height=3.5, aspect=1.6)
g.savefig("theme.png")
print("whitegrid + colorblind")
whitegrid + colorblind

theme.png

  • sns.set_theme(style=..., palette=...) changes the look of every chart after it (matplotlib charts too). Styles: "darkgrid" (default), "whitegrid", "dark", "white", "ticks". palette="colorblind" gives colours most colour-blind viewers can tell apart (episode 32).
  • displot(kind="kde") is the figure-level version of kdeplot (kind="hist" for histograms); aspect=1.6 makes each panel 1.6 times as wide as it is tall.
  • sns.set_theme() with no arguments restores seaborn's defaults; context="talk" enlarges fonts for slides.

Common mistakes

Code / habit Real error / symptom Why Fix
sns.histplot(data=df, x="Bill") ValueError: Could not interpret value `Bill` for `x`. An entry with this name does not appear in `data`. column names are case sensitive x="bill" (check df.columns)
sns.relplot(..., ax=ax) UserWarning: relplot is a figure-level function and does not accept the `ax` parameter. You may wish to try scatterplot figure-level functions build their own figure scatterplot(ax=ax) or relplot(col=...)
reading barplot bars as totals no error; bars are means default estimator is the mean estimator="sum"
box plot of two-humped data no error; a "typical" value nobody pays 5 numbers can't show shape violinplot or kdeplot
KDE of bills going below 0 no error; impossible values drawn smoothing spills past the data cut=0, compare with a histogram
wide data (one column per stall) odd charts or errors seaborn expects tidy/long data df.melt(...) to long form
calling a seaborn function after another without a new figure charts drawn on top of each other axes-level functions use the current Axes fig, ax = plt.subplots() and ax=ax

Practice

1. 300 made-up expenses in three categories. Draw a KDE per category that doesn't spill below 0, and print each category's median.

Solution
import sys; sys.tracebacklimit = 0
import numpy as np, pandas as pd
import matplotlib.pyplot as plt, seaborn as sns
rng = np.random.default_rng(5)
spend = pd.DataFrame({"category": rng.choice(["Food", "Travel", "Fun"], 300),
                      "amount": rng.gamma(3, 80, 300).round()})
ax = sns.kdeplot(data=spend, x="amount", hue="category", cut=0)
ax.figure.savefig("p1.png")
print(spend.groupby("category")["amount"].median())
category
Food      228.0
Fun       242.0
Travel    227.0
Name: amount, dtype: float64

2. Draw the default barplot of amount by category next to one with estimator="sum" and no error bars. Explain the difference.

Solution
fig, axs = plt.subplots(1, 2, figsize=(10, 4))
sns.barplot(data=spend, x="category", y="amount", ax=axs[0])
sns.barplot(data=spend, x="category", y="amount", estimator="sum", errorbar=None, ax=axs[1])
fig.savefig("p2.png")
print(spend.groupby("category")["amount"].agg(["mean", "sum"]).round(1))
           mean      sum
category                
Food      247.6  25501.0
Fun       253.7  26128.0
Travel    240.3  22589.0

The left bars are means (about 240-254) with 95% CIs; the right bars are totals (22,589 to 26,128). Totals also depend on how many expenses each category has.

3. What y values does this lineplot draw?

tips = pd.DataFrame({"x": [1, 1, 2, 2], "y": [10, 30, 20, 40]})
fig, ax = plt.subplots()
sns.lineplot(data=tips, x="x", y="y", errorbar=None, ax=ax)
print(ax.lines[0].get_ydata().tolist())
Solution
[20.0, 30.0]

x = 1 appears twice (10 and 30), so lineplot draws their mean, 20; x = 2 → (20 + 40) / 2 = 30.

4. Make a catplot of box plots of bill by stall, split into columns by pay. How many panels do you get?

Solution

g = sns.catplot(data=df, x="stall", y="bill", col="pay", kind="box") gives one panel per payment method: 3 panels (g.axes.shape is (1, 3)).

5. Which seaborn chart would you use to check whether two humps hide inside a group, and why not a box plot?

Solution

A violinplot (or kdeplot / histplot): they show the shape. A box plot shows only the median, quartiles and whiskers, so two humps look like one tall box.

Quick quiz

df = pd.DataFrame({"stall": ["Pune", "Pune", "Pune"],
                   "bill": [100, 200, 600]})
sns.barplot(data=df, x="stall", y="bill")

How tall is Pune's bar? A. 900 B. 300 C. 200 D. 600

Answer

B. 300. barplot's default estimator is the mean: (100 + 200 + 600) / 3 = 300 (checked: ax.patches[0].get_height() prints 300.0). estimator="sum" would give 900; 200 is the median.

Interview questions

  1. seaborn vs matplotlib? seaborn is built on matplotlib; it works from tidy DataFrames, handles grouping (hue), legends and statistics, and returns matplotlib objects you can customise.
  2. What does hue do? Splits the data by a column and colours each group, adding a legend.
  3. What is a KDE? A smooth estimate of a distribution made by summing a small kernel (bump) on every data point; its smoothness is set by the bandwidth.
  4. Box plot vs violin plot? The violin also shows the shape (e.g. bimodal data) via a mirrored KDE.
  5. What does sns.barplot show by default? The mean of each group with a 95% confidence interval computed by bootstrapping.
  6. What is bootstrapping? Resampling the data with replacement many times to see how much a statistic varies.
  7. What does lineplot do with repeated x values? Averages y per x and draws a confidence band.
  8. Axes-level vs figure-level functions? Axes-level draw on one Axes (ax=); figure-level (relplot, displot, catplot) create a FacetGrid and facet with col/row.
  9. When would you use pairplot? For a quick first look at relationships among several numeric columns.
  10. How do you make all charts colour-blind friendly? sns.set_theme(palette="colorblind").

Glossary

Term Meaning Example
seaborn (sns) Statistical plotting library built on matplotlib import seaborn as sns
Tidy / long-form data One row per observation, one column per variable one row per order
data= The DataFrame to plot data=df
x=, y= Column names for the axes x="bill"
hue= Column that colours and splits the groups hue="stall"
histplot seaborn histogram sns.histplot(data=df, x="bill")
Kernel A small smooth bump placed on each value one pile of sand
Kernel density estimate (KDE) Smooth curve from summing kernels; estimates a distribution sns.kdeplot(...)
Density Height of a KDE; how packed values are y axis of kde.png
Bimodal A distribution with two peaks Mumbai bills
Bandwidth (bw_adjust) How wide each kernel is (smoothness) bw_adjust=0.5
cut=0 Stop the KDE at the data's min and max no bills below 0
common_norm Whether all hue groups share total area 1 common_norm=False
Violin plot Mirrored KDE per group, with a mini box plot inside sns.violinplot(...)
countplot Bars of row counts per category sns.countplot(x="pay")
barplot Bars of an estimate (default mean) per group, with error bars sns.barplot(x="stall", y="bill")
Estimator The statistic a bar shows estimator="sum"
Error bar A line showing uncertainty or spread black line on a bar
Sample The rows we actually have from a bigger population 600 orders
Confidence interval (CI) A range likely to contain the true value 95% CI of the mean
Bootstrapping Resampling with replacement many times to estimate uncertainty 1,000 resamples
Resample (with replacement) Draw rows again, allowing repeats bootstrap sample
Standard deviation A measure of spread (statistics episodes) errorbar="sd"
scatterplot seaborn scatter with hue/size/style sns.scatterplot(...)
lineplot Line of the mean y per x, with a CI band sns.lineplot(x="mins", y="rating")
Confidence band Shaded CI around a line lineplot.png
pairplot Scatter of every pair of columns, distributions on the diagonal sns.pairplot(df, vars=[...])
PairGrid Object returned by pairplot g.savefig(...)
crosstab Counts of each combination of two columns pd.crosstab(df["stall"], df["pay"])
Contingency table A table of counts for two categories stall × payment
heatmap (seaborn) Coloured grid from a 2-D table sns.heatmap(table, annot=True)
annot / fmt Write values in cells / their format annot=True, fmt="d"
Axes-level function Draws on one Axes; accepts ax= histplot
Figure-level function Builds its own figure and facets relplot, displot, catplot
relplot Figure-level scatter/line plots sns.relplot(..., col="stall")
displot Figure-level distribution plots sns.displot(kind="kde")
catplot Figure-level category plots sns.catplot(kind="violin")
Facet One subset of the data in its own panel the Pune panel
FacetGrid Grid of facets; returned by figure-level functions sns.FacetGrid(df, row=, col=)
map_dataframe Runs a plot function on each facet g.map_dataframe(sns.histplot, x="bill")
col= / row= Column / row to split panels by col="stall"
Theme Global look for all charts sns.set_theme(style="whitegrid")
Palette The set of colours used for groups palette="colorblind"
UserWarning A warning: the program continues relplot with ax=

Summary

  • seaborn plots tidy DataFrames with data=, x=, y=, hue= and returns matplotlib objects.
  • histplot / kdeplot: a KDE is a smooth histogram made of kernels; watch cut and bw_adjust.
  • Box plots hide shape; violin plots show it (Mumbai's two humps).
  • barplot = mean + 95% CI (bootstrap), not a total; countplot counts rows; lineplot averages per x with a band.
  • pairplot for a first look; heatmap(annot=True) for a 2-D table.
  • Figure-level relplot, displot, catplot and FacetGrid make small multiples with col=/row= and don't accept ax=.
  • sns.set_theme(style=..., palette="colorblind") once at the top.
  • Next episode: descriptive statistics 1: averages (mean, median, mode and when each one lies).