svgstem-leaf
Stem-and-leaf
What are the actual values of a small sample, shown as a sideways histogram?
How to read it
- Read a row as stem plus leaf: the stem is the leading digit and each leaf is the next digit of one value.
- Turn your head sideways: the leaf lengths form a histogram.
- Check the note above the display for where the decimal point falls.
- Callout 1: Stem: the leading digit.
- Callout 2: Leaves: the next digit of each value in this row.
- Callout 3: The longest rows: where values concentrate.
Watch out
- Only useful for small samples: beyond a hundred or so values use a histogram.
Defaults
- Scale (stem length)
- 1
- A larger scale spreads values over more stems.
- Range 0.5 to 4, step 0.5
Pinned in the code
- Exact port of R's `stem(x, scale, width = 80, atom = 1e-08)` (graphics/src/stem.c): line width and stem unit (×1, ×2 or ×5 splits) chosen from the range and n; leaves are rounded, not truncated.
- The note says where the decimal point sits relative to the bar; the right column is the line count.
# Stem-and-leaf — Codesplash Chart Lab (recipe "stem-leaf")
# controls: scale=1
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"]
df = pd.read_csv("stem-leaf-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
def stem(x, scale=1.0, width=80, atom=1e-8):
"""Port of R's stem() (src/library/graphics/src/stem.c): returns (note, lines)."""
x = np.sort(np.asarray(x, dtype=float))
x = x[np.isfinite(x)]
n = x.size
if n <= 1:
return "", []
if x[-1] > x[0]:
r = atom + (x[-1] - x[0]) / scale
c = 10.0 ** int(1 - np.floor(np.log10(r) + 1e-7))
mm = min(2, max(0, int(r * c / 25)))
k = 3 * mm + 2 - int(150 / (n + 50))
if (k - 1) * (k - 2) * (k - 5) == 0:
c *= 10
x1 = max(abs(x[0]), abs(x[-1]))
while x1 * c > 2147483647:
c /= 10
else:
r = atom + abs(x[0]) / scale
c = 10.0 ** int(1 - np.floor(np.log10(r) + 1e-7))
k = 2
mu = 10
if k * (k - 4) * (k - 8) == 0:
mu = 5
if (k - 1) * (k - 5) * (k - 6) == 0:
mu = 20
lo = np.floor(x[0] * c / mu) * mu
hi = np.floor(x[-1] * c / mu) * mu
ldigits = int(np.floor(np.log10(-lo))) + 1 if lo < 0 else 0
hdigits = int(np.floor(np.log10(hi))) if hi > 0 else 0
ndigits = max(ldigits, hdigits)
if lo < 0 and np.floor(x[0] * c) == lo:
lo -= mu
hi = lo + mu
if np.floor(x[0] * c + 0.5) > hi:
lo = hi
hi = lo + mu
pdigits = 1 - int(np.floor(np.log10(c) + 0.5))
if pdigits == 0:
note = "The decimal point is at the |"
else:
note = f"The decimal point is {abs(pdigits)} digit(s) to the {'right' if pdigits > 0 else 'left'} of the |"
def stem_text(close, dist):
s = "-0" if int(close / 10) == 0 and dist < 0 else str(int(close / 10))
return s.rjust(ndigits)
lines, i = [], 0
while True:
label = stem_text(int(hi), int(lo)) if lo < 0 else stem_text(int(lo), int(hi))
leaves, j = "", 0
while i < n:
xi = int(x[i] * c - 0.5) if x[i] < 0 else int(x[i] * c + 0.5)
if (hi == 0 and x[i] >= 0) or (lo < 0 and xi > hi) or (lo >= 0 and xi >= hi):
break
j += 1
if j <= width - 12:
leaves += str(abs(xi) % 10)
i += 1
lines.append(f" {label} | {leaves}" + (f"+{j - width}" if j > width else ""))
if i >= n:
break
hi += mu
lo += mu
return note, lines
note, lines = stem(df["score"].dropna().to_numpy(dtype=float), scale=1)
text = "\n".join([note, ""] + lines)
print(text)
fig, ax = plt.subplots(figsize=(7, 0.8 + 0.2 * (len(lines) + 2)))
ax.axis("off")
ax.text(0, 1, text, family="monospace", va="top", ha="left", fontsize=9, transform=ax.transAxes)
ax.set_title("Stem-and-leaf display of score", loc="left")
plt.show()Needs pandas, numpy, matplotlib · reads stem-leaf-demo.csv · app theme from the optional codesplash helper
# Stem-and-leaf — Codesplash Chart Lab (recipe "stem-leaf")
# controls: scale=1
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("stem-leaf-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
x <- df[["score"]]
x <- x[is.finite(x)]
lines <- capture.output(stem(x, scale = 1, width = 80)) # R's own stem(): the app ports it exactly
cat(lines, sep = "\n")
p <- ggplot(data.frame(y = rev(seq_along(lines)), label = lines), aes(0, y, label = label)) +
geom_text(family = "mono", hjust = 0, size = 3.2) +
scale_x_continuous(limits = c(0, 1)) +
labs(title = "Stem-and-leaf display of score") +
theme_void() + theme(plot.title = element_text(face = "bold"))
print(p)Needs ggplot2 · reads stem-leaf-demo.csv · app theme from the optional codesplashr helper
- A stem-and-leaf display is text: plotly has no equivalent and the leaves are not SQL-friendly, so only matplotlib (a port of R's stem()) and R are emitted.