svgbrushablehistogram
Histogram
How is one numeric variable distributed?
How to read it
- Find the tallest bars: that is where values are most common.
- Follow the outline for shape: one hump or two, a long tail on one side, gaps.
- Change the bin rule. A feature that survives other bin widths is real; one that vanishes came from the binning.
- Callout 1: The tallest bars: the most common values.
- Callout 2: A second hump: two groups may be mixed in this column.
- Callout 3: The tail: how far values stretch from the centre.
Watch out
- With few rows the shape is mostly noise: a bumpy histogram of 30 values says little about modes.
- Bin edges can create or hide a mode. Check a density curve or another bin rule before you describe a shape.
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 · Manual
- Bins (manual)
- 30
- The number of bins when the bin rule is manual.
- Range 2 to 200, step 1
- Y axis
- Density
- Show counts, density or shares on the y axis.
- Also: Count
- Density curve (KDE)
- On
- Draw a smoothed curve over the bars, to judge shape apart from the bins.
- Bandwidth rule
- nrd0 (Silverman, R default)
- The rule that sets how much the curve is smoothed. Scott and Silverman suit one-humped data.
- Also: nrd (Scott variant) · Scott (scipy default)
- Bandwidth × adjust
- 1
- Multiply the bandwidth: below 1 shows more detail and noise, above 1 gives a smoother curve.
- Range 0.25 to 4, step 0.25
- Normal fit
- Off
- Overlay the normal curve with this mean and standard deviation.
- Rug (≤ 5,000 points)
- Off
- Add one tick per value along the axis.
Pinned in the code
- Edges: numpy-style equal width over [min, max]; bins are [a, b) and the last bin is closed.
- Bin rules (numpy `histogram_bin_edges`): Freedman–Diaconis h = 2·IQR·n^(−1/3), Sturges ⌈log₂n⌉+1, Scott h = 3.49·σ·n^(−1/3), Rice 2·n^(1/3), √n, Doane.
- Quartiles are type 7; σ uses n − 1.
- KDE: Gaussian kernel, bandwidth = rule × adjust (R `density(bw = "nrd0", adjust)`); ≥ 20,000 points are thinned for the curve only.
- Normal fit: N(x̄, s²) density.
# Histogram — Codesplash Chart Lab (recipe "histogram")
# controls: bins=fd, binCount=30, scale=density, kde=true, bandwidth=nrd0, adjust=1, normal=false, rug=false
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.stats import gaussian_kde, norm
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"]
df = pd.read_csv("histogram-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
def bandwidth(v, rule="nrd0"):
"""R bw.nrd0 / bw.nrd, or scipy's Scott rule — as the app computes it."""
v = np.asarray(v, dtype=float)
n, sd = v.size, v.std(ddof=1)
iqr = np.subtract(*np.percentile(v, [75, 25]))
if rule == "scott":
return sd * n ** (-1 / 5)
lo = min(sd, iqr / 1.34) or sd or abs(v[0]) or 1.0
return (0.9 if rule == "nrd0" else 1.06) * lo * n ** (-1 / 5)
x = df["score"].dropna().to_numpy(dtype=float)
edges = np.histogram_bin_edges(x, bins="fd") # numpy edges, [a, b) like the app
width = edges[1] - edges[0]
fig, ax = plt.subplots(figsize=(7, 4))
ax.hist(x, bins=edges, density=True, color=PALETTE[0], alpha=0.85, edgecolor="white", linewidth=0.6)
grid = np.linspace(edges[0], edges[-1], 512)
scale = 1.0 # density → density
h = bandwidth(x, "nrd0") * 1
kde = gaussian_kde(x, bw_method=h / x.std(ddof=1)) # scipy takes the bandwidth relative to sd
ax.plot(grid, kde(grid) * scale, color=PALETTE[1], linewidth=2, label=f"KDE (h = {h:.3g})")
ax.set_xlabel("score")
ax.set_ylabel("Density")
ax.legend()
plt.show()Needs pandas, numpy, matplotlib, scipy · reads histogram-demo.csv · app theme from the optional codesplash helper
# Histogram — Codesplash Chart Lab (recipe "histogram")
# controls: bins=fd, binCount=30, scale=density, kde=true, bandwidth=nrd0, adjust=1, normal=false, rug=false
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from scipy.stats import gaussian_kde, norm
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
df = pd.read_csv("histogram-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
def bandwidth(v, rule="nrd0"):
"""R bw.nrd0 / bw.nrd, or scipy's Scott rule — as the app computes it."""
v = np.asarray(v, dtype=float)
n, sd = v.size, v.std(ddof=1)
iqr = np.subtract(*np.percentile(v, [75, 25]))
if rule == "scott":
return sd * n ** (-1 / 5)
lo = min(sd, iqr / 1.34) or sd or abs(v[0]) or 1.0
return (0.9 if rule == "nrd0" else 1.06) * lo * n ** (-1 / 5)
x = df["score"].dropna().to_numpy(dtype=float)
edges = np.histogram_bin_edges(x, bins="fd") # numpy edges, [a, b) like the app
counts, _ = np.histogram(x, bins=edges, density=True)
fig = go.Figure(go.Bar(x=(edges[:-1] + edges[1:]) / 2, y=counts, width=np.diff(edges), marker_color=PALETTE[0], opacity=0.85, name="score"))
grid = np.linspace(edges[0], edges[-1], 512)
scale = 1.0
from scipy.stats import gaussian_kde
h = bandwidth(x, "nrd0") * 1
fig.add_scatter(x=grid, y=gaussian_kde(x, bw_method=h / x.std(ddof=1))(grid) * scale, mode="lines", line_color=PALETTE[1], name="KDE")
fig.update_layout(bargap=0, xaxis_title="score", yaxis_title="Density")
fig.show()Needs pandas, numpy, plotly, scipy · reads histogram-demo.csv · app theme from the optional codesplash helper
# Histogram — Codesplash Chart Lab (recipe "histogram")
# controls: bins=fd, binCount=30, scale=density, kde=true, bandwidth=nrd0, adjust=1, normal=false, rug=false
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))
df <- read.csv("histogram-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
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)
}
bandwidth <- function(v, rule = "nrd0") {
switch(rule, nrd0 = bw.nrd0(v), nrd = bw.nrd(v), scott = sd(v) * length(v)^(-1 / 5))
}
x <- df[["score"]]
x <- x[is.finite(x)]
breaks <- np_edges(x, "fd")
bw <- diff(breaks)[1]
scale <- 1 # density
kde <- density(x, bw = bandwidth(x, "nrd0") * 1,
from = min(breaks), to = max(breaks), n = 512)
p <- ggplot(data.frame(x = x), aes(x)) +
geom_histogram(aes(y = after_stat(density)), breaks = breaks, closed = "left", fill = cs_cat[1], colour = "white", alpha = 0.85) +
geom_line(data = data.frame(x = kde$x, y = kde$y * scale), aes(x, y), colour = cs_cat[2], linewidth = 1) +
labs(x = "score", y = "Density") +
theme_cs
print(p)Needs ggplot2 · reads histogram-demo.csv · app theme from the optional codesplashr helper
-- Histogram — Codesplash Chart Lab (recipe "histogram")
-- controls: bins=fd, binCount=30, scale=density, kde=true, bandwidth=nrd0, adjust=1, normal=false, rug=false
-- numpy-style equal-width edges from min to max; bins are [a, b), the last one closed
WITH v AS (SELECT "score"::DOUBLE AS x FROM read_csv('histogram-demo.csv') WHERE "score" IS NOT NULL AND isfinite("score"::DOUBLE)),
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 least(floor((x - lo) / ((hi - lo) / k)), k - 1)::INTEGER AS bin
FROM v, k
)
SELECT bin,
lo + bin * (hi - lo) / k AS x0,
lo + (bin + 1) * (hi - lo) / k AS x1,
count(*) AS count,
count(*) / (n * (hi - lo) / k) AS density
FROM b, k
GROUP BY bin, lo, hi, n, k
ORDER BY bin;Needs duckdb · reads histogram-demo.csv