Kernel Density Estimation (KDE)
What is KDE?
Section titled “What is KDE?”A Kernel Density Estimate (KDE) is a smooth curve that approximates the probability density of a continuous variable.
Think of it as a “smoothed histogram”.
flowchart LR A["Data points"] --> B["Place a small
bump (kernel) at each point"] B --> C["Add all the bumps
together"] C --> D["One smooth curve
(the KDE)"]
KDE plot
Section titled “KDE plot”import seaborn as sns
import matplotlib.pyplot as plt
values = [55, 60, 62, 63, 65, 67, 70, 72, 76, 80, 81, 85, 90, 92, 95]
plt.figure(figsize=(7, 4))
sns.kdeplot(values, fill=True)
plt.title("KDE plot")
plt.xlabel("Value")
plt.tight_layout()
plt.show()Visualize it
Section titled “Visualize it”Each dot on the axis drops a small bump (its own mini bell curve). Stacking every bump together produces the single smooth KDE line:
Compare KDE across groups
Section titled “Compare KDE across groups”import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset("tips")
plt.figure(figsize=(7, 4))
sns.kdeplot(data=tips, x="total_bill", hue="sex", fill=True, common_norm=False)
plt.title("KDE of total_bill by sex")
plt.tight_layout()
plt.show()Bandwidth matters
Section titled “Bandwidth matters”The “bandwidth” controls smoothing:
- Too small → noisy curve
- Too large → over-smoothed curve
Seaborn chooses a default automatically, but you can tune it.
import seaborn as sns
import matplotlib.pyplot as plt
plt.figure(figsize=(7, 4))
sns.kdeplot(values, bw_adjust=0.6, label="less smooth")
sns.kdeplot(values, bw_adjust=1.6, label="more smooth")
plt.legend()
plt.title("KDE bandwidth effects")
plt.tight_layout()
plt.show()Continue to Box Plots and Whiskers to compare distributions using quartiles instead of a smooth curve.
🧪 Try It Yourself
Section titled “🧪 Try It Yourself”Exercise 1 – Draw a Filled KDE
Section titled “Exercise 1 – Draw a Filled KDE”Exercise 2 – Compare Normalization With common_norm
Section titled “Exercise 2 – Compare Normalization With common_norm”Exercise 3 – Adjust the Bandwidth
Section titled “Exercise 3 – Adjust the Bandwidth”pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading