svgbrushablefreq-poly
Frequency polygon
How do the distributions of several groups compare on the same bins?
How to read it
- Follow one line at a time: its height at each point is the count or share in that bin.
- Compare where each group peaks.
- Use shares rather than counts when group sizes differ.
- Callout 1: A peak: the most common range for this group.
- Callout 2: Another group peaks further right: larger values.
- 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
# Frequency polygon — Codesplash Chart Lab (recipe "freq-poly")
# controls: bins=fd, value=percent
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
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 px.colors.qualitative.Plotly
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_DASHES = ["solid", "6px,3px", "1.5px,2.5px", "8px,3px,2px,3px", "12px,4px", "3px,3px", "8px,2px,2px,2px,2px,2px", "1.5px,5px"]
SERIES_MARKERS = ["circle", "square", "triangle-up", "diamond", "cross", "star", "y-up", "triangle-down"]
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 = go.Figure()
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
fig.add_scatter(x=xs, y=np.r_[0, counts / v.size * 100, 0], mode="lines+markers", line=dict(color=PALETTE[i % len(PALETTE)], width=2, dash=SERIES_DASHES[i % 8] if many else "solid"), marker=dict(size=6 if many else 5, symbol=SERIES_MARKERS[i % 8] if many else "circle"), name=label)
fig.update_layout(xaxis_title="commute_min", yaxis_title="Percent of group", showlegend=len(parts) > 1)
fig.show()Needs pandas, numpy, plotly · reads freq-poly-demo.csv · app theme from the optional codesplash helper
# Frequency polygon — Codesplash Chart Lab (recipe "freq-poly")
# controls: bins=fd, value=percent
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
cs_linetypes <- c("solid", "63", "23", "8323", "C4", "33", "822222", "25")
cs_shapes <- c(16, 15, 17, 18, 3, 8, 4, 25)
df <- read.csv("freq-poly-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["mode"]] <- factor(df[["mode"]], levels = c("Car", "Transit", "Bike"))
np_edges <- function(x, rule = "fd", k = NULL) {
# numpy.histogram_bin_edges: equal-width edges from min to max (the app's convention)
n <- length(x); lo <- min(x); hi <- max(x); ptp <- hi - lo
if (is.null(k)) {
width <- switch(rule,
fd = 2 * IQR(x, type = 7) * n^(-1 / 3),
sturges = ptp / (log2(n) + 1),
scott = (24 * sqrt(pi) / n)^(1 / 3) * sqrt(mean((x - mean(x))^2)),
rice = ptp / (2 * n^(1 / 3)),
sqrt = ptp / sqrt(n),
doane = {
sg1 <- sqrt(6 * (n - 2) / ((n + 1) * (n + 3)))
g1 <- mean(((x - mean(x)) / sqrt(mean((x - mean(x))^2)))^3)
ptp / (1 + log2(n) + log2(1 + abs(g1) / sg1))
})
k <- if (is.finite(width) && width > 0) max(1, ceiling(ptp / width)) else 1
}
if (ptp == 0) return(c(lo - 0.5, hi + 0.5))
seq(lo, hi, length.out = k + 1)
}
groups_of <- function(df, value, group = NULL, max_levels = 12) {
# values per group in level order; rows missing the value or the group are dropped
v <- df[[value]]
if (is.null(group)) return(stats::setNames(list(v[is.finite(v)]), value))
g <- df[[group]]
keep <- is.finite(v) & !is.na(g)
out <- split(v[keep], factor(g[keep], levels = utils::head(levels(g), max_levels)))
out[lengths(out) > 0]
}
parts <- groups_of(df, "commute_min", "mode", max_levels = 8)
breaks <- np_edges(unlist(parts, use.names = FALSE), "fd") # one shared set of numpy edges on the pooled data
w <- diff(breaks)[1]
mids <- c(breaks[1] - w / 2, (head(breaks, -1) + tail(breaks, -1)) / 2, tail(breaks, 1) + w / 2) # closed to zero half a bin beyond each end
poly <- do.call(rbind, lapply(names(parts), function(k) {
v <- parts[[k]]
counts <- tabulate(findInterval(v, breaks, rightmost.closed = TRUE, all.inside = TRUE), nbins = length(breaks) - 1) # [a, b), last closed
data.frame(group = k, x = mids, y = c(0, counts / length(v) * 100, 0))
}))
poly$group <- factor(poly$group, levels = names(parts))
p <- ggplot(poly, aes(x, y, colour = group, linetype = group, shape = group)) + # dash and dot shape per group, as in the app
geom_line(linewidth = 0.9) + geom_point(data = function(d) d[!(d$x %in% range(d$x)), ], size = 1.6) + # dots at the bin midpoints, not the closing zeros
scale_colour_manual(values = rep(cs_cat, length.out = length(parts))) + scale_linetype_manual(values = cs_linetypes) + scale_shape_manual(values = cs_shapes) +
labs(x = "commute_min", y = "Percent of group", colour = NULL, linetype = NULL, shape = NULL) + theme_cs
if (length(parts) == 1) p <- p + theme(legend.position = "none")
print(p)Needs ggplot2 · reads freq-poly-demo.csv · app theme from the optional codesplashr helper
-- Frequency polygon — Codesplash Chart Lab (recipe "freq-poly")
-- controls: bins=fd, value=percent
-- one shared set of numpy-style edges over the pooled data; counts per group, bins [a, b) with the last closed
-- (bins a group never reaches have no row)
WITH v AS (
SELECT "mode"::VARCHAR AS grp, "commute_min"::DOUBLE AS x
FROM read_csv('freq-poly-demo.csv')
WHERE "commute_min" IS NOT NULL AND isfinite("commute_min"::DOUBLE) AND "mode" IS NOT NULL
),
s AS (
SELECT min(x) AS lo, max(x) AS hi, count(*) AS n,
quantile_cont(x, 0.75) - quantile_cont(x, 0.25) AS iqr,
stddev_pop(x) AS sd0, skewness(x) AS g1
FROM v
),
k AS (SELECT lo, hi, n, coalesce(greatest(1, ceil((hi - lo) / NULLIF(CASE WHEN true THEN 2 * iqr * pow(n, -1.0 / 3) END, 0)))::INTEGER, 1) AS k FROM s),
b AS (
SELECT grp, least(floor((x - lo) / ((hi - lo) / k)), k - 1)::INTEGER AS bin
FROM v, k
)
SELECT grp, bin,
lo + bin * (hi - lo) / k AS x0,
lo + (bin + 1) * (hi - lo) / k AS x1,
count(*) AS count,
count(*) / sum(count(*)) OVER (PARTITION BY grp) AS share,
count(*) / sum(count(*)) OVER (PARTITION BY grp) / ((hi - lo) / k) AS density
FROM b, k
GROUP BY grp, bin, lo, hi, k
ORDER BY grp, bin;Needs duckdb · reads freq-poly-demo.csv