Matplotlib Histograms
A histogram shows how values are distributed. It splits the range of the data into intervals called bins and draws a bar whose height is the number of values in each bin. Where is the data concentrated? Is it symmetric? Are there outliers? A histogram answers these at a glance.
A first histogram
plt.hist(data) does the counting for you. Here are the delivery times of 500 simulated orders:
import numpy as np
import matplotlib.pyplot as plt
rng = np.random.default_rng(42)
minutes = rng.normal(loc=35, scale=6, size=500)
counts, edges, patches = plt.hist(minutes)
plt.xlabel("Delivery time (minutes)")
plt.ylabel("Orders")
plt.title("500 deliveries")
plt.show()
print("Bins:", len(counts))
print("Counts:", counts.astype(int).tolist())
print(f"First bin: {edges[0]:.1f} to {edges[1]:.1f} min")Bins: 10
Counts: [9, 24, 55, 82, 113, 109, 59, 33, 12, 4]
First bin: 19.6 to 22.9 min
hist() returns three things: the counts per bin, the bin edges (one more than the number of bins) and the drawn bar patches. The default is 10 equal-width bins.
rng.normal(35, 6, 500) draws 500 values from a normal (bell-shaped) distribution with mean 35 and standard deviation 6, which is why the histogram looks like a bell.
Choosing the bins
The number of bins changes the story. Too few hide the shape; too many make it noisy. Pass an integer, an explicit list of edges, or a rule such as "auto":
import numpy as np
import matplotlib.pyplot as plt
rng = np.random.default_rng(42)
minutes = rng.normal(35, 6, 500)
fig, axes = plt.subplots(1, 3, figsize=(10, 3), sharey=False)
for ax, bins in zip(axes, [5, 30, range(15, 61, 5)]):
counts, edges, _ = ax.hist(minutes, bins=bins, edgecolor="white")
ax.set_title(f"{len(counts)} bins")
fig.tight_layout()
plt.show()
print("Explicit edges:", list(range(15, 61, 5)))Explicit edges: [15, 20, 25, 30, 35, 40, 45, 50, 55, 60]
Explicit edges like range(15, 61, 5) give "nice" bin boundaries (15–20, 20–25, …) that readers can interpret easily.
Styling and comparing distributions
histtype="step" draws only the outline, and alpha makes filled histograms see-through, so two distributions can share one plot. density=True scales the heights so that the total area is 1, which makes groups of different sizes comparable:
import numpy as np
import matplotlib.pyplot as plt
rng = np.random.default_rng(5)
weekday = rng.normal(32, 5, 800)
weekend = rng.normal(41, 7, 300)
bins = np.arange(10, 70, 2.5)
plt.hist(weekday, bins=bins, alpha=0.6, density=True, label="Weekday (800)")
plt.hist(weekend, bins=bins, alpha=0.6, density=True, label="Weekend (300)")
plt.xlabel("Delivery time (minutes)")
plt.ylabel("Density")
plt.legend()
plt.show()
print(f"Weekday mean {weekday.mean():.1f}, weekend mean {weekend.mean():.1f}")Weekday mean 32.0, weekend mean 41.6
| Argument | Effect |
|---|---|
bins |
Number of bins, list of edges, or a rule ("auto", "sturges", …) |
range=(a, b) |
Ignore values outside this range |
density=True |
Normalise so the area equals 1 |
cumulative=True |
Each bar counts all values up to its right edge |
histtype |
"bar" (default), "step", "stepfilled", "barstacked" |
orientation |
"vertical" or "horizontal" |
Cumulative histograms
A cumulative histogram answers "how many orders arrived within t minutes?". With density=True the last bar reaches 1 (100 %):
import numpy as np
import matplotlib.pyplot as plt
rng = np.random.default_rng(42)
minutes = rng.normal(35, 6, 500)
counts, edges, _ = plt.hist(minutes, bins=40, cumulative=True, density=True,
histtype="stepfilled", alpha=0.5)
plt.axhline(0.9, color="gray", linestyle="--")
plt.xlabel("Delivery time (minutes)")
plt.ylabel("Share of orders")
plt.show()
within_45 = (minutes <= 45).mean()
print(f"Delivered within 45 minutes: {within_45:.1%}")Delivered within 45 minutes: 95.4%
Note: If you already have counts (for example from
np.histogram) and only want to draw them, useplt.stairs(counts, edges)orplt.barinstead ofhist.
Test yourself
What does plt.hist(data, bins=20) return first?
- The figure
- The counts per bin
- The mean of the data
- Nothing
If a histogram has 8 bins, how many bin edges are there?
- 7
- 8
- 9
- 16
Why use density=True when overlaying two histograms?
- It makes the bars thinner
- It makes groups of different sizes comparable
- It removes outliers
- It sorts the values