TExcelTAD
Home › NumPy › Seaborn Module

Seaborn Module

Seaborn is a plotting library built on top of Matplotlib. It specialises in statistical charts: with one function call you get a histogram, a smooth density curve or a box plot, with sensible styling. Its main job in a NumPy course is to help you see the shape of random data.

Installing and importing

On your computer, install it with pip:

bash
pip install seaborn

The usual imports are:

python
import matplotlib.pyplot as plt
import seaborn as sns

sns is the conventional alias. Seaborn draws on Matplotlib figures, so you still call plt.show() to display the chart.

Note: In this course the seaborn calls are shown as code to try on your own machine, and each one is followed by a runnable Matplotlib twin that draws the same kind of chart. Knowing both is useful: seaborn is quicker to write, Matplotlib shows what is happening underneath and lets you control every detail.

Histograms: sns.histplot

A histogram sorts values into bins (ranges) and draws one bar per bin; the bar height is how many values fell into that range. With seaborn:

python
sns.histplot(scores, bins=20)

The runnable twin uses plt.hist, which does the same counting:

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt

rng = np.random.default_rng(10)
scores = rng.normal(loc=68, scale=10, size=500)    # 500 simulated exam scores

plt.figure(figsize=(6, 3.5))
plt.hist(scores, bins=20, color="#4dabcf", edgecolor="white")
plt.xlabel("exam score")
plt.ylabel("count")
plt.title("500 simulated exam scores")
plt.tight_layout()
plt.show()
print(f"Histogram of {scores.size} scores, mean {scores.mean():.1f}")
Histogram of 500 scores, mean 66.9

You can also compute the bin counts yourself with NumPy, which is what both libraries do internally:

python · try it yourself
import numpy as np

rng = np.random.default_rng(10)
scores = rng.normal(loc=68, scale=10, size=500)
counts, edges = np.histogram(scores, bins=[30, 50, 60, 70, 80, 90, 110])
for lo, hi, c in zip(edges[:-1], edges[1:], counts):
    print(f"{lo:>3.0f}-{hi:<3.0f} {'#' * (c // 5)} {c}")
 30-50  #### 23
 50-60  ################### 95
 60-70  ####################################### 196
 70-80  ############################ 141
 80-90  ######## 42
 90-110  3

Smooth curves: KDE

A KDE (kernel density estimate) is a smoothed curve that estimates the underlying probability density: imagine placing a small bell curve on every data point and adding them all up. In seaborn you draw it with kdeplot, or on top of a histogram with kde=True:

python
sns.histplot(scores, kde=True, stat="density")
sns.kdeplot(scores, fill=True)

Matplotlib has no KDE function of its own, but SciPy's gaussian_kde computes the curve, and we plot it as a line:

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import gaussian_kde

rng = np.random.default_rng(10)
scores = rng.normal(loc=68, scale=10, size=500)
xs = np.linspace(30, 105, 300)
density = gaussian_kde(scores)(xs)

fig, axes = plt.subplots(1, 2, figsize=(8, 3.2))
axes[0].hist(scores, bins=20, density=True, color="#4dabcf", edgecolor="white")
axes[0].plot(xs, density, color="black")
axes[0].set_title("histogram + KDE")
axes[1].fill_between(xs, density, color="#e07a5f", alpha=0.5)
axes[1].plot(xs, density, color="#e07a5f")
axes[1].set_title("KDE only")
plt.tight_layout()
plt.show()
print(f"KDE peak near score {xs[density.argmax()]:.0f}")
KDE peak near score 67

With density=True (seaborn: stat="density") the bar heights are scaled so the total area is 1, which makes the histogram comparable to a density curve.

Comparing several samples

Seaborn accepts a dictionary (or a pandas DataFrame) and colours each sample automatically, adding a legend:

python
sns.kdeplot({"class A": a, "class B": b}, fill=True)

The Matplotlib twin loops over the dictionary:

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import gaussian_kde

rng = np.random.default_rng(4)
groups = {
    "class A": rng.normal(65, 8, 400),
    "class B": rng.normal(75, 5, 400),
}

xs = np.linspace(35, 100, 300)
plt.figure(figsize=(6, 3.5))
for (name, values), color in zip(groups.items(), ["#4dabcf", "#e07a5f"]):
    d = gaussian_kde(values)(xs)
    plt.fill_between(xs, d, alpha=0.3, color=color)
    plt.plot(xs, d, color=color, label=name)
plt.xlabel("score")
plt.legend()
plt.tight_layout()
plt.show()
for name, values in groups.items():
    print(f"{name}: mean {values.mean():.1f}, std {values.std():.1f}")
class A: mean 65.3, std 8.1
class B: mean 74.8, std 5.1

Class B has the higher mean and the narrower curve (smaller standard deviation), and the plot makes that obvious instantly.

About distplot

Older tutorials use sns.distplot(). That function is deprecated (it prints a warning and will be removed). Use its replacements:

Old New
sns.distplot(x) sns.histplot(x, kde=True, stat="density")
sns.distplot(x, hist=False) sns.kdeplot(x)
figure-level version sns.displot(x, kind="hist") or kind="kde"

Tip: Seaborn understands pandas DataFrames natively: sns.histplot(data=df, x="height", hue="sex") plots one coloured histogram per group. You will use that style a lot when you work with pandas.

Test yourself

What is the conventional alias for seaborn?

  1. sb
  2. sea
  3. sns
  4. snb

Which seaborn call draws a histogram with a smooth density curve on top?

  1. sns.kdeplot(x, hist=True)
  2. sns.histplot(x, kde=True)
  3. plt.hist(x, kde=True)
  4. sns.barplot(x)

Why should you avoid sns.distplot in new code?

  1. It is very slow
  2. It is deprecated in favour of histplot / kdeplot / displot
  3. It only works with pandas
  4. It cannot plot NumPy arrays