Module 2 · Beginner · Matplotlib basics

Histograms with Matplotlib

Histograms in Matplotlib: show how values are spread, choose the number of bins, compare groups, density and cumulative histograms, and read skew and peaks.

By theprogrammers team · · 6 min read

A histogram shows how the values of one numeric variable are spread out. It splits the range of values into intervals called bins, counts how many values fall into each, and draws a bar for each count. In one picture you see where most values sit, how spread out they are, whether there's a long tail on one side, whether there are two peaks, and whether any values are far from the rest.

Histograms are the first chart to draw for any numeric column in exploratory data analysis and before training a model. This lesson shows how to make them, how to choose bins, how to compare groups, and how to read the shapes you'll see.

A basic histogram

We'll use Seaborn's tips dataset: 244 restaurant bills with their tips, which downloads automatically the first time.

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

tips = sns.load_dataset("tips")

fig, ax = plt.subplots()
ax.hist(tips["total_bill"], bins=20, edgecolor="white")
ax.set_title("Distribution of restaurant bills")
ax.set_xlabel("Total bill ($)")
ax.set_ylabel("Number of bills")
plt.show()
A histogram of 244 restaurant bills with most between 10 and 25 dollars, a peak around 15, and a long tail stretching to about 50 dollars on the right.

Most bills are between about $10 and $25, with a long tail of bigger bills to the right. edgecolor="white" separates the bars so individual bins are easy to see.

Unlike a bar chart, the x-axis is a continuous number line split into ranges, so the bars touch.

Choosing the number of bins

The number of bins changes the picture a lot:

fig, axes = plt.subplots(1, 3, figsize=(12, 3.5))
for ax, bins in zip(axes, [5, 20, 100]):
    ax.hist(tips["total_bill"], bins=bins, edgecolor="white")
    ax.set_title(f"{bins} bins")
fig.tight_layout()
plt.show()
The same bills drawn three ways: with 5 bins the shape is a blocky staircase; with 20 bins the peak and right tail are clear; with 100 bins the chart is spiky and noisy.
  • Too few bins hide the shape.
  • Too many bins show random noise, with gaps and spikes.
  • About 10 to 30 works for a few hundred values. Try two or three settings: the shape that stays the same across them is real.

You can also let NumPy choose with bins="auto", or set exact edges, such as bins=range(0, 55, 5) for $5-wide bins starting at zero. Round, meaningful edges make a chart easier to read.

Reading histogram shapes

rng = np.random.default_rng(3)
shapes = {
    "Symmetric (normal)": rng.normal(50, 10, 2000),
    "Right-skewed": rng.exponential(10, 2000),
    "Two peaks (bimodal)": np.concatenate([rng.normal(30, 5, 1000),
                                           rng.normal(60, 6, 1000)]),
    "Uniform": rng.uniform(0, 100, 2000),
}

fig, axes = plt.subplots(2, 2, figsize=(10, 6))
for ax, (name, values) in zip(axes.flat, shapes.items()):
    ax.hist(values, bins=30, edgecolor="white")
    ax.set_title(name)
fig.tight_layout()
plt.show()
Four histograms: a symmetric bell shape, a right-skewed shape with a high left side and a long right tail, a shape with two separate peaks, and a flat uniform shape.
ShapeWhat it meansReal examples
Symmetric, bell-shapedValues cluster around a centre; mean ≈ medianHeights, measurement errors
Right-skewedMost values small, a few very large; mean > medianIncomes, house prices, bills, waiting times
Two peaksProbably two different groups mixed togetherHeights of men and women combined
UniformEvery range equally likelyRandom numbers, some ID numbers

Two peaks are a clue to split the data by some group. Right skew often calls for a log transform before machine learning, covered in statistics for machine learning.

Mark the mean and median

Reference lines help readers connect the picture to the numbers:

bills = tips["total_bill"]

fig, ax = plt.subplots()
ax.hist(bills, bins=20, edgecolor="white", color="lightsteelblue")
ax.axvline(bills.mean(), color="crimson", ls="--",
           label=f"Mean ${bills.mean():.2f}")
ax.axvline(bills.median(), color="black",
           label=f"Median ${bills.median():.2f}")
ax.set_xlabel("Total bill ($)")
ax.legend()
plt.show()
The bills histogram in light blue with a black median line at about 17.80 dollars and a dashed red mean line slightly to its right at about 19.79 dollars.

The mean is pulled to the right of the median by the long tail of big bills, which is the signature of right skew.

Compare groups

To compare two groups, draw both on the same bins with transparency:

lunch = tips.loc[tips["time"] == "Lunch", "total_bill"]
dinner = tips.loc[tips["time"] == "Dinner", "total_bill"]
bins = np.arange(0, 55, 2.5)

fig, ax = plt.subplots()
ax.hist(lunch, bins=bins, alpha=0.6, label="Lunch")
ax.hist(dinner, bins=bins, alpha=0.6, label="Dinner")
ax.set_xlabel("Total bill ($)")
ax.set_ylabel("Number of bills")
ax.legend()
plt.show()
Two overlapping histograms: lunch bills concentrated between 8 and 20 dollars, and dinner bills more numerous and spread further to the right.

Use the same bins for both, or the bars aren't comparable. With more than two or three groups, overlapping histograms get messy; use box plots or small separate charts instead.

Density instead of counts

There were far more dinners than lunches, so dinner's bars are taller just because there are more of them. To compare shapes fairly, use density=True, which scales each histogram so its total area is 1:

fig, ax = plt.subplots()
ax.hist(lunch, bins=bins, alpha=0.6, density=True, label="Lunch")
ax.hist(dinner, bins=bins, alpha=0.6, density=True, label="Dinner")
ax.set_ylabel("Density")
ax.legend()
plt.show()
The same two histograms scaled as densities, so lunch and dinner have equal total area; lunch is peaked at lower bills and dinner is shifted right.

Cumulative histograms

cumulative=True answers "what share of values are below x?":

fig, ax = plt.subplots()
ax.hist(bills, bins=50, cumulative=True, density=True, histtype="step", lw=2)
ax.axhline(0.8, color="grey", ls=":")
ax.set_xlabel("Total bill ($)")
ax.set_ylabel("Share of bills at or below")
plt.show()
A step line rising from 0 to 1 as the bill amount increases, with a dotted grey line at 0.8 crossing it at roughly 25 dollars.

Reading across from 0.8 shows that about 80% of bills are under roughly $25. (The vertical line at the far right is just Matplotlib closing the outline of the step shape; ignore it.)

Practice

  1. Draw a histogram of tips["tip"] with bins every 50 cents from 0 to 10. What do you notice?
Show the answer
fig, ax = plt.subplots()
ax.hist(tips["tip"], bins=np.arange(0, 10.5, 0.5), edgecolor="white")
plt.show()

Tips are right-skewed, with peaks at round amounts such as $2 and $3: people like round numbers.

  1. Why would you use density=True when comparing groups?
Show the answer

Groups often have different sizes. Density scaling makes each histogram's area 1, so you compare shapes rather than counts.

  1. A histogram of exam marks has two peaks, around 35 and around 75. What might explain it, and what would you check?
Show the answer

Two different groups may be mixed, such as two sections, two courses, or students who did and didn't attend. Split the data by likely groups and draw a histogram for each.

Interview questions

What does a histogram show?

The distribution of one numeric variable: values are grouped into bins, and bar heights show counts or densities. It reveals centre, spread, skewness, multiple peaks and outliers.

How does the number of bins affect a histogram?

Too few bins over-smooth and hide structure; too many create noisy spikes. Choose a moderate number, use rules such as bins="auto", and check that the shape is stable across a few settings.

In a right-skewed distribution, how do mean and median compare?

The mean is greater than the median, because the long right tail pulls the mean upwards.

What to learn next

  1. Compare distributions across groups with box plots in Matplotlib.
  2. Show parts of a whole with pie and donut charts.