Skip to content
svgbrushablefreq-poly

Frequency polygon

How do the distributions of several groups compare on the same bins?

Demo data · seed 20261101 · 860 rows · default settings · 640 × 360SVG, lightSVG, darkDemo CSV

How to read it

  1. Follow one line at a time: its height at each point is the count or share in that bin.
  2. Compare where each group peaks.
  3. Use shares rather than counts when group sizes differ.
  1. Callout 1: A peak: the most common range for this group.
  2. Callout 2: Another group peaks further right: larger values.
  3. Callout 3: A line resting on zero: no values there.

Watch out

  • Lines imply continuity between bins; a sharp peak may only be one bin.

Defaults

Bin rule
Freedman–Diaconis
How the bin width is chosen. Freedman–Diaconis resists outliers; Sturges suits small, near-normal data.
Also: Sturges · Scott · Rice · Square root · Doane
Y axis
Percent of group
Show counts, density or shares on the y axis.
Also: Count · Density

Pinned in the code

  • Bins: one shared set of equal-width numpy-style edges over the pooled range (rule on the pooled data), [a, b) with the last bin closed.
  • Polygon through bin midpoints, closed to zero half a bin beyond each end (ggplot2 `geom_freqpoly`).
  • Percent = bin count / group n, so groups of different sizes are comparable.
# Frequency polygon — Codesplash Chart Lab (recipe "freq-poly")
# controls: bins=fd, value=percent
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

try:
    import codesplash as cs  # optional: the app's chart theme
except ImportError:
    cs = None
if cs:
    cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else plt.rcParams["axes.prop_cycle"].by_key()["color"]
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_DASHES = ["-", (0, (6, 3)), (0, (1.5, 2.5)), (0, (8, 3, 2, 3)), (0, (12, 4)), (0, (3, 3)), (0, (8, 2, 2, 2, 2, 2)), (0, (1.5, 5))]
SERIES_MARKERS = ["o", "s", "^", "D", "P", "*", "2", "v"]

df = pd.read_csv("freq-poly-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["mode"] = pd.Categorical(df["mode"].astype("string"), categories=["Car", "Transit", "Bike"])

def groups(frame, value, group=None, max_levels=12):
    """(label, values) per group in level order; rows missing the value or the group are dropped."""
    if group is None:
        return [(value, frame[value].dropna().to_numpy(dtype=float))]
    d = frame[[value, group]].dropna()
    out = []
    for level in list(d[group].cat.categories)[:max_levels]:
        v = d.loc[d[group] == level, value].to_numpy(dtype=float)
        if v.size:
            out.append((str(level), v))
    return out

parts = groups(df, "commute_min", "mode", max_levels=8)
pooled = np.concatenate([v for _, v in parts])
edges = np.histogram_bin_edges(pooled, bins="fd")  # one shared set of numpy edges on the pooled data
w = edges[1] - edges[0]
xs = np.r_[edges[0] - w / 2, (edges[:-1] + edges[1:]) / 2, edges[-1] + w / 2]  # closed to zero half a bin beyond each end
fig, ax = plt.subplots(figsize=(7, 4))
for i, (label, v) in enumerate(parts):
    counts, _ = np.histogram(v, bins=edges)  # [a, b), last bin closed
    many = len(parts) > 1  # several groups: a dash and a dot shape per group, as in the app
    ax.plot(xs, np.r_[0, counts / v.size * 100, 0], color=PALETTE[i % len(PALETTE)], linewidth=2, linestyle=SERIES_DASHES[i % 8] if many else "-", marker=SERIES_MARKERS[i % 8] if many else "o", markersize=4 if many else 3, markevery=slice(1, -1), label=label)
ax.set_xlabel("commute_min")
ax.set_ylabel("Percent of group")
if len(parts) > 1:
    ax.legend()
plt.show()

Needs pandas, numpy, matplotlib · reads freq-poly-demo.csv · app theme from the optional codesplash helper