- Organize two categorical variables in a two-way table and read joint, marginal, and conditional distributions.
- Decide whether two categorical variables look associated by comparing conditional distributions.
- Explain and detect Simpson's paradox, and say when to trust the pooled table and when to trust the stratified tables.
- Make and describe a scatterplot (direction, form, strength, unusual features) in context.
- Compute covariance and the Pearson correlation \(r\) by hand, interpret it, and list what it can and cannot tell you.
- Compute Spearman's rank correlation and explain when it is preferable.
- Use Anscombe's quartet and the restricted-range effect to explain why you must always plot the data.
- Explain why correlation does not imply causation, and name lurking variables, confounding, and the ecological fallacy.
Chapter 3 described one variable at a time. Real questions almost always involve relationships: does studying more go with higher grades, does a treatment go with better recovery, do taller parents have taller children? This chapter builds the descriptive tools for pairs of variables. The formal machinery for inference about relationships arrives in Chapters 12 and 14, but everything there rests on the ideas you meet here.
| Explanatory variable | Response variable | Display | Summary |
|---|---|---|---|
| Categorical | Categorical | Two-way table, segmented or side-by-side bars | Conditional percentages |
| Categorical | Quantitative | Side-by-side boxplots or dotplots | Compare means, medians, SDs by group (Chapters 11, 13) |
| Quantitative | Quantitative | Scatterplot | Correlation \(r\), regression line (Chapter 14) |
Two categorical variables: two-way tables
A two-way table (also called a contingency table or cross-tabulation) counts how many individuals fall into each combination of the categories of two variables. Rows usually hold the categories of one variable and columns the other. Putting the explanatory variable in the rows and the response in the columns makes the table easy to read.
- The joint distribution gives the proportion of all individuals in each cell (each combination). Cell count divided by the grand total \(n\).
- A marginal distribution is the distribution of one variable alone, found from the row totals or the column totals (they appear in the "margins" of the table).
- A conditional distribution is the distribution of one variable among only those individuals with a given value of the other variable. Cell count divided by the row total (or column total).
Example 4.1: Joint, marginal, and conditional distributions
A hypothetical survey (synthetic data) asks 300 students where they prefer to study. The counts by class year are:
| Library | Home | Cafe | Row total | |
|---|---|---|---|---|
| Freshman | 45 | 60 | 25 | 130 |
| Senior | 30 | 90 | 50 | 170 |
| Column total | 75 | 150 | 75 | 300 |
Divide each cell by 300. For example the proportion of students who are freshmen who study in the library is \(45/300 = 0.15\).
Use the column totals: Library \(75/300 = 0.25\), Home \(150/300 = 0.50\), Cafe \(75/300 = 0.25\). Half of all students prefer home.
Divide each cell by its row total.
| Library | Home | Cafe | Total | |
|---|---|---|---|---|
| Freshman (n = 130) | 0.346 | 0.462 | 0.192 | 1.000 |
| Senior (n = 170) | 0.176 | 0.529 | 0.294 | 1.000 |
Freshmen are almost twice as likely to prefer the library (34.6 percent versus 17.6 percent). The two conditional distributions differ noticeably, so in this sample study location and class year are associated.
Two categorical variables are associated if the conditional distributions of one variable differ across the categories of the other. If all the conditional distributions are (nearly) identical, and equal to the marginal distribution, there is little or no association. Exactly identical conditional distributions means the variables are independent in the data. In Chapter 12 we will test whether a difference is bigger than chance alone would produce.
"Of freshmen, what percent prefer the library?" divides by the freshman total (130). "Of library-lovers, what percent are freshmen?" divides by the library total (75), and gives \(45/75 = 60\) percent. These are different questions with different answers. Always ask: percent of what group? When the response variable is in the columns, compute percentages within each row.
Displaying conditional distributions
A segmented (stacked) bar chart shows one bar per row, scaled to 100 percent, with segments for the response categories. Comparing the segment heights across bars reveals association at a glance. A side-by-side (clustered) bar chart shows the same percentages as adjacent bars. A mosaic plot also makes bar widths proportional to the group sizes, so the areas represent the joint distribution. Use the tool below to build your own table and see all these summaries.
Simpson's paradox
Sometimes a relationship seen in the combined data reverses when the data are separated into subgroups. This is called Simpson's paradox. It happens when a third variable (a lurking or confounding variable) is associated with both the explanatory and the response variable, and the groups are of very different sizes.
Example 4.2: Kidney stone treatments (a published classic)
A well-known 1986 study compared two treatments for kidney stones: open surgery (Treatment A) and percutaneous nephrolithotomy (Treatment B). The counts of successful treatments out of patients treated were:
| Small stones | Large stones | All patients | |
|---|---|---|---|
| Treatment A | 81 of 87 (93.1%) | 192 of 263 (73.0%) | 273 of 350 (78.0%) |
| Treatment B | 234 of 270 (86.7%) | 55 of 80 (68.8%) | 289 of 350 (82.6%) |
Treatment A does better for small stones (93.1 versus 86.7 percent) and better for large stones (73.0 versus 68.8 percent), yet Treatment B looks better overall (82.6 versus 78.0 percent). Which treatment is better?
Stone size is a lurking variable. Large stones are harder to treat (lower success rates for both treatments). Treatment A was given mostly to patients with large stones (263 of 350), while B was given mostly to patients with small stones (270 of 350). The pooled percentage for A is dragged down by its heavy load of difficult cases. Pooled success rates are weighted averages of the group rates, and the weights differ:
\[\text{overall A} = \frac{87}{350}(93.1\%) + \frac{263}{350}(73.0\%) = 78.0\%,\qquad \text{overall B} = \frac{270}{350}(86.7\%) + \frac{80}{350}(68.8\%) = 82.6\%.\]Here we want to compare treatments for patients of the same stone size, because size affects both how the treatment was chosen and how it turned out. The stratified tables are the fair comparison, and they favor Treatment A. Note that the answer comes from understanding how the data arose, not from a rule of arithmetic.
- It is not a contradiction in arithmetic. It is an example of weighted averages with different weights.
- Whether to trust the aggregate or the stratified data depends on the causal story. If the third variable is a confounder (it influences who gets the treatment), stratify. If the third variable is a consequence of the treatment (a mediator), stratifying can hide the effect you want to measure.
- Randomized experiments protect against this problem: random assignment makes the treatment groups similar on every third variable (Chapter 2).
Two quantitative variables: scatterplots
A scatterplot plots each individual as a point, with the explanatory variable \(x\) on the horizontal axis and the response variable \(y\) on the vertical axis. It is the single most informative display for two quantitative variables, and you should always draw one before computing anything.
- Direction: positive association (above-average \(x\) tends to go with above-average \(y\)) or negative association (above-average \(x\) goes with below-average \(y\)), or none.
- Form: is the pattern roughly linear, curved, or clustered?
- Strength: how closely do the points follow the pattern? Tightly clustered around a curve or line is strong; a diffuse cloud is weak.
- Unusual features: outliers (points far from the pattern), clusters, gaps, and points with unusual \(x\) values.
Always describe these in context, with variable names and units.
The explanatory variable (predictor, independent variable) is the one we think might help explain or predict; the response variable (outcome, dependent variable) is what we want to explain. Which is which depends on your question, not on the data. Study hours may predict exam score, but you could also ask how much a student who scored 80 studied. The correlation coefficient is symmetric, but the regression line (Chapter 14) is not.
Covariance and the correlation coefficient
To measure the strength of a linear association with a single number, we look at how the deviations of \(x\) and \(y\) from their means move together. Let the means be \(\bar{x}, \bar{y}\). For each point, the product \((x_i - \bar{x})(y_i - \bar{y})\) is positive when the point lies in the upper-right or lower-left quadrant (both above average or both below average), and negative in the other two quadrants.
The covariance \(s_{xy}\) has units of \(x\) times units of \(y\), so its size is hard to interpret. Dividing by \(s_x s_y\) removes the units: \(r\) is the (almost) average product of z-scores.
Equivalent computing formulas use sums of squares: with \(S_{xx} = \sum(x_i-\bar{x})^2\), \(S_{yy} = \sum(y_i-\bar{y})^2\), and \(S_{xy} = \sum(x_i-\bar{x})(y_i-\bar{y})\),
\[r = \frac{S_{xy}}{\sqrt{S_{xx}\,S_{yy}}}.\]Example 4.3: Computing r by hand
Five students (synthetic data) record hours studied \(x\) and exam score \(y\):
| Student | \(x\) (hours) | \(y\) (score) |
|---|---|---|
| 1 | 2 | 62 |
| 2 | 3 | 70 |
| 3 | 5 | 68 |
| 4 | 7 | 85 |
| 5 | 8 | 90 |
\(\bar{x} = 25/5 = 5\) and \(\bar{y} = 375/5 = 75\).
| \(x-\bar{x}\) | \(y-\bar{y}\) | \((x-\bar{x})^2\) | \((y-\bar{y})^2\) | \((x-\bar{x})(y-\bar{y})\) |
|---|---|---|---|---|
| -3 | -13 | 9 | 169 | 39 |
| -2 | -5 | 4 | 25 | 10 |
| 0 | -7 | 0 | 49 | 0 |
| 2 | 10 | 4 | 100 | 20 |
| 3 | 15 | 9 | 225 | 45 |
| 0 | 0 | 26 | 568 | 114 |
\(s_{xy} = 114/4 = 28.5\). \(s_x = \sqrt{26/4} = 2.5495\), \(s_y = \sqrt{568/4} = 11.9164\). Then
\[r = \frac{28.5}{2.5495 \times 11.9164} = 0.9381 \qquad\text{or equivalently}\qquad r = \frac{114}{\sqrt{26 \times 568}} = 0.9381.\]Interpretation: there is a strong, positive, linear association between hours studied and exam score in these five students. (Notice that with only five points, one unusual point could change \(r\) a lot.)
Properties of the correlation coefficient
- \(-1 \le r \le 1\). The sign gives the direction; the size gives the strength of the linear pattern. \(r = \pm 1\) only if all points lie exactly on a line.
- \(r\) has no units. Changing units (feet to meters, dollars to thousands of dollars) does not change \(r\). More generally, \(r\) is unchanged by \(x \to ax + b\) and \(y \to cy + d\) for \(a, c > 0\) (the sign flips if \(a\) and \(c\) have opposite signs).
- \(r\) is symmetric: swapping \(x\) and \(y\) gives the same \(r\).
- \(r\) measures only linear association. A perfect curved relationship can have \(r\) near 0.
- \(r\) is not resistant. A single outlier can raise, lower, or even flip the sign of \(r\).
- \(r\) says nothing about causation, and nothing about the slope of the line.
Many texts describe \(|r| < 0.3\) as weak, \(0.3\) to \(0.7\) as moderate, and above \(0.7\) as strong. These cut-offs are conventions, not laws. In physics, \(r = 0.9\) may be a poor fit; in psychology, \(r = 0.3\) may be a notable finding. Always look at the plot, and remember that \(r^2\) (Chapter 14) is the fraction of variation in \(y\) accounted for by a linear relationship with \(x\).
Going deeper: Why is r always between -1 and 1?
Let \(u_i = (x_i - \bar{x})/s_x\) and \(v_i = (y_i - \bar{y})/s_y\) be the z-scores, so \(\sum u_i^2 = \sum v_i^2 = n-1\) and \(r = \frac{1}{n-1}\sum u_i v_i\). For any real \(t\), the sum \(\sum (u_i - t v_i)^2 \ge 0\). Expanding, \((n-1) - 2t(n-1)r + t^2(n-1) \ge 0\), that is, \(1 - 2tr + t^2 \ge 0\) for every \(t\). A quadratic in \(t\) that is never negative has a non-positive discriminant: \(4r^2 - 4 \le 0\), so \(|r| \le 1\). Equality holds only if some \(u_i = t v_i\) for all \(i\): the z-scores are exactly proportional, meaning the points lie on a line. This is the Cauchy-Schwarz inequality.
Rank correlation (Spearman)
Pearson's \(r\) is sensitive to outliers and detects only linear patterns. When a relationship is monotonic (consistently increasing or consistently decreasing) but curved, or when the data are ordinal ranks, we can use Spearman's rank correlation \(r_s\): replace each variable's values by their ranks (1 for the smallest; ties get the average of the ranks they occupy), then compute Pearson's \(r\) on the ranks.
If there are no ties, with \(d_i\) the difference between the ranks of the \(i\)th pair,
\[r_s = 1 - \frac{6\sum d_i^2}{n(n^2 - 1)}.\]With ties, compute Pearson's \(r\) on the (average) ranks. \(r_s = 1\) if \(y\) always increases with \(x\), however curved; \(r_s = -1\) if \(y\) always decreases.
Example 4.4: Spearman by hand
Two judges rank five dishes (the scores are synthetic): Judge 1 gives scores 3, 1, 4, 2, 5 and Judge 2 gives 2, 1, 5, 3, 4. The scores are already in rank order, so
| Dish | Rank 1 | Rank 2 | \(d\) | \(d^2\) |
|---|---|---|---|---|
| 1 | 3 | 2 | 1 | 1 |
| 2 | 1 | 1 | 0 | 0 |
| 3 | 4 | 5 | -1 | 1 |
| 4 | 2 | 3 | -1 | 1 |
| 5 | 5 | 4 | 1 | 1 |
The judges agree strongly, though not perfectly.
Always plot the data: Anscombe's quartet
In 1973 the statistician Francis Anscombe constructed four small datasets that have nearly identical summary statistics: the same mean of \(x\) (9), the same mean of \(y\) (7.50), the same standard deviations, the same correlation \(r \approx 0.816\), and the same fitted line \(\hat{y} = 3.0 + 0.5x\). Yet their scatterplots look completely different: one is a noisy line, one a smooth curve, one a perfect line with a single outlier, and one is a vertical stack of points with a single high-leverage point deciding the entire fit.
Summary numbers can hide the structure of the data. Compute \(r\) only after looking at the scatterplot, and re-check the plot whenever \(r\) surprises you. Modern versions such as the "Datasaurus Dozen" make the same point with a dinosaur.
Other traps when using correlation
- Restricted range. If you only observe a narrow slice of the \(x\) values, the correlation shrinks even if the underlying relationship is just as strong. For example, the correlation between test score and college GPA looks weak among students who were all admitted with high scores. Use the tool below to see it.
- Averages hide variation. Correlations computed from group averages (cities, schools) are usually much stronger than correlations between the individuals inside the groups. Applying group-level results to individuals is the ecological fallacy.
- Nonlinear patterns. \(r \approx 0\) does not mean "no relationship" (think of a U shape).
- Combining groups. Pooling two subgroups can create, remove, or reverse an apparent correlation (the scatterplot version of Simpson's paradox).
Correlation and causation
A strong association between two variables does not mean that one causes the other. If \(x\) and \(y\) are correlated there are several possible explanations:
| Explanation | Example |
|---|---|
| \(x\) causes \(y\) | More fertilizer produces more corn (established by experiment). |
| \(y\) causes \(x\) (reverse causation) | Cities with more police have more crime: crime may prompt hiring more police. |
| A lurking variable causes both | Ice cream sales and drowning deaths rise together; hot weather drives both. |
| Confounding (effects cannot be separated) | People who take vitamins also exercise, eat well, and see doctors. |
| Coincidence | With many pairs of time series, some will correlate by chance alone. |
A well-designed randomized experiment is the gold standard (Chapter 2). For questions where experiments are impossible or unethical (smoking and cancer), causal conclusions rest on many lines of evidence: a strong and consistent association across studies and populations, a dose-response relationship, the right time order (cause before effect), a plausible mechanism, and ruling out alternative explanations. Statisticians call some of this the Bradford Hill criteria.
Example 4.5: Spotting the lurking variable
A study finds that across a set of towns, the number of fire trucks sent to a fire is positively correlated with the amount of damage. Should the fire department send fewer trucks to reduce damage?
No. The lurking variable is the size of the fire: bigger fires cause both more trucks to be dispatched and more damage. The correlation is real, but it does not mean sending trucks causes damage. Diagnosing this requires thinking about the mechanism, not calculation.
Chapter summary
- Two-way table: joint, marginal, and conditional distributions. Compare conditional percentages (divide by the group total, not the grand total) to look for association.
- Simpson's paradox: a trend in the pooled data can reverse within subgroups when the group sizes differ. Think about the confounder and the causal story.
- Scatterplot: describe direction, form, strength, unusual features, in context.
- \(s_{xy} = \dfrac{\sum (x_i-\bar{x})(y_i-\bar{y})}{n-1}\), \(\;r = \dfrac{s_{xy}}{s_x s_y} = \dfrac{S_{xy}}{\sqrt{S_{xx}S_{yy}}} = \dfrac{1}{n-1}\sum z_x z_y\).
- \(-1 \le r \le 1\); unit-free; symmetric; linear only; not resistant.
- Spearman: \(r_s\) is Pearson's \(r\) on ranks; \(r_s = 1 - \dfrac{6\sum d^2}{n(n^2-1)}\) without ties. Robust to outliers, detects monotone patterns.
- Anscombe: identical summaries, different pictures. Plot first.
- Correlation does not imply causation: consider reverse causation, lurking variables, confounding, and coincidence. Randomized experiments give causal evidence.
Key terms
| Term | Meaning |
|---|---|
| Two-way table | Counts for each combination of two categorical variables |
| Marginal distribution | Distribution of one variable ignoring the other (row or column totals) |
| Conditional distribution | Distribution of one variable within one category of the other |
| Simpson's paradox | A trend that appears in pooled data but reverses in every subgroup |
| Lurking variable | An unmeasured variable that affects the relationship between the variables studied |
| Confounding | Two variables' effects on the response cannot be separated |
| Correlation \(r\) | Unit-free measure of the strength and direction of linear association |
| Spearman \(r_s\) | Correlation of the ranks; measures monotone association |
| Ecological fallacy | Assuming a group-level relationship holds for individuals |