Seaborn kdeplot: Density Plots in Python

Draw density plots with sns.kdeplot: fill the curves, compare groups, control smoothing with bw_adjust, keep curves from going below zero, and plot a 2D KDE.

sns.kdeplot(data=df, x="column") draws a density plot: a smooth curve estimating how a numeric variable is distributed. Add hue= to compare groups, fill=True to shade under the curves, and bw_adjust= to make them smoother or more detailed.

Quick Example

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

# Sample data: delivery times for two couriers
rng = np.random.default_rng(61)
orders = pd.DataFrame({
    "courier": np.repeat(["Bike", "Van"], [450, 300]),
    "minutes": np.concatenate([
        rng.gamma(shape=4, scale=5, size=450),
        rng.normal(41, 9, size=300),
    ]).round(1),
})
orders["km"] = (orders["minutes"] * np.where(orders["courier"] == "Bike", 0.16, 0.27)
                + rng.normal(0, 1.1, len(orders))).clip(0.3).round(2)
colors = {"Bike": "#7c3aed", "Van": "#ea580c"}

sns.set_theme(style="white")
fig, ax = plt.subplots(figsize=(8, 4.6))
sns.kdeplot(data=orders, x="minutes", hue="courier", palette=colors,
            fill=True, alpha=0.35, linewidth=2, cut=0, ax=ax)
ax.set(title="Delivery time by courier", xlabel="Minutes", ylabel="Density")
sns.despine()
plt.show()

Seaborn density plot of delivery times, with a purple bike curve peaking near 15 minutes and a lower orange van curve peaking near 44 minutes

Bike deliveries peak around 15 minutes and have a long right tail. Van deliveries peak near 44 minutes. The code targets Seaborn 0.13, where fill=True replaces the deprecated shade=True.

What Does the Density Axis Mean?

The y-axis is probability density. The area under the curve between two x values estimates the share of observations in that range, so the height itself isn't a count or a percentage.

With hue, the default common_norm=True scales each curve by its group size, and the areas add up to 1 together. The bike curve above covers 60% of the total area because bikes made 450 of the 750 deliveries. Set common_norm=False to give every group an area of 1 and compare shapes alone.

fig, axes = plt.subplots(1, 2, figsize=(11, 3.8), sharey=True)
for ax, common in zip(axes, [True, False]):
    sns.kdeplot(data=orders, x="minutes", hue="courier", palette=colors,
                common_norm=common, linewidth=2, cut=0, ax=ax)
    ax.set_title(f"common_norm={common}")
sns.despine()
plt.show()

Two density plots of the same data: with common_norm True the smaller van group has a lower curve, and with False the van curve rises

If you want counts on the y-axis, use a histogram: sns.histplot(..., kde=True) draws the bars and the curve together.

Control the Smoothing with bw_adjust

A kernel density estimate places a small bell curve on every observation and adds them up. The bandwidth sets how wide those bells are. bw_adjust multiplies the automatic bandwidth: below 1 follows the data more closely, above 1 smooths more.

bike = orders[orders["courier"] == "Bike"]

fig, axes = plt.subplots(1, 3, figsize=(11, 3.4), sharey=True)
for ax, bw in zip(axes, [0.25, 1, 3]):
    sns.histplot(data=bike, x="minutes", stat="density", binwidth=2,
                 color="#ddd6fe", edgecolor="white", ax=ax)
    sns.kdeplot(data=bike, x="minutes", bw_adjust=bw, color="#5b21b6",
                linewidth=2, cut=0, ax=ax)
    ax.set_title(f"bw_adjust={bw}")
sns.despine()
plt.show()

Three density curves over the same bike histogram: bw_adjust 0.25 is jagged, 1 follows the shape, and 3 is too wide and flat

At 0.25 the curve chases noise. At 3 it flattens the peak and spreads it out. Check a histogram before you settle on a value. bw_method changes the rule that picks the base bandwidth ("scott" by default, or "silverman", or a number).

Stop the Density Curve Going Below Zero

The curve extends past the smallest and largest observations by default (cut=3 bandwidths), so a delivery time can appear to be negative. Two parameters limit it:

  • cut=0 ends the curve at the data minimum and maximum.
  • clip=(0, None) sets hard limits, here "nothing below zero".
fig, axes = plt.subplots(1, 3, figsize=(11, 3.4), sharey=True)
options = {"default (cut=3)": {}, "cut=0": {"cut": 0}, "clip=(0, None)": {"clip": (0, None)}}
for ax, (title, kwargs) in zip(axes, options.items()):
    sns.kdeplot(data=bike, x="minutes", fill=True, color="#7c3aed", ax=ax, **kwargs)
    ax.axvline(0, color="#111827", linewidth=1, linestyle="--")
    ax.set(title=title, xlim=(-10, 70))
sns.despine()
plt.show()

Three bike delivery density curves: the default extends left of zero, cut=0 stops at the data limits, and clip stops at zero

Both only change where the curve is drawn. The estimate near a hard boundary is still pulled down, because part of each bell falls on the impossible side. For strictly positive, skewed data, log_scale=True estimates the density in log space, which never reaches zero:

fig, ax = plt.subplots(figsize=(8, 4))
sns.kdeplot(data=orders, x="minutes", hue="courier", palette=colors,
            log_scale=True, fill=True, ax=ax)
ax.set(xlabel="Minutes (log scale)")
sns.despine()
plt.show()

Density plot of delivery times on a logarithmic x-axis, where the long right tail of the bike distribution disappears

Stack or Fill Groups

multiple="stack" piles the curves so the top edge shows all deliveries. multiple="fill" shows each group's share at every x value.

fig, axes = plt.subplots(1, 2, figsize=(11, 3.8))
for ax, mode in zip(axes, ["stack", "fill"]):
    sns.kdeplot(data=orders, x="minutes", hue="courier", palette=colors,
                multiple=mode, cut=0, clip=(5, 55), ax=ax)
    ax.set_title(f'multiple="{mode}"')
sns.despine()
plt.show()

Stacked density plot beside a filled density plot showing the van share of deliveries rising as delivery time increases

Shares computed from very few observations are unreliable, which is why this example clips to 5–55 minutes.

Cumulative Density

cumulative=True plots the share of observations at or below each value. Pair it with common_norm=False so each group climbs to 1.

fig, ax = plt.subplots(figsize=(8, 4))
sns.kdeplot(data=orders, x="minutes", hue="courier", palette=colors,
            cumulative=True, common_norm=False, linewidth=2, ax=ax)
ax.axhline(0.5, color="#9ca3af", linestyle=":")
ax.set(xlabel="Minutes", ylabel="Share delivered within", xlim=(0, None))
sns.despine()
plt.show()

Cumulative density curves showing bike deliveries reaching half of orders much sooner than van deliveries

For exact shares with no smoothing, use sns.ecdfplot() with the same arguments.

2D KDE Plot

Pass both x and y to estimate a joint density, drawn as contours.

fig, ax = plt.subplots(figsize=(8, 5.5))
sns.kdeplot(data=orders, x="minutes", y="km", fill=True, cmap="mako_r",
            levels=8, thresh=0.05, clip=((0, None), (0, None)),
            cbar=True, ax=ax)
ax.set(title="Where deliveries concentrate", xlabel="Minutes", ylabel="Distance (km)",
       xlim=(0, 80), ylim=(0, 22))
plt.show()

Filled 2D density contours of delivery minutes against distance, with a dense dark region for short bike trips and a second region for longer van trips

For 2D data, clip takes one pair of limits per axis, which keeps the contours out of negative distances. levels sets the number of contour bands. Each level marks a share of the probability mass, and thresh=0.05 leaves the outermost 5% unshaded. With hue, drop fill so the contour lines of each group stay readable:

fig, ax = plt.subplots(figsize=(8, 5.5))
sns.scatterplot(data=orders, x="minutes", y="km", hue="courier", palette=colors,
                s=10, alpha=0.35, legend=False, ax=ax)
sns.kdeplot(data=orders, x="minutes", y="km", hue="courier", palette=colors,
            levels=5, linewidths=1.8, clip=((0, None), (0, None)), ax=ax)
ax.set(xlabel="Minutes", ylabel="Distance (km)", xlim=(0, 80), ylim=(0, 22))
sns.despine()
plt.show()

Scatter plot of distance against minutes with purple and orange density contour lines around the bike and van clusters

To add marginal distributions around a 2D plot, use jointplot(kind="kde").

kdeplot vs histplot vs violinplot

Plot Use it when
kdeplot Comparing the shapes of a few overlapping groups
histplot You need counts, have little data, or have hard edges and spikes
ecdfplot You need exact shares and percentiles
violinplot Comparing many categories side by side
displot(kind="kde") One density panel per category with col=

A group where every value is identical has no density to estimate. Seaborn warns and skips it.

Similar Topics