Stage I · Bachelor's: Foundations
Part 1 of 65The Shape of Data
What can you know about what you cannot see, from what you can?
In 1662 John Graunt reads London's Bills of Mortality and estimates what nobody had counted: the city's growth by migration, the surplus of boys, a table of how long Londoners lived. The part then builds the series' laboratory, the World, a simulated population of one million whose truth is known, and looks at samples from it before any probability. Histograms come first; the mean and the median turn out to be the minimizers of squared and absolute loss, and squares win because of Pythagoras. Quantiles, heavy tails, QQ plots and the Box-Cox family describe shape, and correlation is the cosine of an angle between centred vectors. Then the summaries fail: Anscombe's quartet and an annealed cloud share their statistics, the World's clinic reverses under aggregation, and a chart can lie by its axis. The part ends with twenty samples of a hundred heights whose averages all differ: every statistic is random.
What you need. School algebra and a first look at derivatives. Nothing from the series.
- Hook
- Graunt's bills, 1662
- Mathematics
- summaries as loss minimizers, ECDF, QQ, transformations, correlation as a cosine, Anscombe, Simpson
- Built
- the World; a same-statistics morph
What you will be able to do
Bachelor's
- Compute the mean, median, SD, MAD, IQR and five-number summary of a sample, and say which of them one extreme value can move.
- Read a histogram, a box plot and a QQ plot, and say what a bend in a QQ plot means.
- Explain why two samples from the same population give different averages.
Master's
- Derive the mean and the median as minimizers of squared and absolute loss, and prove the Pythagorean decomposition of a sum of squares.
- Derive the Box-Cox family's limit at lambda = 0 and choose lambda by its profile log-likelihood.
PhD
- State which moments a Pareto tail of exponent alpha has, and explain why the sample skewness of the World's incomes cannot settle as n grows.
Practice
- Diagnose a misleading chart by its lie factor, its axis and its encoding, and redraw it honestly.
- Report group and aggregate rates together, and say which comparison the question needs when they disagree.
Contents
Each chapter has a home level. Choose a track to see what to read and watch: Bachelor's 51 min · Master's 64 min · PhD 64 min · Practice 56 min.
- 0Graunt's questionBachelor's4 min
- 1Populations and samplesBachelor's4 min
- 2Building the WorldBachelor's4 min
- 3Pictures firstBachelor's4 min
- 4The centre as an optimizationBachelor's5 min
- 5Spread, and why squaresBachelor's5 min
- 6Quantiles and the box plotBachelor's4 min
- 7Shape: skew, tails and power lawsMaster's5 min
- 8The QQ plotBachelor's4 min
- 9TransformationsMaster's4 min
- 10Two variables: correlation as a cosineBachelor's4 min
- 11Same statistics, different picturesBachelor's3 min
- 12The trap of aggregationBachelor's4 min
- 13Honest picturesPractice5 min
- 14The sample is randomBachelor's3 min
- Recap, problems, and the road aheadAll tracks3 min
Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · Build the film.
Lecture
The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film. A dashed box stands for a number the film computes when it is rendered (hover over it to see what is computed); the README's figures for each chapter, where it lists them, follow the chapter's text.
Graunt's questionBachelor's4 min
In 1662 a London haberdasher named John Graunt published a short book about lists of the dead. Every week, the parish clerks of London printed a Bill of Mortality: how many people were buried, and of what, and how many children were christened. Readers used them especially as warnings of when the plague was coming. Here are those numbers, year by year, from 1629 to 1710. Christenings in blue, burials in red. And here is 1665, the Great Plague: burials in one year, of them from plague, three years after Graunt's book. Graunt had read decades of these lists, and he asked a question nobody had asked of them: what do the dead tell us about the living?
Nobody had ever counted London. There was no census, and there wouldn't be one for another hundred and forty years. But Graunt reasoned from the Bills. In almost every year, more people were buried than were christened: in the years he could read, about more each year. And yet London was growing, visibly, street by street. So people must have been arriving from the countryside, year after year, faster than the city's own deaths could thin it. A fact about the living, read from a list of the dead. He noticed something else. In every one of these eighty-two years, more boys were christened than girls. Graunt put it as fourteen boys for every thirteen girls, a ratio of one point oh seven seven. The Bills of his years give . Forty-eight years later John Arbuthnot asked whether a fair coin could produce eighty-two years like that. His answer was the first significance test, and we'll run it ourselves in Part 10.
Graunt went further. He wanted to know how long Londoners lived, and the Bills didn't record ages at all. So he estimated. The Bills did record deaths from the diseases of infancy: thrush, convulsions, teeth, rickets. From those he estimated that of every hundred children conceived, thirty-six died before the age of six. For the rest of life he assumed a steady loss, decade after decade: sixty-four alive at six, forty at sixteen, twenty-five at twenty-six, sixteen at thirty-six, and on down to one at seventy-six. It's rough, and the second half is an assumption, not a measurement. But it's a pioneering life table: an ancestor of every survival curve in medicine and every insurance premium. Its modern descendant, the Kaplan–Meier curve, arrives in Part 40.
That leap, from what was written down to what was never counted, is the whole subject. What can we know about what we cannot see, from what we can? And the half that turns it into a science: how often will we be wrong? This series is an education in that question, from a first course to a PhD, in sixty-five parts. The first two stages are a bachelor's degree: data, probability, estimation, testing, and the everyday methods, from regression to surveys. The third is a master's: the modern toolkit, from mixed models and Bayesian computation to causal inference. The fourth is the theory a PhD student is examined on, and the fifth is research, ending with a dissertation. We start where Graunt started: with data, and the shapes it makes.
What it establishes: Graunt (1662): the Bills of Mortality; burials exceed christenings, so London grows by migration; the male surplus (Graunt's 14 to 13); Graunt’s pioneering life table. The series' question, the five stages, Part 1's objectives.; Computed or shown: Christenings, burials and plague deaths 1629–1710 (Arbuthnot 1710; Creighton); the 1665 plague (97,306 burials, 68,596 of plague); the sex ratio of Graunt's years (1.076); Graunt's table of 100 conceived.
1Populations and samplesBachelor's4 min
Every statistical question has two sides. On one side is the population: everyone we want to know about. Here it's the World's adults; we'll build the World in the next chapter. A number that describes the whole population, like the average height of all of them, is a parameter. We'll write it theta, and it's always gold. Here it's centimetres. On the other side is the sample: the few we actually measure. Here, twenty-five adults chosen at random. A number computed from the sample is a statistic. When it's meant to estimate a parameter we write it theta hat, and it's always blue. The average of these twenty-five is . The sample's average is not the population's. It missed by of a centimetre. That gap, theta hat minus theta, is the error, and in one way or another the rest of the series is about it.
Now the part that makes it hard. In real life you never see the population. Graunt never saw London's living. A pollster never hears every voter, and a drug trial never treats every future patient. So the gold line is gone. All you have is the sample, and its average. You can't know the error, because knowing it would mean knowing theta. But you can know something nearly as useful: how big errors like this tend to be. Draw a different twenty-five and you'd get a different average. If you knew how those averages scatter around theta, you could say how far from theta your one average is likely to be. That scatter is the subject of Parts 6 and 8, and at the end of this part we'll watch it happen.
That's what statistics promises: not the answer, but an honest statement of how often you'll be wrong. The classic form is an interval: a range computed from the sample, built so that it captures theta in, say, ninety-five percent of samples. Here are twenty samples, each with a normal-approximation interval targeting that rate. Its actual coverage is something to check, not assume. of these twenty catch the gold line; the red ones miss. A promise like ninety-five percent can be checked, but only if you know the truth. So the series keeps a scoreboard, the Coverage Board. Every interval and every test we meet will be run thousands of times on a population whose truth we know, and the board records whether the promise was kept. Right now it's empty. The first rows arrive in Part 8, and some of them will be red: textbook methods that don't do what they say.
One convention runs through the whole series: colour is meaning. Gold is the truth: a parameter, a population. Blue is an estimate: a statistic, a fitted line. White is data. Red is a deviation or an error. Grey is a null hypothesis, and teal its alternative. Purple, green and orange are Bayes's prior, likelihood and posterior. Whenever you see gold, you're looking at something that, in real life, nobody gets to see.
What it establishes: Population and parameter (θ, gold); sample and statistic (θ̂, blue); the error θ̂ − θ; in real life θ is hidden; the 95% promise and the empty Coverage Board; colour is meaning.; Computed or shown: One sample of 25 adult heights against the World's mean (169.50 cm); twenty normal-approximation intervals targeting 95%, 18 covering.
2Building the WorldBachelor's4 min
Statistics has a teaching problem. Its methods promise things about the truth, and in real data the truth is never available to check them against. So we're going to build a population whose truth we do know. We'll call it the World. It's an island of two hundred towns in ten regions, with residents. A few towns are cities; the largest has people, the smallest , the way real settlements follow a power law. Every resident is a row of numbers: age, sex, height, income, and, as the series goes on, a school, a clinic, a vote, a lifetime, a genome. Because we generated every one of those numbers, every parameter is something we can compute exactly, and every method in the series can be graded against it, not just applied.
Who lives there? Here's the World's age pyramid: men to the left, women to the right, five-year bands, a slowly ageing population like most rich countries today. Their heights: men average centimetres and women , drawn from bell curves, though as we'll see the mixture of the two isn't quite one. Their incomes look nothing like a bell. Most people earn modest amounts, and a long tail stretches far to the right: the richest adult makes a year. That tail drags the mean, , well above the median, , which is the income of the person exactly in the middle. Which of the two is the typical income is a question we'll answer properly in chapter four.
So here is something you can never write in real life: the truth. The mean adult height in the World is centimetres, and its standard deviation . The median income is , the mean , and the top one percent of earners take percent of all income. These aren't estimates. Each is computed from every adult in the World: the population is finite, and these are its exact values. When a sample's average comes out at one hundred and sixty-eight point six, we'll know precisely how wrong it is. The World grows as the series does. Families arrive in Part 5, schools in Part 25, surveys whose respondents aren't random, a clinic whose doctors treat the sickest patients (you'll visit it in chapter twelve), lifetimes, a pollution field, a genome. Each block is added without changing anything already there.
Two promises about the World itself. It's reproducible. Everything comes from one seed, sixteen sixty-two, after Graunt's book, so the same World is rebuilt on any computer. And it's stable. Each block, geography, ages, heights, incomes, draws from its own random stream, derived from the seed and the block's name. So when a later part adds a new block, nothing already in the World changes: a number shown in Part 1 is still true in Part 40. And one honest caveat. The World is simulated. It's a laboratory for learning how methods behave, not evidence about real people. For that, the series keeps a museum of real historical data, like Graunt's Bills, each with its source on screen.
What it establishes: Why build a world; the island of 200 towns in 10 regions; ages, heights, incomes; the truth table; reproducibility and stability (one random stream per block); the World teaches about methods, the Museum about history.; Computed or shown: Town populations (Zipf); the age pyramid; heights (men 176.0, women 163.0); incomes (median 38,910, mean 49,484, top 1% share 6.8%).
3Pictures firstBachelor's4 min
Before any formula, look. Tukey, who did more than anyone to make statisticians look at their data, put it this way: the greatest value of a picture is when it forces us to notice what we never expected to see. Here are sixty adults from the World, drawn at random, each placed at their height, rounded to the nearest centimetre. Where two people share a height they stack. Already you can see things: a crowd in the middle, thinning out to either side; nobody below about one hundred and fifty, almost nobody above one hundred and ninety. This is a dot plot, and for a few dozen numbers it's the most honest picture there is: nothing is hidden, nothing is averaged away.
With more data, dots pile into towers too tall to read, so we group them. Cut the line into bins five centimetres wide, and replace each bin's dots by a bar as tall as their count. That's a histogram: the oldest picture of a distribution, named in the 1890s by Karl Pearson. Here's the whole sample of . The shape is clearer now: one peak, roughly symmetric, falling away on both sides. But we made a choice to get this picture, the width of the bins, and that choice is not innocent.
First, a better vertical scale. Instead of counts, make each bar's height the proportion of the data in the bin divided by the bin's width. Then a bar's area is its proportion: this bar holds of the people, a proportion of , and that's its area. The areas of all the bars add up to one. This is the density scale, and it makes histograms with different bins, or different sample sizes, comparable. It's also the first glimpse of an idea that runs through the whole series: probability as area.
Now let the bin width move. At one centimetre, the histogram is all spikes. Every accident of who happened to be sampled shows up as a tower or a gap, and you can't see the shape for the noise. At fifteen centimetres it's a few crude blocks: the noise is gone, and so is the shape. Somewhere between is a width that shows the distribution rather than the sample, or the bins. The same two hundred numbers, three different stories. This is a trade-off between variance and bias: narrow bins follow the noise; wide bins blur the truth. It's the first appearance of the most important trade-off in statistics, and Part 29 will solve it exactly.
There are rules of thumb for the width. Sturges, in 1926, chose the number of bins as the logarithm of n to base two, plus one: bins here, each about centimetres. Scott, in 1979, and Freedman and Diaconis, two years later, derived widths from the data's spread, its standard deviation or its interquartile range, times n to the minus one third: and centimetres. That curious power, minus one third, comes from balancing the two kinds of error, and we'll derive it. And because this sample came from the World, we can do what's impossible in real life: lay the whole population's histogram, in one-centimetre bins, over the picture. Here it is in gold, with the bin centres joined. The histogram of two hundred people estimates this shape, and you can see both how good it is and where chance pushed it around.
What it establishes: Tukey; dot plots; histograms (Pearson's name); the density scale (area = proportion); bin width as a variance–bias choice; Sturges, Scott, Freedman–Diaconis; the population laid over the sample.; Computed or shown: 200 adult heights; bin widths 5.45, 6.37, 6.07 cm; the full population’s histogram in 1 cm bins.
4The centre as an optimizationBachelor's5 min
If you had to replace nine numbers by one, which would you choose? Here are nine incomes from the World, in thousands, each in its own lane. Pick a candidate centre, c, and measure how far it is from each income. Legendre's answer, in 1805, and Gauss's, was to square those distances and add them up, and choose the c that makes the total as small as possible. Slide c, and watch the total. It falls, reaches a bottom, and rises again. Where is the bottom? Differentiate: the derivative is minus twice the sum of the deviations. Set it to zero, and c must be the ordinary average. The mean is the answer to an optimization problem. Here it's thousand. And notice where it sits: to the right of seven of the nine people, pulled there by one large income.
Now change the loss. Instead of squared distances, add up the plain distances, the absolute values. Laplace preferred this one. Its derivative is easy to read off the picture: every income to the left of c pulls the total up as c moves right, one unit per unit, and every income to the right pulls it down. Away from an observation, the slope is the number on the left minus the number on the right. At an observation the two one-sided slopes can differ. It's a tug of war. The total keeps falling while more people are on the right, and reaches a minimum when neither side holds more than half: at the middle observation, the median, thousand. The median doesn't care how far away people are, only which side they're on. Make the richest person three times richer, and the median doesn't move. The mean does.
Squares and absolute values are two members of one family. Raise the distances to a power p at least one, add them up, and minimize. p equals one gives the median; p equals two gives the mean. Here's the whole family on two hundred incomes. Start at p equals one, at the median, thousand. As p grows, far-away incomes count for more and more, and the centre is dragged toward them: at p equals two, and then far past anything typical. As p goes to infinity only the two most extreme incomes matter, and the centre becomes the midrange, halfway between the smallest and the largest: thousand, an income almost nobody has. The choice of a centre is a choice of a loss: how much do you mind being far from the people who are far away?
The mode answers a different question: which value occurs most often? It minimizes the number of exact mismatches. For continuously measured heights, exact repeats are rare, so that rule alone gives no useful unique centre. Instead, choose a window and find where it holds the most observations. Here a five-centimetre window is most crowded at centimetres. Change the window width, and the answer can change, just as changing histogram bins changes the picture. A mode estimate needs a scale as well as data.
Seeing the mean as a minimum pays off immediately. Here are six bedtimes, from twenty to eleven at night to half past one in the morning. What's the average bedtime? Write them as hours after midnight and average the numbers, and you get :: about noon. That's absurd: nobody here goes to bed at noon. The numbers wrapped around midnight, and the formula didn't know. But the mean was never really the formula; it was the point that minimizes the total squared distance. On a clock, distance is the distance around the circle. Minimize that, and the centre is : pm, two minutes before midnight. This is the Fréchet mean, after Maurice Fréchet, and it works for anything you can measure distances between: directions, shapes, networks, whole probability distributions. We'll meet it again in Part 61.
What it establishes: The mean minimizes Σ(xᵢ − c)² (derived); the median minimizes Σ|xᵢ − c| (the tug of war); the median ignores distance, the mean does not; the Lᵖ family from median (p = 1) to midrange (p = ∞), and the mode as a count or window optimum; the Fréchet mean on a clock.; Computed or shown: Nine incomes (mean 52.8k, median 36.4k); Lᵖ centres of 200 incomes (41.7 → 185.1k; midrange 201.4k); the mode window; six bedtimes (arithmetic mean 11:58 am, Fréchet mean 11:58 pm).
5Spread, and why squaresBachelor's5 min
A centre isn't enough. Two towns can have the same average height, one where everyone is close to it and one where nobody is. We need a number for spread. Here are seven heights and their mean, . Each person's deviation is their distance from the mean, with a sign: positive above, negative below. The deviations always add up to zero; that's what made the mean the balance point. So their average tells us nothing. Instead, square each one. Literally: turn each deviation into a square whose side is the deviation. The variance is the average area of these squares, square centimetres. Its square root, the side of the average square, is the standard deviation: centimetres. It's in the data's own units, and it's the most used measure of spread there is.
Why squares, rather than absolute values? Because squares are geometry. Take a sample of three heights. Three numbers are one point in three-dimensional space: person one along this axis, person two along that one, person three up. Subtract any candidate centre c from all three, and you get this white vector. The diagonal line is every point whose three coordinates are equal: every way of replacing the sample by one number. Now drop a perpendicular from the white point onto the diagonal. The foot is exactly the mean, repeated three times: the mean is the projection of the data onto the diagonal. What's left, the deviations from the mean, is the red vector, at right angles to the diagonal. So Pythagoras applies. The squared distance from the data to any centre equals the squared deviations from the mean, plus n times the squared distance from the mean to that centre. That one identity says three things at once: that the mean minimizes the sum of squares, which we found in the last chapter; that spread around any point splits into spread around the mean plus an offset; and, when we come to regression and the analysis of variance, that sums of squares can be cut into pieces. Absolute values have no Pythagoras. That's why squares won.
Squares have a cost, though: they magnify big deviations. Two other measures of spread don't. The MAD is the median of the absolute deviations from the median. The interquartile range is the width of the middle half of the data. Each is scaled by a constant so that, for a normal distribution, all three agree. For the World's heights they nearly do: , and centimetres. The heights are close to a bell, a slightly flattened one, because men and women are mixed. For incomes, they don't. The standard deviation is ; the robust measures say about and . The standard deviation is more than twice as big, because a few enormous incomes, squared, dominate it. Neither answer is wrong. They're answers to different questions, and Part 30 is about choosing between them when some of the data are bad.
How much of the data does a standard deviation describe? Chebyshev proved a guarantee in 1867 that holds for every distribution with a variance at all: at least one minus one over k squared of it lies within k standard deviations of the mean. Three quarters within two standard deviations; eight ninths within three. For the World's heights, the truth is far better: percent within two standard deviations, and percent within three. Even the incomes beat the guarantee: percent within two, though for a strange reason: their standard deviation is so inflated by the tail that two of them reach most of the way to the rich. Chebyshev's bound is a guarantee, not a description. Its virtue is that it never fails. We'll prove it in two lines in Part 6, and it's the ancestor of the concentration inequalities that run all the way into the PhD stages.
What it establishes: Deviations sum to zero; variance as the average square; SD as its side; Pythagoras in R³: Σ(x − c)² = Σ(x − x̄)² + n(x̄ − c)²; MAD and IQR; Chebyshev's guarantee.; Computed or shown: Seven heights (s = 7.17); three heights in R³; SD/MAD/IQR of heights (9.37/10.18/10.21) and incomes (56,852/22,743/24,707); shares within k SDs.
6Quantiles and the box plotBachelor's4 min
The mean and the standard deviation squeeze a whole distribution into two numbers. Here's a picture that squeezes nothing. Forty incomes from the World, marked along the axis. Now walk from left to right and keep count: at each income you pass, climb by one fortieth. The staircase you trace is the empirical cumulative distribution function. Its height above any income x is the share of the sample earning x or less. At twenty thousand, it's this many; slide along, and it climbs. Every observation is a step, so the staircase contains the data exactly, sorted. And it's the single most important estimator in the series: in Part 6 we'll prove that as the sample grows, this staircase converges to the true distribution, uniformly, everywhere at once. That theorem has been called the fundamental theorem of statistics.
Read the staircase the other way, and you get quantiles. Pick a share, say a half. Go across at height one half until you hit the staircase, then down. The income you land on is the lower median: thousand. Half the sample earns no more than this. At one quarter, the first quartile, ; at three quarters, the third, . And at nine tenths, the ninetieth percentile, . This rule, the smallest x whose share reaches p, is the quantile function: the inverse of the staircase, defined even where the staircase is flat or jumps. Geometrically it's the same staircase reflected in the diagonal, with the axes swapped. Quantiles are how growth charts, exam percentiles and income deciles are reported. Software also uses interpolated quantiles; we'll use that convention for the box plots next. Unlike the mean, quantiles say where a person stands.
Five quantiles make a summary that fits on a line. The minimum, the first quartile, the median, the third quartile and the maximum: a five-number summary. Here the quartiles use linear interpolation between observations, and the median averages the two middle incomes. Tukey drew it as a box from the first to the third quartile, with the median inside: the box holds the middle half of the data, and its width is the interquartile range. Then whiskers reach out to the most extreme points that are within one and a half box widths of the box. Anything beyond, here incomes, is drawn as a separate point, an outlier. Tukey meant it as a flag, not a verdict: a point worth a second look. Here it isn't an error at all. The World's incomes have a long right tail, and these flagged values are simply the tail. A rule built for symmetric data calls the rich outliers.
Box plots are made for comparing groups. Here are three hundred adults from each of the World's ten regions. The medians wander, from to thousand, and it's tempting to rank the regions, and to look for reasons: why is region so much richer than region ? But we know the truth. In the World, as built so far, income doesn't depend on region at all. The gold marks are the ten true regional medians, and they're all essentially the same. Every difference between those boxes is the luck of who was sampled. Learning to tell a real difference from this kind of noise takes up much of the bachelor's degree; Part 10 starts on it properly.
What it establishes: The ECDF; quantiles as its generalized inverse (the reflected staircase); Tukey's five numbers and box plot; outliers as a flag, not a verdict; regional box plots that differ only by chance.; Computed or shown: 40 incomes (ECDF lower median 38.5k; interpolated box-plot median 38.6k, five outliers); 300 incomes in each of 10 regions against the true regional medians.
7Shape: skew, tails and power lawsMaster's5 min
Centre and spread are two numbers. The rest of a distribution's shape takes more. Standardize every value: subtract the mean and divide by the standard deviation, so it's measured in standard deviations from the centre. Then average the cubes. Cubes keep their sign, so deviations to the right and left cancel when the distribution is symmetric, and don't when one side stretches further. That average is the skewness. The World's heights: skewness , very nearly symmetric. Its incomes: . A long tail to the right. Average the fourth powers instead, and subtract three, and you get the excess kurtosis. For years textbooks said it measured peakedness. It doesn't: fourth powers are dominated by the most extreme values, so kurtosis measures the tails, as Westfall argued in 2014. Heights: , lighter tails than a bell curve, because mixing men and women flattens the top. Incomes: .
Those last numbers deserve suspicion. Compute the skewness of incomes on a thousand people, then ten thousand, then a hundred thousand, then everyone. It doesn't settle: , , , . The reason is one person. The richest adult in the World is standard deviations above the mean. Cube that, divide by the number of adults, and that single term is : more than half of the whole skewness comes from one human being. And it's not bad luck. The World's top incomes follow a power law with exponent two point one, and for such a tail the third and fourth moments of the distribution they're drawn from are infinite. The sample skewness is estimating something that doesn't exist, so it can only jump around, dominated by whoever is richest in the sample. A summary is only as good as the thing it summarizes is real.
There's a simple way to tame a tail like this. On an ordinary axis, the incomes are a cliff and a long, thin beach. Every income from a hundred thousand to millions is squeezed into the flat part on the right. Now put income on a logarithmic scale, where each step multiplies by ten. The cliff becomes a hill, and almost a symmetric one: the skewness of the logarithm of income is . On this scale, the median, , sits in the middle of the hill; the mean, , sits to its right, pulled by the tail. A logarithm turns multiplication into addition, and many quantities grow multiplicatively: incomes, populations, prices, the sizes of towns. Their logarithms are often close to bell-shaped. That's the log-normal distribution, which the World's incomes were built from, and which Part 3 derives.
The tail itself has a law. Plot, for each income y, the share of adults earning more than y, with both axes on logarithmic scales. Beyond a hundred thousand or so, the points fall on a straight line. A straight line on log-log axes means a power law: the share earning more than y falls like y to the power minus alpha. Vilfredo Pareto found this in the tax records of several countries in 1896, and it bears his name. The slope of this line is . A better estimator, Hill's, uses only the top incomes and gives . And because this is the World, we can check: the true exponent is . A caution, from Clauset, Shalizi and Newman: a straight-looking line on log-log axes is not proof of a power law; log-normal tails can look straight for a long way. Telling them apart is a problem in testing, and we'll be ready for it in Part 10.
What it establishes: Skewness and kurtosis (tails, not peaks: Westfall 2014); with a Pareto tail of exponent 2.1 the third and fourth moments do not exist, so the sample skewness never settles; the log scale; Pareto's law, the log–log slope and Hill's estimator.; Computed or shown: Skewness 0.11 (heights) and 72 (incomes, 39.9 of it from one adult); skewness at n = 1,000 … 741,311; log-income skewness 0.26; slope −2.18, Hill 2.17, true α = 2.1.
8The QQ plotBachelor's4 min
A histogram tells you a distribution's shape. To ask whether that shape is a particular one, a bell curve for instance, there's a sharper tool. Take fifteen men from the World and sort their heights. Now slice a standard bell curve into fifteen pieces of equal probability, and take the middle of each slice: fifteen normal quantiles, crowded in the centre and spread out in the tails. Pair them up: the smallest height with the smallest normal quantile, the second with the second, and so on, and plot each pair. That's a quantile–quantile plot, introduced in this form by Wilk and Gnanadesikan in 1968. If the data came from a bell curve, the points should lie on a straight line. Here they nearly do.
Why a straight line? Every normal distribution is a standard one, shifted by its mean and stretched by its standard deviation: X equals mu plus sigma Z. So the chance that X is below mu plus sigma z is exactly the chance that Z is below z. Which means the quantiles of X are the quantiles of Z, stretched and shifted: a straight line, whose slope is sigma and whose intercept is mu. So a QQ plot does three things at once. It tests the shape without needing to know the centre or the spread; and if the shape is right, the line's intercept and slope estimate them. And the same argument works for any family that's just one shape shifted and stretched.
In 1846 Adolphe Quetelet, the Belgian astronomer who became a statistician, published the chest measurements of Scottish militiamen and argued that they followed the same curve as errors of astronomical observation. Here is his table, as Stigler corrected it against the original 1817 source: men, in sixteen one-inch classes, as a QQ plot. Each class is one point, sized by how many men it holds. It's very nearly a straight line. Its intercept, inches, is the mean chest, and its slope, , is close to the standard deviation, . Quetelet drew a large conclusion: that nature aims at an average man, and that individuals are errors around him. That idea, l'homme moyen, shaped the next century of statistics, and some of its worst misuses too. The curve is a fact about these measurements. The meaning he gave it was a choice.
When the line bends, the bend tells you how the shape differs. Three hundred of the World's men: straight. Their heights are close to a bell. Three hundred incomes: the points bend upward, more and more steeply on the right. The top incomes are far higher than a bell curve with this centre and spread would ever produce: a long right tail, the skew of the last chapter, seen without computing a single moment. And three hundred draws from a distribution with heavy tails on both sides, Student's t with three degrees of freedom: the points are flat in the middle and bend away at both ends, an S. Extreme values in both directions come more often than a bell allows. The QQ plot is the statistician's most used diagnostic: for residuals of a regression in Part 12, for the assumptions of a test in Part 10, for whether a model's errors behave. It's worth learning to read at a glance.
What it establishes: Building a QQ plot; why a location–scale family gives a straight line (derived); Quetelet's chests; reading the bends: straight, convex (right skew), S-shaped (heavy tails).; Computed or shown: 15 men's heights; Quetelet's 5,732 chests (Stigler's corrected table): intercept 39.85 = mean, slope 2.11 ≈ SD 2.07; QQ plots of men, incomes, t₃.
9TransformationsMaster's4 min
If a logarithm can turn a lopsided distribution into a symmetric one, what about other transformations? In 1964 George Box and David Cox proposed a family with one dial, lambda: y to the lambda, minus one, divided by lambda. At lambda equal to one it's just y minus one: nothing changes but the origin. At a half it's essentially a square root; at minus one, essentially one over y. The subtraction and division are there to make the family continuous. Write y to the lambda as e to the lambda log y, expand in lambda, and as lambda goes to zero the curve becomes the logarithm. So the log isn't a special case bolted on; it's the middle of the family. Turning the dial bends the ruler: lambdas below one compress large values and stretch small ones, pulling in a right tail.
Watch what the dial does to real data. Three hundred World incomes, transformed, then standardized so the pictures are comparable. At lambda equal to one the histogram is the raw income: skewness . Turn lambda down to a half, a square root: the skew drops to . At zero, the logarithm: , nearly symmetric. Go further, to minus a half, and you overshoot: the skew turns negative, , and the long tail is now on the left. There's a best setting, and it's near zero.
Box and Cox didn't choose lambda by eye. They asked: if some transformation makes the data exactly normal, which lambda makes these data most probable? That's maximum likelihood, the workhorse of Parts 9 and 22. The formula has a term you might not expect: lambda minus one times the sum of the log y's. It's a Jacobian. Stretching the ruler stretches the density, and a fair comparison between lambdas has to account for it. Here's the log-likelihood across lambda. Its peak is at lambda hat equals . And the curve says how sure to be: every lambda from to is within the usual margin of the peak,
One more use of a transformation: to make spreads equal. Counts of rare events, like the deaths by horse kick of Part 3, follow a Poisson distribution, whose variance equals its mean. So groups with bigger counts are more spread out. Here are four groups, with means two, eight, thirty-two and a hundred and twenty-eight. Their standard deviations grow: , , , . That breaks methods which assume every group is equally noisy. Take square roots, and the spreads become , , , : all close to a half. Why a half? A transformation g of a variable near its mean changes its variance by the square of g's slope. The slope of the square root at mu is one over two root mu; square it, multiply by the Poisson variance mu, and the mu cancels, leaving one quarter. That's the delta method, and Part 6 proves it.
What it establishes: The Box–Cox family and its λ → 0 limit (derived); the histogram straightening as λ turns; the profile log-likelihood with its Jacobian; variance stabilization by √ for Poisson counts (delta method).; Computed or shown: 300 incomes: skewness at λ = 1, ½, 0, −½; λ̂ = −0.09, likelihood interval −0.21 to 0.02; Poisson SDs 1.38 … 11.04 → 0.62 … 0.49.
10Two variables: correlation as a cosineBachelor's4 min
Now two variables at once. Four hundred families from the World: the mid-parent height, the average of the two parents, with mothers' heights scaled up by eight percent as Galton did, against the height of their grown child. Galton, studying exactly this in 1886, invented the idea we're about to build. Draw a cross through the two means. It cuts the plane into four quadrants. In the top right and bottom left, both are above average or both below: they agree. In the other two they disagree. Here families agree and disagree. To turn that into a number, multiply each family's two deviations. A family that agrees gives a positive product, a rectangle of positive area; one that disagrees, a negative one. Average the products: that's the covariance, square centimetres. Its units are awkward, so divide by both standard deviations. The result, the correlation r, has no units at all. Here it's .
Correlation has a geometric meaning that makes everything about it obvious. Take just three pairs of numbers. As in chapter five, the three x's are one point in three-dimensional space, and so are the three y's. Centre each, by subtracting its mean, and we have two arrows. Write out r: the covariance over the two standard deviations. The one over n's cancel, and what's left is the dot product of the two centred vectors, divided by both their lengths. That's the cosine of the angle between them. Here the angle is degrees, and its cosine is , exactly the correlation of these six numbers. With four hundred families, the vectors live in four hundred dimensions, but there are still just two of them, and the angle between them is still the correlation.
The geometry also proves the most important fact about r: it always lies between minus one and one. The length of u minus t times v can't be negative, whatever t is. Expand it, and it's a quadratic in t. A quadratic that never dips below zero has at most one real root, so its discriminant can't be positive. That's the Cauchy–Schwarz inequality. Divide through, and r is trapped between minus one and one, with equality only when the two arrows point the same way or opposite ways, which means every point lies exactly on a line. A cosine of one is a perfect straight line rising; zero is no linear relation at all; minus one a perfect line falling.
Two warnings about what r is not. It's not the slope. The line that best predicts a child's height from the mid-parent has slope : an inch taller in parents, two thirds of an inch taller in children on average, very close to Galton's own estimate of two thirds. The correlation is . Change the units of one variable and the slope changes; r doesn't. And r depends on the range you look at. Keep only the families whose parents are in the tallest quarter. The slope barely changes, , but the correlation falls to . Nothing about how height is inherited has changed. We've only thrown away most of the spread in x, and r measures how much of the spread in y lines up with the spread in x. Studies of selected groups, like university entrance tests among those admitted, fall into this trap constantly. And neither r nor the slope says anything about cause. That's two chapters and thirty-five parts away.
What it establishes: Quadrants, products, covariance, r; r as the cosine of the angle between centred vectors; −1 ≤ r ≤ 1 by Cauchy–Schwarz (proved); r is not the slope; restriction of range.; Computed or shown: 400 World families (r = 0.46, slope 0.64, Galton's two-thirds); (2, 5, 8) and (3, 3.5, 7.5) at 24.2°, cos = 0.912 = r; the tallest quarter: r = 0.19.
11Same statistics, different picturesBachelor's3 min
Everything so far has been a summary: a centre, a spread, a correlation. Here's what summaries can hide. In 1973 Francis Anscombe published four small datasets, eleven points each. All four have nearly the same means, variances, correlation, and best-fitting line. The published observations are rounded, so the summaries differ slightly in their last digits. As far as these summaries suggest, they're almost the same data. Now look. The first is what you'd imagine: a line with noise. The second is a smooth curve, with no noise at all. The third is a perfect line, except for one point that drags the fit. And in the fourth, x doesn't vary at all, except for a single point that creates the entire correlation by itself. Anscombe's moral was blunt: make both calculations and graphs. Both sorts of output should be studied; each will contribute to understanding.
Anscombe built his four by hand. In 2017 Justin Matejka and George Fitzmaurice showed you can make as many as you like, by computer, from any data. Here are a hundred and forty-two adults from the World: age across, the logarithm of income up, rescaled to a box. On the right, their five summary statistics, computed live from the points on the screen. Watch the points, and then watch the numbers. The cloud is becoming a word, and not one of the five statistics moves in the second decimal place. And from the word to a ring. Same means, same spreads, same correlation. Three completely different datasets that these five summaries call identical. Other summaries, such as quantiles, can distinguish them.
How is it done? With a simple search. Move one point a tiny random step. Keep the move only if all five statistics are unchanged to two decimals, and the point has moved closer to the target shape. Early on, also accept some moves that don't help, at random, so the search doesn't get stuck; that's simulated annealing. Run it a few hundred thousand times and the points settle onto the letters, on average within units of them, and then onto the ring, within . The lesson is geometric. A summary statistic maps a whole dataset to a few numbers, like a shadow cast by a three-dimensional object. Infinitely many different datasets cast the same shadow. So look at the data, not only at its shadow.
What it establishes: Anscombe's quartet; same statistics, different graphs by simulated annealing (Matejka & Fitzmaurice 2017); a summary as a projection.; Computed or shown: The quartet's statistics; 142 World adults annealed into STATS and into a ring, the five statistics read live from every frame (each frame is a real snapshot of the search).
12The trap of aggregationBachelor's4 min
The World has a clinic. Over the years it has seen patients with the same illness. Some were given a new treatment; some weren't. Of those treated, percent recovered. Of those not treated, percent. On these numbers the treatment looks harmful: eleven points worse. Should the clinic stop using it?
Before deciding, look at who was treated. The illness comes in two forms, mild and severe. Split the patients by severity. Among the mild cases, percent of the treated recovered, against percent of the untreated. Among the severe cases, percent against . The treatment is better in each group, by about eight points, and worse when the groups are combined. Nothing is miscounted. Every patient is in exactly one group and in the total. This is Simpson's paradox, described by Yule in 1903 and by Simpson in 1951.
Here's the mechanism. Each group's overall recovery rate is an average of its mild and severe rates, weighted by how many of its patients were mild and how many severe. Draw each group as a segment from its severe rate to its mild rate; the overall rate is a point on the segment, placed by the mix. The treated segment lies entirely to the right of the untreated one at both ends: better for mild patients, better for severe. But the doctors gave the treatment mostly to the sickest. percent of the treated were severe cases, against percent of the untreated. So the treated point slides down toward its severe end, the untreated point toward its mild end, and they cross. The comparison of totals is mostly a comparison of how sick the two groups were.
So is the right answer the one within groups? Here, yes, because of how the data arose. Severity came first: it influenced who got treated, and it influenced who recovered. To compare the treatment fairly, you compare like with like, within severity. But the very same table could arise differently. Suppose the third variable were something the treatment itself changes, say it lowers blood pressure, which is how it helps. Then splitting by blood pressure would compare people after the treatment had already done its work, and the totals would be the fair comparison. The arithmetic is identical in the two stories; only the causal picture differs. Data never tell you on their own which way to slice them. That question has a precise answer, a graph of what causes what, and Part 36 is about it.
Aggregation has a cousin trap. Here are five groups, say five regions. Within every one, y falls as x rises. But compare the regions' averages, and y rises with x. In 1950 the sociologist W. S. Robinson showed that correlations computed across American states between immigration and literacy had nothing like the sign or size of the correlation among the individual people in them. Inferring how individuals behave from how groups behave is the ecological fallacy. A correlation between groups is not a correlation between people.
What it establishes: Better in every group, worse overall; the weighted-average mechanism; which comparison is right depends on the causal story (Part 36); the ecological fallacy (Robinson 1950).; Computed or shown: The World's clinic: 62.4% vs 73.7% overall; 87.2% vs 79.5% (mild), 47.6% vs 39.5% (severe); 63% vs 15% severe.
13Honest picturesPractice5 min
Most of the pictures in this part were invented by one man. William Playfair, a Scottish engineer and pamphleteer, published the first line charts and bar charts in 1786, and the first pie chart fifteen years later. Here is one of his last, from 1821, redrawn from his numbers: the price of a quarter of wheat over two and a half centuries, as bars, and a skilled worker's weekly wage, as a line. Two series on one picture invite a comparison. In the 1590s a week's wages bought about of a quarter of wheat; by the 1780s, about . Playfair's point was that bread had become cheaper relative to labour than ever before, and the picture makes the argument at a glance, which is both the power and the danger of a chart.
Florence Nightingale used a chart as evidence before a royal commission. Each wedge is a month of the Crimean War, and its area is that month's death rate in the British army in the East: blue for preventable disease, red for wounds, grey for everything else. In the first year, soldiers died of disease and of wounds. In the worst month, January 1855, disease alone was killing at an annualized rate of per thousand soldier-years. That is a rate of deaths per exposure time, not a probability of dying within a year. In March 1855 a sanitary commission arrived, cleaned the water and the drains. The second year's rose is drawn to the same scale: deaths from disease. Nightingale chose area, not radius, deliberately: double the radius and the wedge looks four times as bad. She wanted the picture to be true at a glance, and to be unarguable.
And the picture often called the best statistical graphic ever drawn. In 1869 Charles Joseph Minard, a retired French engineer, mapped Napoleon's invasion of Russia in 1812. The band follows the army's route; its width is the number of troops remaining in each column. The main column set out strong. It reached Moscow with . And the grey band is the retreat, through the Russian winter, narrowing to . Six variables on one flat page: the size of the army, its position in two dimensions, its direction, and, in Minard's original, the dates and the temperature during the retreat. Nothing is decorative. Every mark carries data.
Some picture forms are easier to read than others, and this has been measured. Here are five numbers as a pie. Which slice is bigger, B or C? Hard to say. The same five numbers as bars: B is bigger, and you can see by how much. In 1984 William Cleveland and Robert McGill tested how accurately people judge different encodings. Positions along a common scale came first; then lengths; then angles; areas and colours came last. A pie chart asks you to compare angles. A bar chart asks you to compare positions. That's why nearly every chart in this series is a position on an axis.
And the commonest dishonesty of all. Two bars: ninety-eight and a hundred. Start the axis at ninety-seven, and the second bar is three times the height of the first. Start it at zero, and they're nearly equal, which is the truth: a two percent difference. Edward Tufte gave the distortion a number in 1983, the lie factor: the size of the effect shown in the graphic divided by the size of the effect in the data. A bar three times as tall for a value two percent larger has a lie factor of about . A truncated axis isn't always wrong; for a line chart of a slowly changing quantity it's often right. But a bar's length is a claim about an amount, and bars should start at zero.
What it establishes: Playfair's charts; Nightingale's rose (area, not radius); Minard's march; Cleveland & McGill's ranking of encodings; Tufte's lie factor.; Computed or shown: Playfair's wheat and wages (1565–1821); Nightingale's monthly death rates (11,157 disease deaths in the first year); Minard's main column (340,000 → 100,000 → 4,000); a lie factor of 98.
14The sample is randomBachelor's3 min
We've been treating each sample as if it were the data. It is only one of many samples we might have drawn. Here is the World's population, and a machine that draws a hundred adults at random. One sample: its hundred heights land on the line above, and its average, , drops into the chart below. Another hundred: . Another: . Every sample gives a different average, and none of them is exactly the truth. The truth is the gold line, the mean of all adults, . The averages scatter around it.
Keep going. Seventeen more samples, each dropping its average into the chart. It's not only the average that jumps. Here are the histograms of those twenty samples, side by side. Each was drawn from the same population by the same procedure. Their shapes differ: one looks lopsided, another has two peaks, another a gap. Their medians, standard deviations, skewness, correlations, everything we've computed in this part, would all differ from sample to sample. Every summary of a sample is a random quantity. To say how far to trust one, we need to know how it varies.
So let's find out. Draw not twenty samples but two thousand, and keep every average. As they pile up, a shape emerges: a smooth bell, centred on the truth. This is the sampling distribution of the mean: the distribution of the averages of all the samples we might have drawn. Its spread is much narrower than the population's. Heights vary by about centimetres from person to person, but the averages of a hundred people vary by only . And that number isn't arbitrary. It's almost exactly the population's standard deviation divided by the square root of the sample size, . Why the square root, and why a bell even when the population isn't one, are two of the great theorems of probability, the law of large numbers and the central limit theorem, and Part 6 proves them. This picture, the sampling distribution, is the central object of statistics. It's how we will measure how often we're wrong. And to reason about it, we need the language of chance.
What it establishes: Every summary is random; the SamplingMachine; twenty samples' histograms; the sampling distribution of the mean and its standard error.; Computed or shown: 20 + 2,000 samples of 100 heights: SD of the means 0.951 vs σ/√n = 0.937.
Recap, problems, and the road aheadAll tracks3 min
Part one in fourteen lines. A population has parameters, gold; a sample has statistics, blue; and the World is a population we built so we'd always know the truth. Histograms show shape, and their bin width trades noise against blur. The mean, the median and the mode are the solutions of three optimization problems, and squares won because of Pythagoras. The empirical distribution function holds the data exactly; quantiles and box plots read it. Some distributions have tails so heavy that their moments don't exist. QQ plots test a shape by asking for a straight line, and the Box–Cox family finds the transformation that straightens it. Correlation is the cosine of an angle. The same summaries can hide entirely different pictures; combining groups can reverse a comparison; and a picture can lie by its choice of axis or its encoding. And every statistic we compute is random: it has a distribution of its own.
Almost every idea here comes back. The sampling distribution is the subject of Parts 6, 8 and 11. Estimators as minimizers of a loss are the subject of estimation theory and optimization. Pythagoras returns in least squares and the analysis of variance; the empirical distribution function returns as the bootstrap and, in the PhD stage, as empirical process theory. Heavy tails return in robust statistics, Simpson's paradox in causal inference, and the Coverage Board in every part that makes a promise.
Six problems to work on, with full solutions in this part's README. Two are about centres as minimizers; one asks you to summarize five numbers, one of them a hundred; one is about how correlation behaves under a change of units; one asks you to build your own Simpson's paradox; and the last asks for the transformation that tames an exponential's spread. Pause here if you want to try them.
The books and papers this part follows are listed here and in the README: Tukey's Exploratory Data Analysis, the classic textbook by Freedman, Pisani and Purves, Cleveland and Tufte on graphics, and Stigler's histories, along with the original papers from Graunt to Matejka and Fitzmaurice.
That's the first course on the transcript: one part of sixty-five. We ended with a discovery: every summary of a sample is random, and has a distribution of its own. To reason about that, we need a precise language for chance. It was invented in 1654, in letters between Pascal and Fermat, about a game of dice interrupted at two points to one. How should the stake be divided between the players? That question, and the theory of probability it started, is Part 2.
Where it goes next. The sampling distribution is the subject of Parts 6, 8 and 11; estimators as minimizers of a loss return in Parts 9 and 21; Pythagoras returns as least squares in Part 12 and ANOVA in Part 13; the ECDF becomes the bootstrap in Part 16; heavy tails return in the robust statistics of Part 30; Simpson's paradox is resolved in Part 36; the Coverage Board is filled by every part that makes a promise.
Key results
The part's results in one place, for revision.
Try it
Lab 1 · Centres as minimizers, and a statistic that is random
Draw 200 incomes from the World and find, by brute force, the c that minimizes the sum of |x - c|^p: it is the median at p = 1 and the mean at p = 2. Then draw 2,000 samples of 100 heights and compare the spread of their means with sigma / sqrt(n).
python -m videos.stats.labs 1
needs numpy, scipy, matplotlib · download lab01.py ·
source on GitHubp = 1: brute-force minimizer 36.64 median 36.54 (n even: any c in [36.33, 36.75])
p = 2: brute-force minimizer 48.80 mean 48.79
p = 8: brute-force minimizer 168.60 midrange 231.25
sum of squares about the median 468030.2 = 438030.4 + 29999.8
mean of the 2,000 sample means 169.48 cm (the World's mean 169.50)
SD of the 2,000 sample means 0.917 cm (sigma / sqrt(n) = 0.937)
means within 2 SE of the truth 95.5% (normal: 95.4%)
The median and the mean are the answers to two optimization problems, and only the second follows the long right tail; the mean of a sample is itself a draw from a distribution of width sigma / sqrt(n).
The code (89 lines; it asserts its own result)
"""Lab 1: find the centre of a sample by minimizing a loss, then watch the sample mean itself vary."""
import numpy as np
from videos.coursekit import labs
from explainer.stats.world import World
TITLE = "Centres as minimizers, and a statistic that is random"
GOAL = ("Draw 200 incomes from the World and find, by brute force, the c that minimizes the sum of |x - c|^p: it is "
"the median at p = 1 and the mean at p = 2. Then draw 2,000 samples of 100 heights and compare the spread of "
"their means with sigma / sqrt(n).")
TASKS = [
"Replace the largest income in the sample by ten times its value. Which of the centres move, and by how much?",
"Change the sample size of the height samples from 100 to 400. By what factor does the spread of the means fall?",
"Repeat the second half with the sample median of incomes instead of the mean of heights. Is its spread still "
"sigma / sqrt(n)?",
]
def lp_centre(x, p, grid):
"""The grid point c that minimizes sum |x_i - c|^p (brute force: every candidate is tried)."""
loss = (np.abs(x[:, None] - grid[None, :]) ** p).sum(0)
return grid[np.argmin(loss)], loss
def run(seed=0):
rng = np.random.default_rng(seed)
w = World()
lab = labs.Lab()
# 1. Centres of 200 incomes (in thousands) as minimizers of a loss.
income = w.income[w.adult] / 1000
x = np.sort(rng.choice(income, 200, replace=False))
grid = np.linspace(x[0], x[-1], 20001)
step = grid[1] - grid[0]
c1, loss1 = lp_centre(x, 1, grid)
c2, loss2 = lp_centre(x, 2, grid)
c8, _ = lp_centre(x, 8, grid)
mean, median, midrange = x.mean(), np.median(x), (x[0] + x[-1]) / 2
lab.row("p = 1: brute-force minimizer", f"{c1:.2f} median {median:.2f} (n even: any c in [{x[99]:.2f}, {x[100]:.2f}])")
lab.row("p = 2: brute-force minimizer", f"{c2:.2f} mean {mean:.2f}")
lab.row("p = 8: brute-force minimizer", f"{c8:.2f} midrange {midrange:.2f}")
assert x[99] - step <= c1 <= x[100] + step, "absolute loss is minimized between the two middle values"
assert abs(c2 - mean) <= step, "squared loss is minimized at the mean"
assert median < mean < c8 < midrange, "on right-skewed data the centre slides toward the midrange as p grows"
# 2. Pythagoras: the squared loss at any c is the loss at the mean plus n (mean - c)^2.
lhs = ((x - median) ** 2).sum()
rhs = ((x - mean) ** 2).sum() + len(x) * (mean - median) ** 2
lab.row("sum of squares about the median", f"{lhs:.1f} = {((x - mean) ** 2).sum():.1f} + {len(x) * (mean - median) ** 2:.1f}")
assert np.isclose(lhs, rhs, rtol=1e-10)
# 3. The sample mean is random: 2,000 disjoint simple random samples of 100 adult heights.
height = w.height[w.adult]
n, reps = 100, 2000
samples = height[rng.choice(len(height), n * reps, replace=False)].reshape(reps, n)
means = samples.mean(1)
mu, sigma = w.truth("mean_height"), w.truth("sd_height")
se = sigma / np.sqrt(n)
lab.row("mean of the 2,000 sample means", f"{means.mean():.2f} cm (the World's mean {mu:.2f})")
lab.row("SD of the 2,000 sample means", f"{means.std(ddof=1):.3f} cm (sigma / sqrt(n) = {se:.3f})")
inside = np.mean(np.abs(means - mu) < 2 * se)
lab.row("means within 2 SE of the truth", f"{inside:.1%} (normal: 95.4%)")
assert abs(means.mean() - mu) < 0.1, "the sample mean is centred on the truth"
assert abs(means.std(ddof=1) / se - 1) < 0.07, "its spread is sigma / sqrt(n)"
assert abs(inside - 0.954) < 0.025
lab.note = ("The median and the mean are the answers to two optimization problems, and only the second follows "
"the long right tail; the mean of a sample is itself a draw from a distribution of width sigma / sqrt(n).")
fig, ax = labs.figure(2, size=(11, 4.2))
keep = (grid > x[0]) & (grid < np.quantile(x, 0.97))
ax[0].plot(grid[keep], loss1[keep] / loss1.min(), color=labs.GREEN, label="absolute loss, p = 1")
ax[0].plot(grid[keep], loss2[keep] / loss2.min(), color=labs.RED, label="squared loss, p = 2")
ax[0].axvline(median, color=labs.GREEN, ls="--", lw=1)
ax[0].axvline(mean, color=labs.RED, ls="--", lw=1)
ax[0].plot(x[x < np.quantile(x, 0.97)], np.full((x < np.quantile(x, 0.97)).sum(), 0.97), "|", color=labs.BLUE, ms=7,
label="the incomes (top 3% off the axis)")
ax[0].set(title="Loss against the candidate centre c", xlabel="c, thousands a year",
ylabel="loss / minimum loss", ylim=(0.94, 1.6))
ax[0].legend(loc="upper center")
bins = np.linspace(mu - 4.2 * se, mu + 4.2 * se, 45)
ax[1].hist(means, bins=bins, density=True, color=labs.BLUE, alpha=0.6, label="2,000 sample means, n = 100")
ax[1].plot(bins, np.exp(-0.5 * ((bins - mu) / se) ** 2) / (se * np.sqrt(2 * np.pi)), color=labs.GOLD,
label="normal, SD sigma / sqrt(n)")
ax[1].axvline(mu, color=labs.GOLD, ls="--", lw=1)
ax[1].set(title="The sampling distribution of the mean height", xlabel="sample mean, cm", ylabel="density")
ax[1].legend(loc="upper left")
lab.fig = fig
return lab
Now change it
- Replace the largest income in the sample by ten times its value. Which of the centres move, and by how much?
- Change the sample size of the height samples from 100 to 400. By what factor does the spread of the means fall?
- Repeat the second half with the sample median of incomes instead of the mean of heights. Is its spread still sigma / sqrt(n)?
Problems, with solutions
Try each problem before opening its solution.
1. The median minimizes the sum of absolute deviations.
Solution
Let f(c) = Σ|xᵢ − c|. Away from the data points, f is linear with slope L(c) − R(c), the number of points below c minus the number above. Sort the data.
- n odd (n = 2m + 1): the slope is negative for c < x₍ₘ₊₁₎ and positive after, so the unique minimizer is the median x₍ₘ₊₁₎.
- n even (n = 2m): the slope is zero on the whole interval [x₍ₘ₎, x₍ₘ₊₁₎], and every point of it minimizes f. The minimizer is unique only when x₍ₘ₎ = x₍ₘ₊₁₎.
2. Pythagoras for sums of squares.
Solution
Write xᵢ − c = (xᵢ − x̄) + (x̄ − c) and square:
Σ(xᵢ − c)² = Σ(xᵢ − x̄)² + 2(x̄ − c)Σ(xᵢ − x̄) + n(x̄ − c)².
The middle sum is zero, because deviations from the mean sum to zero. So Σ(xᵢ − c)² = Σ(xᵢ − x̄)² + n(x̄ − c)², which is at least Σ(xᵢ − x̄)², with equality exactly when c = x̄.
3. Summarizing 1, 2, 3, 4, 100.
Solution
- Centre: mean 22, median 3.
- SD (divisor n): √1522 ≈ 39.0.
- MAD: the absolute deviations from the median are 2, 1, 0, 1, 97, whose median is 1. Scaled by 1.4826, ≈ 1.48.
- IQR: with numpy's interpolation, Q₁ = 2 and Q₃ = 4, so IQR = 2.
The median, MAD and IQR describe the four typical values. The mean and SD are dominated by the single 100, and describe no observation at all.
4. Correlation under a change of units.
Solution
Let x′ = a + bx.
- Centring removes a, and both the covariance and s_x scale by |b| (the covariance with its sign, b). So r′ = b·cov / (|b| s_x s_y) = sign(b)·r: unchanged for b > 0, sign flipped for b < 0.
- The slope of y on x′ is cov/(b s_x²), the old slope divided by b.
5. Building a Simpson reversal.
Solution
Take mild cases with treated 90 of 100 recovering against untreated 800 of 1,000, and severe cases with treated 300 of 1,000 against untreated 20 of 100.
- Within each group the treatment is better: 90% vs 80%, and 30% vs 20%.
- Overall it is worse: treated (90 + 300)/1,100 = 35.5%, untreated (800 + 20)/1,100 = 74.5%.
- Each overall rate is a weighted average of its group rates. For the treated, (100/1,100)·0.9 + (1,000/1,100)·0.3; for the untreated, (1,000/1,100)·0.8 + (100/1,100)·0.2. The weights, the share of severe cases, are what differ.
6. Stabilizing an exponential.
Solution
By the delta method, SD(g(X)) ≈ |g′(μ)|·SD(X) = |g′(μ)|·μ. This is constant when g′(μ) ∝ 1/μ, that is g = log. In fact, if X is exponential with mean μ, then log X = log μ + log E with E standard exponential. The spread of log X does not depend on μ at all; only its location moves.
Notes and sources
Sources
- J. Graunt, Natural and Political Observations Made upon the Bills of Mortality (1662). J. Arbuthnot, "An argument for Divine Providence …", Phil. Trans. 27 (1710). Burials and plague deaths from C. Creighton, A History of Epidemics in Britain, as compiled by R. B. Campbell (2001), via the R package HistData (M. Friendly).
- A. Quetelet, Lettres … sur la théorie des probabilités (1846); the chest table as corrected by S. M. Stigler, The History of Statistics (1986), p. 208.
- F. Galton, "Regression towards mediocrity in hereditary stature" (1886). V. Pareto, Cours d'économie politique (1896). W. S. Robinson, "Ecological correlations and the behavior of individuals" (1950).
- G. Box & D. Cox, "An analysis of transformations" (1964). M. Wilk & R. Gnanadesikan, "Probability plotting methods for the analysis of data" (1968). F. Anscombe, "Graphs in statistical analysis" (1973).
- W. Playfair, The Commercial and Political Atlas (1786) and A Letter on our Agricultural Distresses (1821). F. Nightingale, Notes on Matters Affecting the Health … of the British Army (1858), data via Pearson & Short (2007). C. J. Minard (1869), data via L. Wilkinson, The Grammar of Graphics.
- W. Cleveland & R. McGill, "Graphical perception" (1984). E. Tufte, The Visual Display of Quantitative Information (1983). A. Clauset, C. Shalizi & M. Newman, "Power-law distributions in empirical data" (2009). P. Westfall, "Kurtosis as peakedness, 1905–2014. R.I.P." (2014). J. Matejka & G. Fitzmaurice, "Same stats, different graphs" (2017).
- Books: Tukey, Exploratory Data Analysis (1977); Freedman, Pisani & Purves, Statistics; Cleveland, Visualizing Data; Stigler, The History of Statistics and The Seven Pillars of Statistical Wisdom; Hacking, The Taming of Chance.
About this partfrom its README
Part 1 of a sixty-five-part course in statistics, from a first course to a PhD (see the series plan and the syllabus). It is the first part of Stage I, Bachelor's: Foundations. It starts where statistics started, with John Graunt reading London's Bills of Mortality in 1662, and builds the series' laboratory, the World: a simulated population of one million whose truth we know. Then it looks at data before any probability:
- histograms, and the centre and spread of data as solutions of optimization problems;
- quantiles, shape and power-law tails, QQ plots and transformations;
- correlation as the cosine of an angle;
- how summaries mislead, and how pictures can.
It ends with the discovery that makes the rest of the series necessary: every summary of a sample is itself random.
Every number on screen is computed in compute.py, from the World (explainer.stats.world, seed 1662)
or from the Museum's historical tables (explainer.stats.museum, each with its source). Simulated data are tagged
simulated, historical data historical data with the source, and made-up examples illustrative.
Chapter notesChapters (about 63 minutes, silent estimate)
| # | Scene | What it establishes | Computed or shown |
|---|---|---|---|
| 0 | Hook |
Graunt (1662): the Bills of Mortality; burials exceed christenings, so London grows by migration; the male surplus (Graunt's 14 to 13); Graunt’s pioneering life table. The series' question, the five stages, Part 1's objectives. | Christenings, burials and plague deaths 1629–1710 (Arbuthnot 1710; Creighton); the 1665 plague (97,306 burials, 68,596 of plague); the sex ratio of Graunt's years (1.076); Graunt's table of 100 conceived. |
| 1 | Populations |
Population and parameter (θ, gold); sample and statistic (θ̂, blue); the error θ̂ − θ; in real life θ is hidden; the 95% promise and the empty Coverage Board; colour is meaning. | One sample of 25 adult heights against the World's mean (169.50 cm); twenty normal-approximation intervals targeting 95%, 18 covering. |
| 2 | TheWorld |
Why build a world; the island of 200 towns in 10 regions; ages, heights, incomes; the truth table; reproducibility and stability (one random stream per block); the World teaches about methods, the Museum about history. | Town populations (Zipf); the age pyramid; heights (men 176.0, women 163.0); incomes (median 38,910, mean 49,484, top 1% share 6.8%). |
| 3 | Pictures |
Tukey; dot plots; histograms (Pearson's name); the density scale (area = proportion); bin width as a variance–bias choice; Sturges, Scott, Freedman–Diaconis; the population laid over the sample. | 200 adult heights; bin widths 5.45, 6.37, 6.07 cm; the full population’s histogram in 1 cm bins. |
| 4 | Center |
The mean minimizes Σ(xᵢ − c)² (derived); the median minimizes Σ|xᵢ − c| (the tug of war); the median ignores distance, the mean does not; the Lᵖ family from median (p = 1) to midrange (p = ∞), and the mode as a count or window optimum; the Fréchet mean on a clock. | Nine incomes (mean 52.8k, median 36.4k); Lᵖ centres of 200 incomes (41.7 → 185.1k; midrange 201.4k); the mode window; six bedtimes (arithmetic mean 11:58 am, Fréchet mean 11:58 pm). |
| 5 | Spread |
Deviations sum to zero; variance as the average square; SD as its side; Pythagoras in R³: Σ(x − c)² = Σ(x − x̄)² + n(x̄ − c)²; MAD and IQR; Chebyshev's guarantee. | Seven heights (s = 7.17); three heights in R³; SD/MAD/IQR of heights (9.37/10.18/10.21) and incomes (56,852/22,743/24,707); shares within k SDs. |
| 6 | Quantiles |
The ECDF; quantiles as its generalized inverse (the reflected staircase); Tukey's five numbers and box plot; outliers as a flag, not a verdict; regional box plots that differ only by chance. | 40 incomes (ECDF lower median 38.5k; interpolated box-plot median 38.6k, five outliers); 300 incomes in each of 10 regions against the true regional medians. |
| 7 | Shape |
Skewness and kurtosis (tails, not peaks: Westfall 2014); with a Pareto tail of exponent 2.1 the third and fourth moments do not exist, so the sample skewness never settles; the log scale; Pareto's law, the log–log slope and Hill's estimator. | Skewness 0.11 (heights) and 72 (incomes, 39.9 of it from one adult); skewness at n = 1,000 … 741,311; log-income skewness 0.26; slope −2.18, Hill 2.17, true α = 2.1. |
| 8 | QQ |
Building a QQ plot; why a location–scale family gives a straight line (derived); Quetelet's chests; reading the bends: straight, convex (right skew), S-shaped (heavy tails). | 15 men's heights; Quetelet's 5,732 chests (Stigler's corrected table): intercept 39.85 = mean, slope 2.11 ≈ SD 2.07; QQ plots of men, incomes, t₃. |
| 9 | Transform |
The Box–Cox family and its λ → 0 limit (derived); the histogram straightening as λ turns; the profile log-likelihood with its Jacobian; variance stabilization by √ for Poisson counts (delta method). | 300 incomes: skewness at λ = 1, ½, 0, −½; λ̂ = −0.09, likelihood interval −0.21 to 0.02; Poisson SDs 1.38 … 11.04 → 0.62 … 0.49. |
| 10 | Correlation |
Quadrants, products, covariance, r; r as the cosine of the angle between centred vectors; −1 ≤ r ≤ 1 by Cauchy–Schwarz (proved); r is not the slope; restriction of range. | 400 World families (r = 0.46, slope 0.64, Galton's two-thirds); (2, 5, 8) and (3, 3.5, 7.5) at 24.2°, cos = 0.912 = r; the tallest quarter: r = 0.19. |
| 11 | SameStats |
Anscombe's quartet; same statistics, different graphs by simulated annealing (Matejka & Fitzmaurice 2017); a summary as a projection. | The quartet's statistics; 142 World adults annealed into STATS and into a ring, the five statistics read live from every frame (each frame is a real snapshot of the search). |
| 12 | Simpson |
Better in every group, worse overall; the weighted-average mechanism; which comparison is right depends on the causal story (Part 36); the ecological fallacy (Robinson 1950). | The World's clinic: 62.4% vs 73.7% overall; 87.2% vs 79.5% (mild), 47.6% vs 39.5% (severe); 63% vs 15% severe. |
| 13 | Integrity |
Playfair's charts; Nightingale's rose (area, not radius); Minard's march; Cleveland & McGill's ranking of encodings; Tufte's lie factor. | Playfair's wheat and wages (1565–1821); Nightingale's monthly death rates (11,157 disease deaths in the first year); Minard's main column (340,000 → 100,000 → 4,000); a lie factor of 98. |
| 14 | Random |
Every summary is random; the SamplingMachine; twenty samples' histograms; the sampling distribution of the mean and its standard error. | 20 + 2,000 samples of 100 heights: SD of the means 0.951 vs σ/√n = 0.937. |
| 15 | Outro |
Recap in fourteen lines; where each idea returns; problems; references; the Transcript; Part 2's question. | — |
Companion material in this repository
The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
- Hook: the Bills of Mortality (1662). Graunt's tables of christenings and burials, the plague years, the male surplus at birth (tested in Part 10); his estimate of London's size; Halley's life table (1693).
- Populations and samples. Parameters vs statistics; the series' question; the "95% promise" and the empty Coverage Board; the Transcript and the degree ahead.
- Building the World. Its design (§2), and why a known truth makes honest teaching possible; the
simulatedtag; a tour of the map, families, incomes, schools and clinics. - Pictures first. Dot plots and histograms; bin width as a choice (Sturges 1926, Scott 1979, Freedman–Diaconis 1981; derived in Part 29).
- The centre as an optimization.
- The mean minimizes Σ(xᵢ − c)². The median minimizes Σ|xᵢ − c|: the subgradient as a tug-of-war. Discrete modes minimize 0–1 loss; density modes arise from shrinking local windows under regularity. The midrange is the L∞ centre; the Lᵖ centre sliding as p goes from 1 to ∞.
- The Fréchet mean on a circle (clock times).
- Spread. Σ(xᵢ − c)² = Σ(xᵢ − x̄)² + n(x̄ − c)² as Pythagoras in Rⁿ (
NSpace); SD, MAD, IQR; Chebyshev's guarantee (Part 6). - Quantiles and the ECDF. The staircase and its generalized inverse; Tukey's five numbers and box plots; outliers.
- Shape. Skewness; kurtosis as tails (Westfall 2014); Pareto's income law (1896) in the World; log scales; mean vs median income.
- The QQ plot (Wilk & Gnanadesikan 1968). A straight population QQ relation characterizes location and scale; finite QQ plots are diagnostic evidence; reading the curvature; Quetelet's 5,738 Scottish chests (1846).
- Transformations. Log, square root, Box–Cox (1964); variance stabilization (Part 6's delta method).
- Two variables. Covariance; correlation as the cosine between centred vectors; |r| ≤ 1 by Cauchy–Schwarz; correlation is not slope; restriction of range.
- Same statistics, different pictures. Anscombe (1973). Built: the Matejka–Fitzmaurice (2017) annealing morph, holding means, SDs and r to two decimals while a cloud becomes the word STATS.
- Traps of aggregation. Simpson's paradox in the World (resolved in Part 36); the ecological fallacy (Robinson 1950).
- Graphical integrity. Playfair (1786), Nightingale (1858), Minard (1869); Cleveland & McGill (1984); misleading axes.
- The sample is random. Twenty samples of 100; the
SamplingMachine's first run. - Outro. The five stages, problems, references.
Built: the World (v1); the morph engine. Data: Graunt; Quetelet; Anscombe.
Build the film
python -m videos.stats.stats1.compute # the part's numbers, into .cache/stats1
python tools/build.py stats1 # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py stats1 Hook # one chapter, silent, with a contact sheet
Scenes: videos/stats/stats1. Setup: see the course page. Source of these notes: the README and the scenes' narration.
Build it
The finished video is not stored in the repository. From the repo root, after the one-time setup in the top-level README:
python -m videos.stats.stats1.compute # once: every computed item (about a minute; cached in .cache/stats1)
python tools/build.py stats1 -q l # fast 480p preview
python tools/build.py stats1 # 1080p30 -> renders/stats1.mp4
python tools/qa_scene.py stats1 Center # one chapter, silent, with a contact sheet
python tools/lecture_length.py stats1 --floor 50