Python Charts

Python plotting and visualization demystified

Seaborn Histograms with histplot and displot

Make histograms in Seaborn with sns.histplot and sns.displot: set bins and binwidth, compare groups with hue and multiple, normalize with stat, add a KDE, and facet by column.

To make a histogram in Seaborn, use sns.histplot(data=df, x="column"). Set the bin size with binwidth= (or the number of bins with bins=), add a smoothed density curve with kde=True, and split by group with hue=. sns.displot() draws the same histogram as a figure-level plot, so it can also facet into subplots with col= and row=. The old sns.distplot() is deprecated and slated for removal in Seaborn 0.14, so use these two instead.

Quick Example

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

# Sample data: 1,000 commute times by travel mode and city
rng = np.random.default_rng(11)
modes = np.repeat(["Car", "Transit", "Bike"], [500, 350, 150])
minutes = np.concatenate([
    rng.gamma(shape=6, scale=4.5, size=500),   # car: right-skewed
    rng.normal(40, 9, size=350),              # transit
    rng.normal(22, 5, size=150),              # bike
]).clip(3).round(1)
commutes = pd.DataFrame({
    "mode": modes,
    "minutes": minutes,
    "city": rng.choice(["Seattle", "Denver"], size=1000),
})

sns.set_theme(style="whitegrid")
fig, ax = plt.subplots(figsize=(8, 4.8))
sns.histplot(data=commutes, x="minutes", binwidth=5, kde=True, color="#0d9488", ax=ax)
ax.set(xlabel="Commute time (minutes)", ylabel="Commuters",
       title="Distribution of 1,000 commute times")

Seaborn histogram of 1,000 commute times in 5-minute bins with a KDE curve, peaking around 25 to 30 minutes with a second bump near 40 minutes

Each bar counts the commutes in a 5-minute window. The KDE line shows two peaks: one around 25–30 minutes and a smaller one near 40, which is a hint that the data mixes groups. We'll split it by mode below. The code targets Seaborn 0.13.

Set the Number of Bins or the Bin Width

bins sets how many bins to use. binwidth sets how wide each bin is, which is usually easier to reason about because the bin edges land on round numbers. Add binrange=(low, high) to fix where the bins start and stop.

sns.histplot(data=commutes, x="minutes", bins=8)
sns.histplot(data=commutes, x="minutes", bins=60)
sns.histplot(data=commutes, x="minutes", binwidth=5, binrange=(0, 75))

Three Seaborn histograms of the same commute data: 8 bins hides the shape, 60 bins is noisy, and a 5-minute binwidth shows the distribution clearly

With 8 bins the second peak disappears, and with 60 the chart is mostly noise. A 5-minute binwidth shows the shape and gives bins people can read ("20 to 25 minutes"). The default, bins="auto", picks a count with NumPy's rules and is a decent starting point.

For integer data like counts or ratings, pass discrete=True. It centers one bar on each integer, so you don't get gaps or bars that straddle two values.

Compare Groups with hue and multiple

Pass a column to hue to draw one histogram per group. multiple controls how the groups share the space:

mode_colors = {"Car": "#64748b", "Transit": "#0d9488", "Bike": "#f97316"}

sns.histplot(data=commutes, x="minutes", hue="mode", multiple="stack",
             binwidth=5, binrange=(0, 75), palette=mode_colors)

Four Seaborn histograms of commute time by mode (car, transit, bike) using multiple set to layer, stack, dodge, and fill

  • "layer" (the default) overlaps semi-transparent histograms. It works for two groups and gets muddy with more.
  • "stack" stacks the groups, so the bar tops still show the overall distribution.
  • "dodge" puts the groups side by side in each bin. Use shrink=0.8 to add gaps between bins.
  • "fill" stretches every bin to 1, showing each group's share of that bin. In this data, bikes make up a quarter to a third of 15–30 minute commutes, while transit is about two-thirds of everything past 35 minutes.

Use hue_order=["Bike", "Car", "Transit"] to control the stacking and legend order. If the legend is in the way, sns.move_legend() can move it outside or above the plot. See How to Move the Legend in Seaborn.

Show Percent, Proportion, or Density with stat

By default the y-axis is a count. stat changes what the bars measure:

stat Bar height Use it for
"count" Number of observations The default
"frequency" Count divided by bin width Comparing histograms with different bin widths
"probability" or "proportion" Bar heights sum to 1 Share of observations
"percent" Bar heights sum to 100 Same, easier to read
"density" Total area is 1 Overlaying a probability density

Once you normalize with hue, common_norm matters. With the default common_norm=True, every group is normalized by the total across all groups, so a small group gets small bars. With common_norm=False, each group sums to 100% on its own, which is what you want for comparing shapes:

sns.histplot(data=commutes, x="minutes", hue="mode", stat="percent",
             common_norm=False, element="step", binwidth=5, binrange=(0, 75),
             palette=mode_colors)

Two step histograms of commute time percent by mode: with common_norm True the bike group looks small, with common_norm False each mode sums to 100 percent and the bike distribution is tall and narrow

On the left, the 150 bike commutes are barely visible next to 500 car commutes. On the right, each mode is normalized separately, and it's clear that bike commutes cluster tightly between 15 and 30 minutes. element="step" draws outlines instead of bars, which keeps overlapping groups readable. element="poly" draws a frequency polygon.

Add a KDE Curve, Log Scale, or Cumulative Histogram

A few more one-argument changes:

sns.histplot(data=commutes, x="minutes", kde=True, kde_kws={"bw_adjust": 0.7})
sns.histplot(data=commutes, x="minutes", log_scale=True)       # log-spaced bins
sns.histplot(data=commutes, x="minutes", cumulative=True, stat="percent",
             element="step", fill=False)                         # running total
  • kde=True overlays a kernel density estimate. kde_kws={"bw_adjust": ...} makes it smoother (above 1) or more detailed (below 1).
  • log_scale=True puts the x-axis on a log scale and spaces the bins evenly on that scale. This is the right way to histogram skewed data like incomes or file sizes. Setting ax.set_xscale("log") afterwards doesn't re-bin.
  • cumulative=True turns the histogram into a running total. For a smooth version, sns.ecdfplot() is usually better. See Plot a Cumulative Distribution Function (CDF) in Python.

Facet into Subplots with displot

sns.displot() takes all the same arguments as histplot, plus col, row, and col_wrap to draw one panel per group. It creates its own figure, so you set the size with height and aspect instead of figsize:

g = sns.displot(data=commutes, x="minutes", hue="mode", col="city",
                multiple="stack", binwidth=5, binrange=(0, 75),
                palette=mode_colors, height=3.8, aspect=1.25)
g.set_axis_labels("Commute time (minutes)", "Commuters")
g.set_titles("{col_name}")

Seaborn displot with two side-by-side stacked histograms of commute time by mode, one for Denver and one for Seattle, with a shared legend on the right

Each city gets its own stacked histogram with shared axes and a single legend. displot can also draw other distribution plots with kind="kde" or kind="ecdf".

histplot vs displot vs distplot

Function Level Faceting Use it when
sns.histplot() Axes-level (accepts ax=) No You're placing the histogram in your own plt.subplots() layout
sns.displot() Figure-level (returns a FacetGrid) col=, row= You want small multiples or a quick standalone figure
sns.distplot() Deprecated No Never in new code. It warns in 0.13 and is scheduled for removal

To resize figure-level plots, see Adjust Aspect Ratio and Figure Size in a Seaborn catplot. The same height/aspect rules apply to displot.

Make a 2D Histogram

Pass both x and y to bin into a grid and color each cell by its count. This is the histogram equivalent of a scatter plot and is good when points overlap heavily:

commutes["distance_km"] = (
    commutes["minutes"] * commutes["mode"].map({"Car": 0.55, "Transit": 0.35, "Bike": 0.25})
    + rng.normal(0, 2, 1000)
).clip(0.5).round(1)

sns.histplot(data=commutes, x="distance_km", y="minutes", binwidth=(2, 5),
             cmap="mako_r", cbar=True, cbar_kws={"label": "Commuters"})

Seaborn 2D histogram of commute distance versus commute time with a colorbar showing the number of commuters in each cell

binwidth=(2, 5) sets 2 km by 5 minute cells. Darker cells hold more commuters. Commute time rises with distance, and the busiest cells sit around 12–16 km and 30–40 minutes. For marginal histograms on the sides, use sns.jointplot(..., kind="hist"), covered in How to Plot Bivariate Distributions (jointplot) in Seaborn.

Practical Tips

  • Start with binwidth in a unit that means something (5 minutes, $10k, 1 year) rather than a bin count.
  • When comparing groups of different sizes, use stat="percent" (or "density") with common_norm=False.
  • Prefer element="step" or multiple="stack" over the default layered bars once you have three or more groups.
  • Use log_scale=True for long-tailed data instead of changing the axis afterwards.
  • If you want full control with plain Matplotlib, see Histograms in Matplotlib.

Similar Topics