Plot guides › Chart types

Density plot (KDE)

A kernel density estimate (KDE) replaces a histogram's bars with a smooth curve, which makes it easier to overlay several distributions without the bars hiding each other.

Example density plot (kde) made with matplotlib
Rendered from the code below, with example data.

When to use it

Watch out: A KDE can suggest values outside the possible range (below zero, above 100%). Check the tails.

Ask for it in pltchat

Upload your file and type something like:

"density curves of exam score for each class, filled with transparency"

pltchat writes the loader and the plot for your columns, runs it in your browser and shows you the code.

The matplotlib code

Self-contained with example data; swap in pd.read_csv(...) or pd.read_excel(...) for your own file.

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

rng = np.random.default_rng(7)
df = pd.DataFrame({"A": rng.normal(68, 9, 300),
                   "B": rng.normal(74, 6, 300),
                   "C": np.r_[rng.normal(60, 5, 150), rng.normal(82, 5, 150)]})

fig, ax = plt.subplots(figsize=(6.4, 4))
xs = np.linspace(30, 105, 300)
for col in df.columns:
    vals = df[col].to_numpy()
    bw = 1.06 * vals.std() * len(vals) ** -0.2          # Silverman's rule
    dens = np.exp(-0.5 * ((xs[:, None] - vals) / bw) ** 2).sum(1)
    dens /= len(vals) * bw * np.sqrt(2 * np.pi)
    ax.plot(xs, dens, label=f"Class {col}")
    ax.fill_between(xs, dens, alpha=0.2)
ax.set_xlabel("Exam score")
ax.set_ylabel("Density")
ax.legend()
plt.tight_layout()
plt.show()

Make this with your data

Upload a CSV, Excel, JSON or Parquet file. Your first plot is always free.

Related plots