Stem-and-Leaf Plots
Data Visualization
Preserve Your Data While Seeing the Shape
A stem-and-leaf plot organizes numerical data while retaining the actual values — unlike a histogram which loses individual data points. It is the best of both worlds: shape visibility plus raw data preservation.
- Retain original values — Every data point stays visible in the display
- Small dataset champion — Ideal when n is less than 100 and individual values matter
- Back-to-back comparison — Compare two distributions side by side effortlessly
- Read percentiles directly — Count to the middle value to find the median instantly
When your dataset is small enough that every value matters, the stem-and-leaf plot is your best friend.
What You'll Learn
- 1Split a dataset into stems and leaves and draw the plot with a stated key
- 2Select a leaf unit that keeps leaves as single digits and say what the key means
- 3Read the median, quartiles, shape and outliers straight off the plot
- 4Decide when a split stem or a histogram would represent the data better
What is a Stem-and-Leaf Plot?
Definition
A stem-and-leaf plot (or stemplot) is a data display that organizes numerical data while retaining the actual values — unlike a histogram which loses individual data points.
Best for: Small datasets (n less than 100), when you want to preserve original values, two-group comparisons.
Construction
Rule: Split each data value into a stem (leading digit(s)) and a leaf (last digit).
Example: Exam scores: 72, 68, 85, 91, 73, 77, 88, 65, 82, 79, 84, 93, 71, 66
Three conventions keep the display honest. Leaves are written as single digits in ascending order, so each row reads like a little histogram bar made of the actual data. Empty stems are kept rather than dropped, because a visible gap is information about the distribution. And a key is printed with every plot: without 7|2 = 72 a reader cannot tell whether the plot records 72, 7.2 or 720.
def stem_and_leaf(data, leaf_unit=1):
"""
Create a stem-and-leaf display for a list of numbers.
leaf_unit: the place value of the leaf (1 for ones, 10 for tens, etc.)
"""
from collections import defaultdict
stems = defaultdict(list)
for val in sorted(data):
stem = int(val // (leaf_unit * 10))
leaf = int((val % (leaf_unit * 10)) // leaf_unit)
stems[stem].append(leaf)
print(f"Stem-and-Leaf Plot (leaf unit = {leaf_unit})")
print(f"{'Stem':>5} | Leaves")
print(f"{'-----':>5}---{'-------'}")
for stem in sorted(stems.keys()):
leaves = ' '.join(str(l) for l in sorted(stems[stem]))
print(f"{stem:>5} | {leaves}")
print(f"\nKey: stem|leaf = each unit of {leaf_unit * 10}")
scores = [72, 68, 85, 91, 73, 77, 88, 65, 82, 79, 84, 93, 71, 66]
stem_and_leaf(scores)
# You can read off the median directly!
import numpy as np
print(f"\nMedian = {np.median(scores)}")
print(f"Min = {min(scores)}, Max = {max(scores)}")
Choosing the Leaf Unit
The leaf unit decides what a single digit stands for, and it is the only free parameter in the design. Choose it so that leaves stay single digits: too coarse a unit piles every value into one stem, too fine a unit scatters each value onto its own row. The plot header or key must always state the unit, because the same digits can be read three different ways.
| Leaf unit | Key | Stems become | Use it for |
|---|---|---|---|
| 10 | 7|2 = 720 | Hundreds | Values recorded in tens, such as 720, 750 |
| 1 | 7|2 = 72 | Tens | Whole numbers in the tens and hundreds |
| 0.1 | 7|2 = 7.2 | Ones | Measurements with one decimal place |
| 0.01 | 7|2 = 7.02 | Tenths | Measurements with two decimal places |
# The same helper with decimal data: leaf unit 0.1
measurements = [2.3, 2.7, 3.1, 3.4, 3.4, 4.0, 4.2, 4.9, 5.5]
stem_and_leaf(measurements, leaf_unit=0.1)
print("\nReading the plot:")
print(f" stem 3, leaf 4 means 3.4 (appears twice)")
print(f" median = {np.median(measurements):.2f}")
print(f" range = {max(measurements) - min(measurements):.2f}")
If every value shares the same leading digits — say all observations lie between 610 and 690 — those digits carry no information and can be dropped as a truncated stem, provided the key announces the truncation. Truncation is a presentation choice, not a data change; the leaves still reproduce every original value exactly once you reattach the prefix.
Reading the Plot by Hand
Because every value remains visible, percentiles other than the quartiles are equally cheap: the 20th percentile of 14 observations is the third value, 68, found simply by counting leaves. This is the property a histogram cannot offer — the moment data is binned, the individual order statistics are gone.
Split Stems for Wide Ranges
When one stem collects far more leaves than the rest, the display hides its own shape: a row of twenty digits looks like a uniform block regardless of how the values are distributed inside it. Splitting the stem fixes this by giving each leading digit two rows — leaves 0 through 4 on the lower half and 5 through 9 on the upper half — or five rows of two leaves each for an even wider range.
def split_stem_leaf(data, halves=True):
"""Stem-and-leaf with split stems: one row per 0-4 / 5-9 half (or per pair)."""
from collections import defaultdict
stems = defaultdict(list)
for val in sorted(data):
unit = val // 10
digit = int(val % 10)
if halves:
key = (unit, 0 if digit < 5 else 1)
else:
key = (unit, digit // 2)
stems[key].append(digit)
print(f"{'Stem':>6} | Leaves (leaf unit = 1)")
for key in sorted(stems):
unit, sub = key
label = f"{unit}.{sub}" if halves else f"{unit}.{sub}"
print(f"{label:>6} | {' '.join(str(d) for d in stems[key])}")
scores = [65, 66, 68, 71, 72, 73, 77, 79, 82, 84, 85, 88, 91, 93]
print("Split into 0-4 and 5-9 rows:\n")
split_stem_leaf(scores, halves=True)
Splitting trades resolution for uniformity: rows become comparable in length, clustering and gaps inside a stem become visible, and the plot still reconstructs every value. The opposite move — merging stems — is appropriate only when the range is so wide that dozens of nearly empty rows would dominate the page. There is no universal rule; the goal is that no single row should hold more than about a fifth of the leaves.
Back-to-Back Stem-and-Leaf
def back_to_back_stem(data_a, label_a, data_b, label_b, leaf_unit=1):
"""Back-to-back stem-and-leaf plot."""
from collections import defaultdict
stems_a = defaultdict(list)
stems_b = defaultdict(list)
for val in data_a:
stem = int(val // (leaf_unit * 10))
leaf = int((val % (leaf_unit * 10)) // leaf_unit)
stems_a[stem].append(leaf)
for val in data_b:
stem = int(val // (leaf_unit * 10))
leaf = int((val % (leaf_unit * 10)) // leaf_unit)
stems_b[stem].append(leaf)
all_stems = sorted(set(stems_a.keys()) | set(stems_b.keys()))
print(f"Back-to-Back Stem-and-Leaf: {label_a} vs {label_b}")
print(f"{'':>15} Stem {'':}")
print(f"{label_a:>15} | | {label_b}")
print("-" * 40)
for stem in all_stems:
left = ' '.join(str(l) for l in sorted(stems_a[stem], reverse=True))
right = ' '.join(str(l) for l in sorted(stems_b[stem]))
print(f"{left:>15} | {stem:2d} | {right}")
import numpy as np
np.random.seed(0)
class_a = sorted(np.random.normal(74, 8, 20).clip(50, 100).round(0).astype(int))
class_b = sorted(np.random.normal(81, 7, 20).clip(50, 100).round(0).astype(int))
back_to_back_stem(class_a, "Class A", class_b, "Class B")
print(f"\nClass A: median={np.median(class_a):.1f}, mean={np.mean(class_a):.1f}")
print(f"Class B: median={np.median(class_b):.1f}, mean={np.mean(class_b):.1f}")
Reading a back-to-back plot is the same counting exercise in two directions: leaves on the left run outward from the stem, so read them right to left to recover the values. A group whose leaves pile up on higher stems, with a longer tail reaching upward, is shifted relative to the other — and because both groups share one stem column, the comparison is immediate in a way that two separate histograms never manages.
Stem-and-Leaf vs Histogram
| Feature | Stem-and-Leaf | Histogram |
|---|---|---|
| Retains raw values | ✅ Yes | ❌ No |
| Works for large n | ❌ Unwieldy | ✅ Yes |
| Side-by-side comparison | ✅ Back-to-back | ✅ Overlaid |
| Shape visible | ✅ Yes | ✅ Yes |
| Median/quartiles readable | ✅ Yes | ❌ Not directly |
| Bin width choice | Fixed by the stem rule | Arbitrary, affects appearance |
| Density estimation | ❌ Not possible | ✅ With enough data |
The bin-width row is the subtle one. A histogram's message can change dramatically with the number of bins, and there is no way to recover the original observations afterwards. A stem-and-leaf plot's resolution is determined by the place value of the leaf, stated in the key, and the data is still there underneath it.
Stem-and-Leaf in Machine Learning
While histograms are more common in ML, stem-and-leaf plots have their place:
| ML Context | Why Stem-and-Leaf Works |
|---|---|
| Small validation set (n less than 50) | See every prediction value |
| A/B test results | Compare two groups precisely |
| Model comparison | Side-by-side error metrics |
| Hyperparameter search | Compare small result sets |
import numpy as np
# Comparing two models' prediction errors on a small test set
np.random.seed(42)
n_test = 25
model_a_errors = np.random.normal(0, 3, n_test).round(1)
model_b_errors = np.random.normal(0.5, 4, n_test).round(1)
def simple_stem(data, label):
"""Quick stem display for small data."""
stems = {}
for val in data:
stem = int(val // 10)
leaf = int(abs(val) % 10)
if stem not in stems:
stems[stem] = []
stems[stem].append(leaf)
print(f"\n{label}:")
for s in sorted(stems.keys()):
leaves = ' '.join(str(l) for l in sorted(stems[s]))
print(f" {s:3d} | {leaves}")
simple_stem(model_a_errors, "Model A errors")
simple_stem(model_b_errors, "Model B errors")
print(f"\nModel A: mean={model_a_errors.mean():.2f}, std={model_a_errors.std():.2f}")
print(f"Model B: mean={model_b_errors.mean():.2f}, std={model_b_errors.std():.2f}")
Negative errors expose a wrinkle in the design: a leaf is a single digit, so signs must be handled explicitly — either plot the absolute value of the leaf with a stated convention, or shift the data so it is positive before plotting. For residual diagnostics on small test sets this is a quick way to spot asymmetry without reaching for a plotting library.
Frequently Asked Questions
How many observations is too many for a stem-and-leaf plot?
Above roughly 100 values the rows become unreadable walls of digits and the plot stops communicating shape. At that size switch to a histogram or a density plot, and keep the stemplot for the exploratory pass on smaller extracts.
Should empty stems be shown?
Yes. A missing stem is a gap in the data — a range of values that never occurred — and removing it would make the distribution look continuous when it is not.
What is the difference between a truncated stem and a split stem?
Truncation drops a constant leading digit that carries no information, such as the hundreds place when every value lies between 600 and 690. Splitting gives one leading digit two or more rows so that a crowded stem reveals its internal shape. They solve opposite problems: too much constant detail versus too little resolution.
Can a stem-and-leaf plot show grouped or binned data?
No, and that is the point. Binning is what a histogram does, and it discards the individual values. The stem-and-leaf plot keeps every observation, which is why you can read exact percentiles from it.
Common Mistakes
Publishing the plot without a key
Fix: Always state what stem|leaf means, for example 7|2 = 72, or note the leaf unit, otherwise the digits are ambiguous.
Choosing a leaf unit that puts every value on one row
Fix: Adjust the unit so each stem collects a handful of leaves; the goal is comparable row lengths, not minimal rows.
Using a stemplot for a dataset of thousands
Fix: Past about 100 observations switch to a histogram or density plot and keep the stemplot for small extracts.
Key Takeaways
- A stemplot splits each value into leading digits and a final digit, keeping every original observation visible in the display
- The leaf unit and the key are mandatory: they are the only thing telling a reader whether 7|2 means 72, 7.2 or 720
- Median, quartiles and any percentile are read by counting leaves in order, with no binning step to lose information
- Split stems rescue a crowded row, truncated stems drop a constant prefix, and empty stems must stay visible as gaps
- Past about 100 observations the display collapses into rows of digits — hand over to a histogram and keep the stemplot for the small extract
Interview Questions
Q1: What is the advantage of a stem-and-leaf plot over a histogram?
It keeps every original value, so you can read the median, quartiles and any percentile directly, and two groups can be compared back-to-back on one stem column. A histogram bins the data and destroys those values.
Q2: How do you choose the leaf unit?
Pick the place value that keeps leaves as single digits and produces rows of comparable length — usually 1, 0.1 or 10 for typical measurement data — and always print the key so the digits are unambiguous.
Q3: When would you split a stem?
When one stem holds a disproportionate share of the leaves, because its internal shape is hidden. Splitting into 0–4 and 5–9 rows restores resolution without losing any values.
Q4: A plot shows an isolated leaf far from the rest of its stem. What next?
Check whether it is a data entry error or a genuine extreme value. Because the value is visible rather than absorbed into a bin, you can go straight back to the record and verify it.