A kernel density estimate is a smooth histogram. sns.kdeplot is useful when you care about shape more than exact counts.
Goal
Draw a density curve, overlay two cities, and fill the area.
One curve
rng = np.random.default_rng(0)
df = pd.DataFrame({"units": rng.normal(10, 3, size=80)})
sns.kdeplot(data=df, x="units")
plt.title("Units density")
plt.show()Hue
rng = np.random.default_rng(0)
df = pd.DataFrame(
{
"city": ["Nairobi"] * 50 + ["Mombasa"] * 50,
"units": np.concatenate(
[rng.normal(8, 2.2, size=50), rng.normal(14, 2.8, size=50)]
),
}
)
sns.kdeplot(data=df, x="units", hue="city", fill=True, alpha=0.4)
plt.title("Two cities")
plt.show()Two dimensions
rng = np.random.default_rng(0)
n = 80
df = pd.DataFrame(
{
"units": rng.integers(1, 20, size=n),
"price": rng.choice([10.5, 22.0], size=n),
}
)
df["revenue"] = df["units"] * df["price"] + rng.normal(0, 10, size=n)
sns.kdeplot(data=df, x="units", y="revenue", fill=True, cmap="Blues")
plt.title("2-D density")
plt.show()A 2-D KDE is a smooth heatmap of where points pile up.
Pitfall
KDE needs more than a handful of rows. With 12 sales rows the curve is mostly guesswork — use a strip or box plot instead, or generate a larger sample as in this chapter.