typestar

Histograms in Python

Distribution shape, and the bin count that decides what you see.

import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np

rng = np.random.default_rng(1)
samples = rng.normal(loc=95, scale=12, size=800)

figure, axes = plt.subplots()
counts, edges, patches = axes.hist(samples, bins=24, density=True,
                                   color="#4c8bf5", edgecolor="white")
axes.axvline(samples.mean(), color="#e06c75", linestyle="--",
             label=f"mean {samples.mean():.1f}")
axes.set_xlabel("tpm")
axes.legend()
print(len(counts), edges[0].round(1), edges[-1].round(1))
figure.savefig("hist.png")

How it works

  1. bins takes a number or explicit edges.
  2. density=True normalizes to an area of one.
  3. axvline marks a statistic on top of the bars.

Keywords and builtins used here

The run, in numbers

Lines
18
Characters to type
526
Tokens
176
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 101 seconds.

Type this snippet

Step 4 of 5 in Plot types, step 8 of 14 in Plotting with matplotlib.

← Previous Next →

Histograms in other languages