Summarizing Distributions

Ten support tickets took 2 to 7 minutes, and one took 120. The mean says 15.9 minutes. Nine of the ten tickets beat it.

Drag the slow ticket out to 1,000 minutes. Watch the mean chase it while the median stays at 4.5. Then we build, piece by piece, the summaries that survive outliers, skew and two humps, and the plots that show what one number hides.

You need sums, sorting and square roots (see ML Maths) and a little Python. We build the rest from zero.

Part of the Evaluation and Analytics family. Its siblings The Statistics of Evaluation and Plots That Tell the Truth start where this lesson stops.

Pull one ticket out

120 min

The ten ticket times are a made-up example. The axis is logarithmic so that 2 minutes and 1,000 minutes both fit.

Chapter 0

The Average Is a Lie

See one slow ticket drag the mean away from every real ticket

Ten support tickets came in last week. They took 2, 3, 3, 4, 4, 5, 5, 6, 7 and 120 minutes to resolve. Nine were quick. One was a two-hour outage. The service report wants one number for the "average response time".

Name the quantities first. Call the number of tickets n. Call the time of ticket number i xi. The mean is the total time divided by the count.

Say it aloud

x-bar equals one over n, times the sum over i of x-i.

x̄
x-bar the mean, in minutes here.
1/n
one over n divides by the count: n = 10 tickets.
Σi
the sum over i add one term for each ticket, i from 1 to n.
xi
x-i the time of ticket i, in minutes.
In plain words

Add the n ticket times x-i. Divide the total by n. The result is x-bar.

With numbers

The ten times add to 159 minutes and n = 10, so x-bar = 159 / 10 = 15.9 minutes. No ticket took anywhere near 15.9 minutes.

The median is the middle value after you sort. Ten tickets have two middle values, 4 and 5, so the median is their average, 4.5 minutes. It sits inside the fast cluster, where nine tickets live.

Now drag the slow ticket in the hero to 1,000 minutes. The total becomes 39 + 1,000 = 1,039, so the mean is 103.9. The median stays at 4.5. One ticket moved 880 minutes, the mean moved 88, and the median moved 0.

Ask who lives near the summary

Each dot is one observation. The bands reach 25% either side of the mean (warm) and the median (blue). Pick a dataset and count the dots in each band.

All four datasets are the small made-up examples of this lesson. The 25% band is an arbitrary yardstick for "near".

A summary is robust if one wild value cannot move it far. The median is robust. The mean is not, because every value pulls on the total. The mean is still the right number for totals, since total = mean × count.

The failure, in three parts. Symptom: a dashboard average that no customer recognises. Measure: put the mean beside the median, and count the values below the mean. Fix: report the median for the typical case and a high percentile for the bad case.

The road

  1. Mean, median and mode: the center each one picks, and why.
  2. Percentiles: a rank, computed by one rule, with conventions that disagree.
  3. Spread: standard deviation against IQR when one value goes wild.
  4. The ECDF: the whole distribution with no bins to choose.
  5. Box plots: five numbers and a fence that flags outliers.
  6. Violins and KDE: the second hump a box plot hides.
  7. Heavy tails: a center, a tail number and a plot.
  8. The detective: break one dataset three ways, see which summaries lie.
  9. The field guide: terms, a checklist and the code.
Ticket times are 2, 3, 3, 4, 4, 5, 5, 6, 7 and 120 minutes: mean 15.9, median 4.5. You push the 120 out to 1,000. What happens?

Chapter 1

Mean, Median and Mode

Find the center each summary picks, and see why the median ignores how far the far value is

A startup has seven people. Their salaries, in thousands of dollars, are 38, 42, 45, 45, 52, 58 and 200. The 200 is the founder. What is the typical salary?

Three summaries answer three questions. The mean answers "if we split the payroll equally, how much each?". The median answers "what does the middle person earn?". The mode, the most frequent value, answers "which value occurs most?".

SummaryAll sevenWithout the founder
Mean68.646.7
Median4545
Mode4545

Why does the median ignore the founder? Each center makes some total distance smallest. Call a candidate center c. Call the distance from salary xi to c, ignoring its sign, the absolute distance.

Say it aloud

A of c equals the sum over i of the absolute value of x-i minus c.

A(c)
A of c the total distance from every salary to the candidate c, in thousands of dollars.
Σi
the sum over i one term per person, i from 1 to 7.
|xi − c|
the absolute value of x-i minus c how far salary x-i sits from c. It is never negative.
In plain words

Pick a candidate c. Measure how far each salary x-i is from c. Add the distances to get A of c. The c with the smallest A is the median.

With numbers

At c = 45, A = 7 + 3 + 0 + 0 + 7 + 13 + 155 = 185. At c = 52, A = 192. No c does better than 45, the median.

Here is why. Move c one step to the right. Every salary left of c gets one step farther, and every salary right of c gets one step closer. So A falls while more salaries sit to the right of c. It stops falling when the two sides balance, and that point is the median. The founder counts as one salary on the right, at 200 or at 2,000.

Square each distance instead and add the squares. That total, S(c), is smallest at the mean. Squaring turns the founder's distance of 155 into 24,025, so the center leans toward him.

S(45) = 24,301    S(68.57) = 20,411.7   (the minimum, at the mean)

Slide a candidate center

Top: the salaries and your candidate c. Below: the total distance A (blue) and the total squared distance S (warm) for every c. Find each minimum, then take the founder out.

52

Made-up salaries. We scale each curve to the same height, so compare where they bottom out, not their heights.

The mode is the only center for categories, such as the most common error code. With a long right tail the usual order is mode, then median, then mean. So a mean above the median is a skew alarm.

Symptom: a recruiter quotes the mean, 68.6 thousand, and six of seven people earn less. Measure: the gap from median to mean is (68.6 − 45) / 45 = 52%. Fix: quote the median for the typical member and keep the mean for budgets.

For the values 1, 2 and 9, which center c makes the total distance A(c) smallest?

Chapter 2

Percentiles Count Ranks

Compute any percentile with one rule, and see why two tools can disagree on p99

Your latency target says "p99 under 200 ms". The p-th percentile is the value with p percent of the data at or below it. A quantile is the same idea on a 0 to 1 scale: the 0.9 quantile is the 90th percentile.

The median is the 50th percentile. The quartiles cut the data into four equal parts: Q1 is the 25th percentile, Q2 is the median and Q3 is the 75th.

The hard part is a rank that falls between two values. Take eight API latencies, sorted, in ms: 12, 15, 18, 20, 22, 25, 30, 40. Call them x[0] to x[n − 1], with n = 8. Call the target share p, from 0 to 1. The fractional rank is h = (n − 1) × p. Its whole part is k and the rest is the fraction f.

Say it aloud

Q of p equals x at k, plus f times the gap from x at k to x at k plus one.

Q(p)
Q of p the p quantile, in ms.
x[k]
x at k the sorted value with index k: the lower neighbour. k is the whole part of h = (n − 1) × p.
f
f the fraction of h past k, from 0 up to 1.
x[k+1] − x[k]
x at k plus one, minus x at k the gap to the next sorted value.
In plain words

Sort the values. Compute h = (n − 1) × p and split it into k and f. Start at x at k and walk the fraction f of the way to the next value.

With numbers

For Q1, p = 0.25, so h = 7 × 0.25 = 1.75, k = 1 and f = 0.75. Then Q1 = 15 + 0.75 × (18 − 15) = 17.25 ms. The same steps give a median of 21 ms and Q3 = 26.25 ms.

Walk the percentile ruler

Top: the eight latencies on a value axis. Bottom: the same eight as evenly spaced ranks. Drag p and watch the rank pointer pick a value. Then change the convention.

25

Made-up latencies. The four conventions are four of numpy's percentile methods; linear is its default.

Percentiles count ranks, not distance. The 90th percentile is not the point 90% of the way from 12 to 40, which is 37.2. It is the value with 90% of the points at or below it. By the linear rule that is 33 ms.

Software disagrees on purpose. numpy offers several methods, Excel has PERCENTILE.INC and PERCENTILE.EXC, and Hyndman and Fan (1996) list nine definitions in common packages. On these eight values Q1 is 17.25 by linear, 18 by nearest and 15 by lower.

Symptom: the monitor says p99 is 210 and your notebook says 198. Measure: write down each tool's method, time window and which requests it counts. Fix: pick one definition, write it into the target, and compute both sides that way. Do not average per-server p99 values; merge the data instead.

For the sorted values 12, 15, 18, 20, 22, 25, 30, 40, what is the 25th percentile by the linear rule?

Chapter 3

Spread: Standard Deviation and IQR

Measure how far the data scatters, and watch one outlier inflate the standard deviation

Two teams both average 50 points a sprint. One delivers 48 to 52 every time. The other swings from 10 to 90. A center cannot tell them apart. You need a spread, a number for how far the values scatter.

Build the standard deviation in steps. Call the distance of value xi from the mean x̄ its deviation. Square each deviation so that signs cannot cancel. Average the squares, then take the square root to get back to the data's units.

Say it aloud

s equals the square root of the sum over i of x-i minus x-bar, squared, divided by n minus one.

s
s the sample standard deviation, in the data's units.
√
the square root of undoes the squaring, so s is in points, not squared points.
Σi
the sum over i one term per value, i from 1 to n.
(xi − x̄)²
x-i minus x-bar, squared the squared deviation of value i from the mean x-bar.
n − 1
n minus one the count minus one. This is Bessel's correction: x-bar came from the same data, so the squares run a little small.
In plain words

Find the mean x-bar. Subtract it from each value x-i and square the result. Add the squares, divide by n minus one, and take the square root.

With numbers

Quiz scores 2, 4, 4, 6, 9 have x-bar = 5. The deviations are −3, −1, −1, 1, 4, and their squares 9, 1, 1, 1, 16 sum to 28. So s = √(28 / 4) = 2.65 points. Divide by n = 5 instead and you get 2.37.

numpy's std divides by n unless you pass ddof=1. pandas divides by n − 1. Say which one you used.

Push one value into the tail

Seven values from 20 to 32. Purple is the mean plus or minus one standard deviation. Blue is the IQR. Drag the top value out and compare how far each bar stretches.

32

Made-up values. Quartiles use the linear rule from Chapter 2.

SpreadTop value 32Top value 120
Range12100
Standard deviation s4.3236.07
IQR66
MAD44

The median absolute deviation (MAD) is the median of the distances from the median. Like the IQR, it ignores the tail. The outlier's squared deviation, about 6,631, is 85% of the total of 7,806. That is why s grows more than eight times.

Symptom: "mean ± s" gives an impossible value. For the tickets of Chapter 0, 15.9 − 36.6 = −20.7 minutes. Measure: check whether the mean minus s falls below the smallest possible value. Fix: report the median and IQR, plus a tail percentile.

The values 20, 22, 24, 26, 28, 30, 32 have s = 4.3 and IQR = 6. You replace the 32 with 120. What happens?

Chapter 4

The ECDF: The Whole Shape, No Bins

Draw a distribution as a staircase that no setting can change

A histogram's story changes with its bin width. Make the bins wide and two humps merge into one. Make them narrow and noise grows spikes. One picture of a distribution has no knob at all.

The cumulative distribution function (CDF) at a threshold x is the share of the data at or below x. The empirical CDF (ECDF) is the CDF of the sample you have. Call the number of values n.

Say it aloud

F-hat of x equals one over n, times the count of i such that x-i is at most x.

F̂(x)
F-hat of x the ECDF at threshold x: a share from 0 to 1. The hat means "from the sample".
1/n
one over n turns a count into a share.
#{ i : … }
the count of i such that how many values meet the rule after the colon.
xi ≤ x
x-i is at most x value i sits at or below the threshold.
In plain words

Pick a threshold x. Count the values x-i at or below it and divide by n. Sweep x from left to right and you draw a staircase that climbs 1/n at each value.

With numbers

Task times 1, 2, 2, 3, 4, 4, 6 and 10 seconds give n = 8, so each step is 0.125. At x = 4 the count is 6, so F-hat = 6 / 8 = 0.75. The value 2 appears twice, so the staircase jumps 0.25 there.

Change the bins, keep the staircase

Top: a histogram of 60 task times. Bottom: their ECDF. Drag the bin width and watch the histogram change its story. Then drag the threshold to read the staircase.

3 s
35 s

60 made-up values from two clusters, drawn once with a fixed seed. The bin slider never changes the ECDF.

Read percentiles off the staircase. Go up to height 0.5 and read across: that x is the median. Height 0.9 gives p90. Read the other way to answer "what share is under my 200 ms target?".

The staircase and the linear rule can differ by one step. On the task times, the staircase first reaches 0.75 at 4 seconds, while the linear p75 is 4.5. Both follow a stated rule.

The survival function, 1 − F-hat, is the share above x. At x = 6 it is 1 − 0.875 = 0.125: one slow task. For a long tail, plot it on a log axis so the top 1% stops hiding against the ceiling. Chapter 7 uses it.

Symptom: two people plot the same data and one sees one hump, the other two. Measure: plot the ECDF and look for a flat step in the middle. Fix: read the ECDF first, then pick a bin width that agrees with it.

For the values 1, 2, 2, 3, 4, 4, 6, 10, what is the ECDF at x = 4?

Chapter 5

Box Plots: Five Numbers and a Fence

Squeeze a distribution into five numbers and let a fixed rule flag the outliers

You must compare 200 build pipelines on one screen. 200 histograms will not fit. A box plot draws each pipeline with five numbers and one rule.

The five-number summary is the min, Q1, the median, Q3 and the max. The box runs from Q1 to Q3, so its length is the IQR. A line inside marks the median. The whiskers reach out to the last data points that are not outliers.

Where do the whiskers stop? John Tukey's rule puts a fence beyond each quartile, a fixed number of IQRs out. Call that number k.

Say it aloud

The upper fence equals Q-three plus k times the I-Q-R.

upper fence
upper fence the line above which a point counts as an outlier, in minutes. The lower fence mirrors it below Q1.
Q3
Q-three the 75th percentile.
k
k the multiplier: 1.5 by default, 3 for "far out" points.
IQR
I-Q-R the interquartile range, Q3 minus Q1.
In plain words

Compute Q1, Q3 and the IQR. Add k times the IQR to Q3 for the upper fence, and subtract it from Q1 for the lower fence. A point beyond a fence is an outlier dot, and the whisker stops at the last point inside.

With numbers

Build times 4, 7, 8, 9, 10, 11, 12, 13, 15 and 40 minutes give Q1 = 8.25, Q3 = 12.75 and IQR = 4.5. With k = 1.5 the upper fence is 12.75 + 6.75 = 19.5. So 40 is an outlier, and the whisker stops at 15.

Drag a build past the fence

Ten build times and their box plot. The dashed lines are the fences. Drag the slowest build and watch it become an outlier dot as it crosses the upper fence.

40 min

Made-up build times. Quartiles use the linear rule from Chapter 2.

Why 1.5? For normally distributed data the fences sit 2.70 standard deviations from the center, so about 0.7% of points fall outside. A flagged point is rare, but the rule is not paranoid.

Read a box plot in three looks. A median line close to Q1 means a right tail. A long upper whisker means the same. The dots tell you how many outliers there are and how far out they sit.

Symptom: a box plot of 100,000 requests shows thousands of outlier dots. Measure: even normal data puts 0.7% outside, which is 700 dots here, and skewed data puts more. Fix: treat the dots as flags to inspect, and read tail percentiles for the tail. The box has a blind spot too: it knows five numbers, so it cannot see a second hump.

Build times give Q1 = 8.25, Q3 = 12.75 and IQR = 4.5. Where does the upper whisker end, and is 40 an outlier?

Chapter 6

Violins and KDE: The Hump a Box Hides

Smooth the data into a density and find the second group a box plot flattens

Task times come from two groups: cache hits near 12 seconds and cache misses near 42. Here are ten of them: 10, 11, 12, 12, 13, 40, 41, 42, 42 and 43 seconds.

Q1 = 12, the median is 26.5 and Q3 = 41.75. The box plot draws one fat box with its median line in the gap. The mean, 26.6, sits there too. No task took between 14 and 39 seconds.

A violin plot draws a smooth density curve, mirrored, so its width shows where the data piles up. The curve is a kernel density estimate (KDE): put a small bell curve on each point and add the bells. Call the bell's width the bandwidth h and the bell shape the kernel K.

Say it aloud

f-hat of x equals one over n h, times the sum over i of K of x minus x-i, over h.

f̂(x)
f-hat of x the estimated density at x: the height of the curve.
1/(n h)
one over n h scales the curve so its total area is 1. n is the count, h the bandwidth in seconds.
Σi
the sum over i one bell per data point.
K
K the kernel: here the standard normal bell, 0.399 high at its center.
(x − xi) / h
x minus x-i, over h how many bandwidths x sits from point i.
In plain words

For each point x-i, measure how far x is from it in units of h. Read the bell's height K at that distance. Add the heights and divide by n times h.

With numbers

With made-up points 1, 2 and 4 and h = 1, take x = 2. The distances are 1, 0 and −2, with bell heights 0.242, 0.399 and 0.054. So f-hat(2) = 0.695 / 3 = 0.232.

Pull one cluster into two

The same 40 points as a box plot (left) and a violin (right). Drag the separation to split them. Then widen the bandwidth until the two humps melt.

24 s
3 s

40 made-up points in two equal clusters, drawn once with a fixed seed. The violin uses a normal kernel.

The bandwidth is the violin's knob, as the bin width is the histogram's. On the ten task times, h = 8 still shows two humps: the curve at 26.5 is a third the height of the peak at 12. At h = 15 the humps merge and the violin lies too.

Symptom: a "typical session length" that no user has. Measure: plot a violin at two bandwidths beside the ECDF, and look for a flat step in the middle. Fix: split the data into its groups and summarize each one.

The values are 10, 11, 12, 12, 13, 40, 41, 42, 42, 43, with median 26.5. Why does a box plot mislead here?

Chapter 7

Heavy Tails: When the Rare Dominates

Report a tail without letting it hijack the center or vanish from view

A robot runs ten missions. Its position error per mission, in meters, is 0.28, 0.29, 0.30, 0.30, 0.31, 0.32, 0.33, 0.34, 0.35 and one 4.10.

A distribution has right skew when a long tail stretches toward large values. It is heavy-tailed when huge values turn up far more often than a bell curve allows. Latency, file sizes and failure errors are often both.

SummaryValue (m)What it tells you
Mean0.6922.2 times the median: the failure hijacks it.
Median0.315The typical mission. It hides the failure.
IQR0.0375The middle half is tight: 0.300 to 0.3375.
Upper fence0.394The 4.10 run is far beyond it.
p900.725Already pulled up by the one failure.
p952.41Mostly the failure, by interpolation.

Quote the mean and the robot looks twice as bad as a typical mission. Quote the median and nobody learns that one mission failed. So report three things: the median for the typical run, a tail number for the bad case, and the plot. Here that is median 0.315 m, p95 2.41 m, and one flagged run at 4.10 m.

Grow the failure

Left: the box plot with the mean (warm) and the median (blue). Right: the ECDF or the survival curve. Both use a log axis. Drag the failure and watch which marks move.

4.10 m

Made-up mission errors. The log axis gives 0.2 m and 12 m the same room per factor of ten.

Tail percentiles on ten runs are fragile. The p95 has h = 9 × 0.95 = 8.55, so it walks 55% of the way from 0.35 to 4.10, which gives 2.41. Move the failure and p95 moves with it. The survival curve shows why: it sits at 0.1 all the way from 0.35 m to the failure.

Symptom: a report says "average error 0.69 m". Measure: compute the median, p95 and the count beyond the fence. Fix: report all three, and open the failed run's log.

The errors have mean 0.692 m and median 0.315 m, with one 4.10 m failure. Which summary is honest?

Chapter 8

The Distribution Detective

Damage one dataset in three ways and see which summaries lie each time

Each summary so far fails under one kind of damage. Put them all on one screen, damage the data, and watch which ones move.

Damage the data

A histogram, a box plot and an ECDF of ten values. The mean (warm), median (blue) and p90 (yellow) run through all three. Pick a state and read the verdict.

Clean, one outlier and two clusters are the worked sets in the table below. We made up the long-tail set for this device.

StateMeanMediansIQRValues within 3 of the median
Clean: 20, 22, 23 … 29, 3125.525.53.374.56
One outlier: 31 becomes 20042.425.555.444.56
Two clusters: 10 … 13 and 40 … 4326.626.515.8529.750

The trap is the two-cluster row. The mean and median agree, 26.6 and 26.5, which looks healthy. Agreement rules out strong skew. It does not rule out two humps, and zero values sit near that agreed center.

So the order of work is fixed:

  1. Look at the shape first: the ECDF, or a violin.
  2. Pick the center and spread that fit. One symmetric hump: mean and s. Skew: median and IQR. Two humps: one summary per group.
  3. Add a tail percentile if the tail carries the risk.
  4. Flag outliers with the fence and inspect each one.

Symptom: a team checks "mean equals median" and ships. Measure: count the values within a small distance of the median. Fix: if that count is near zero, plot the ECDF before you report anything.

Mean and median: clean 25.5 and 25.5, one outlier 42.4 and 25.5, two clusters 26.6 and 26.5. What does the two-cluster state teach?

Chapter 9

The Field Guide

Keep the terms, the checklist and the code in one place

Every summary throws information away to fit a report. The skill is to know what each one throws away, and so when it lies.

QuantityDefinitionWhen it lies
MeanTotal / count; least total squared distanceSkew or outliers pull it toward the tail
Median50th percentile; least total distanceHides the tail; strands between two humps
ModeMost frequent valueSeveral values tie when there are two humps
Percentile ph = (n − 1) × p, then interpolateDepends on the convention for small n
Standard deviationRoot of the mean squared deviationOne outlier inflates it; assumes symmetry
IQR and MADQ3 − Q1; median distance from the medianBlind to the tail by design
ECDFShare of values at or below xNever, but less familiar to readers
Box plotFive numbers plus the 1.5 IQR fenceCannot see a second hump
Violin (KDE)Sum of bells, one per pointA wide bandwidth melts two humps
Survival1 − ECDF: share above xUseful only when the tail is the story

Checklist

The core, in code

pythonimport math

def mean(xs):   return sum(xs) / len(xs)

def quantile(xs, p):                       # numpy's default "linear" rule, p in [0, 1]
    s = sorted(xs); h = (len(s) - 1) * p
    k = int(h); f = h - k
    return s[k] if f == 0 else s[k] + f * (s[k + 1] - s[k])

def median(xs): return quantile(xs, 0.5)

def std(xs, ddof=1):
    m = mean(xs)
    return math.sqrt(sum((x - m) ** 2 for x in xs) / (len(xs) - ddof))

def box(xs, k=1.5):
    q1, q3 = quantile(xs, .25), quantile(xs, .75); iqr = q3 - q1
    lo, hi = q1 - k * iqr, q3 + k * iqr
    inside = [x for x in xs if lo <= x <= hi]
    return dict(q1=q1, med=median(xs), q3=q3, whiskers=(min(inside), max(inside)),
                outliers=[x for x in xs if x < lo or x > hi])

def ecdf(xs, x): return sum(v <= x for v in xs) / len(xs)

def kde(xs, x, h):                          # normal kernel
    K = lambda u: math.exp(-u * u / 2) / math.sqrt(2 * math.pi)
    return sum(K((x - v) / h) for v in xs) / (len(xs) * h)

r = [0.30, 0.32, 0.28, 0.35, 0.31, 0.29, 0.33, 0.30, 0.34, 4.10]
print(mean(r), median(r), quantile(r, .95), box(r)["outliers"])   # 0.692 0.315 2.4125 [4.1]
# library: np.mean, np.median, np.percentile(r, [90, 95]), scipy.stats.iqr, scipy.stats.ecdf, scipy.stats.gaussian_kde

Keep going

Sources

John W. Tukey, Exploratory Data Analysis (1977), the source of the box plot and its fences. Rob J. Hyndman and Yanan Fan, "Sample Quantiles in Statistical Packages", The American Statistician (1996), the nine quantile definitions. The numpy percentile documentation lists its methods. We made up every dataset on this page for teaching.

The takeaway. The mean lies on skew, the median hides the tail, and the box plot cannot see two humps. Look at the shape first, then pick the summary that survives it, and add a tail number when the tail is the risk.
Which claim can none of this lesson's tools support, however carefully you compute?

Now press Present or Teach. Explain from memory why the median ignores the founder, how to compute Q1 by hand, and which summary lies under each damage. Then go back to the hero and pull the slow ticket out again.

Summarizing Distributions
The Statistics of Evaluation · Plots That Tell the Truth · Back to Gleams