Statistics Chapter 4 of 15

Chapter 4: Describing Relationships

Two-way tables, scatterplots, and correlation

All chapters
On this page
What you will be able to do after this chapter
  • 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.

Which tool for which pair of variables?
Explanatory variableResponse variableDisplaySummary
CategoricalCategoricalTwo-way table, segmented or side-by-side barsConditional percentages
CategoricalQuantitativeSide-by-side boxplots or dotplotsCompare means, medians, SDs by group (Chapters 11, 13)
QuantitativeQuantitativeScatterplotCorrelation \(r\), regression line (Chapter 14)
4.1

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.

Definitions
  • 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:

LibraryHomeCafeRow total
Freshman456025130
Senior309050170
Column total7515075300
Joint distribution

Divide each cell by 300. For example the proportion of students who are freshmen who study in the library is \(45/300 = 0.15\).

Marginal distribution of study location

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.

Conditional distributions of location given class year

Divide each cell by its row total.

LibraryHomeCafeTotal
Freshman (n = 130)0.3460.4620.1921.000
Senior (n = 170)0.1760.5290.2941.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.

Association versus independence (descriptive version)

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.

Choose the right denominator

"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.

4.2

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 stonesLarge stonesAll patients
Treatment A81 of 87 (93.1%)192 of 263 (73.0%)273 of 350 (78.0%)
Treatment B234 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?

Why the reversal?

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\%.\]
Which table to trust?

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.

How to think about Simpson's paradox
  • 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).
4.3

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.

Describing a scatterplot: DFSU
  • 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.

Explanatory versus response

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.

4.4

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.

Covariance and correlation \[s_{xy} = \frac{\sum_{i=1}^{n} (x_i - \bar{x})(y_i - \bar{y})}{n-1}\qquad\qquad r = \frac{s_{xy}}{s_x\, s_y} = \frac{1}{n-1}\sum_{i=1}^{n}\left(\frac{x_i - \bar{x}}{s_x}\right)\left(\frac{y_i - \bar{y}}{s_y}\right) = \frac{1}{n-1}\sum z_{x_i} z_{y_i}\]

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)
1262
2370
3568
4785
5890
Step 1: means

\(\bar{x} = 25/5 = 5\) and \(\bar{y} = 375/5 = 75\).

Step 2: deviations and products
\(x-\bar{x}\)\(y-\bar{y}\)\((x-\bar{x})^2\)\((y-\bar{y})^2\)\((x-\bar{x})(y-\bar{y})\)
-3-13916939
-2-542510
0-70490
210410020
315922545
0026568114
Step 3: covariance, standard deviations, and r

\(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

What to memorize about r
  • \(-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.
Rough guide to strength (context matters)

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.

4.5

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.

Spearman's rank correlation

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

DishRank 1Rank 2\(d\)\(d^2\)
13211
21100
345-11
423-11
55411
\[r_s = 1 - \frac{6(4)}{5(24)} = 1 - \frac{24}{120} = 0.80.\]

The judges agree strongly, though not perfectly.

4.6

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.

The lesson

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).
4.7

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:

ExplanationExample
\(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 bothIce 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.
CoincidenceWith many pairs of time series, some will correlate by chance alone.
What evidence supports causation?

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.

4.8

Chapter summary

Key ideas and formulas
  • 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

TermMeaning
Two-way tableCounts for each combination of two categorical variables
Marginal distributionDistribution of one variable ignoring the other (row or column totals)
Conditional distributionDistribution of one variable within one category of the other
Simpson's paradoxA trend that appears in pooled data but reverses in every subgroup
Lurking variableAn unmeasured variable that affects the relationship between the variables studied
ConfoundingTwo 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 fallacyAssuming a group-level relationship holds for individuals
4.9

Practice