bhylu.com

Advertisements

Matplotlib Histograms

A histogram groups numeric observations into intervals and counts their occurrences. The bin choices are part of the analysis.

Understand the idea

Unlike a category bar chart, neighbouring bins represent adjacent ranges on a numeric scale. Different bin boundaries can make the same small sample look quite different. Counts and density have different meanings, so label the y-axis accordingly. Do not infer a smooth population distribution from a handful of observations.

Where to try it

Run this complete script in a local virtual environment with Matplotlib installed (py -m pip install matplotlib). It uses a non-interactive backend and saves workshop.png in the current folder. The site shows a rendered example below; its text-only online runner does not display plot windows.

A worked example

Python

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(7, 4), layout="constrained")
durations = [12, 15, 16, 18, 21, 22, 24, 25, 28]
ax.hist(durations, bins=[10, 15, 20, 25, 30], edgecolor="white")
ax.set(xlabel="Task duration (minutes)", ylabel="Tasks", title="Demo task durations")
fig.savefig("workshop.png", dpi=140)
plt.close(fig)
print("Saved workshop.png")

Read the result

The image counts observations in four five-minute intervals. The final interval includes its right boundary under the histogram rules.

The image counts observations in four five-minute intervals. The final interval includes its right boundary under the histogram rules.
Rendered from this original example. Change and rerun the script locally to make your own chart.

Try one change

Compare two sensible bin choices and explain which features remain stable and which are bin-dependent.

For package options, see the Matplotlib documentation.