Ir para o conteúdo

Lição 11 · Two Variables

Relationships Between Two Numeric Variables

Explore two numeric variables with scatter plots, Pearson and Spearman correlation and binned trends, and avoid misreading curves, outliers and clusters.

Bivariate analysis studies two variables together. When both are numeric, you ask: when one is higher, what tends to happen to the other? Is the pattern straight or curved? How tightly do the points follow it?

Start with a scatter plot

A scatter plot draws one point per row. Describe what you see with four words: direction (up or down), form (line, curve, clusters), strength (tight or loose) and exceptions (points far from the rest).

Python Scatter plot of study time and score

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

When thousands of points overlap, the chart becomes a blob. Use transparency (alpha), smaller markers, a random sample or a density view such as ax.hexbin. See scatter plots.

Pearson correlation

The Pearson correlation coefficient, often written r, measures how closely points follow a straight line. It ranges from -1 to 1. The sign gives the direction. Values near 0 mean there is little linear association. It has no units, and swapping the two variables does not change it.

r is not the slope. A very shallow line can have r near 1 if the points sit tightly on it.

Curves and rank correlation

Spearman correlation is the Pearson correlation of the ranks of the values. It measures how consistently one variable increases or decreases with the other, even if the pattern is curved.

Python Pearson and Spearman on four shapes

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Study each row:

  • The straight line scores 1 on both.
  • The exponential curve always rises, so Spearman is 1 while Pearson is lower.
  • The U shape has a perfect relationship, yet both are zero because it is not consistently rising or falling.
  • One wild point gives a Pearson value that suggests a noticeable trend. Spearman is less impressed.

The method="ranked" option needs Python 3.12 or newer.

Same numbers, different pictures

In 1973 the statistician Francis Anscombe published four small datasets with nearly identical means, variances and correlations but very different scatter plots, including a noisy line, a clean curve and patterns driven by a single point. The lesson is simple: never read a correlation without the plot.

To see the shape of a noisy relationship, split x into bins and summarize y in each one.

Python Median y per x bin

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The medians fall and then rise. A single correlation number would not show this valley.

Clusters and restricted range

Two more traps change correlations:

  • Mixed groups. Two clusters can create a correlation even if there is none inside each cluster. Color points by group.
  • Restricted range. If you study only top applicants, a link between test score and later performance can look much weaker than among all applicants, because you removed much of the variation.

Before you trust r

Plot it Is the form straight?
Outliers Does one point drive it?
Groups Are clusters mixed?
Range Were cases filtered out?
1 / 2

Correlation in pandas

df["a"].corr(df["b"]) computes Pearson correlation. For a rank correlation, df["a"].rank().corr(df["b"].rank()) gives Spearman's value when there are no missing values. corr also accepts method="spearman", which may need SciPy in your installation. Missing values are excluded pair by pair, so check how many pairs were used. For the theory, see correlation and covariance.

Correlation is not causation

If x and y move together, several explanations are possible: x affects y, y affects x, a third variable affects both, the way you selected rows created the link, or it is chance. Ice cream sales and swimming accidents can rise together because both increase in hot weather.

Avoid causal verbs such as "drives", "boosts" or "leads to" when you only have an observed association. Write "is associated with" or "tends to be higher when".

Describe the relationship in words

A good description is more useful than a bare coefficient. For the study example you might write: "In this invented sample of 120 students, scores tend to rise with study hours. The pattern looks roughly straight, points scatter widely around it, and scores are capped at 100, which flattens the top right." That sentence mentions the base, the direction, the form, the strength and a limit of the measurement.

If you add a fitted line, say what it is for. A line summarizes the average trend inside the observed range. It says little about values outside that range, and it can be badly wrong when the true pattern is curved. Predicting the score for 40 study hours from data that stops at 10 would be pure guesswork.

Try it yourself

In the four-shapes example, change the wild point from 60 to 6 and run it again. Note how both coefficients react. Then draw a scatter plot of the U shape and explain in one sentence why a value of zero does not mean "unrelated".

Check subgroups

Split the scatter plot by one meaningful category, such as course, store or year, and use the same axes in every panel. Ask whether the direction and form stay similar. If they differ, a single overall coefficient is a poor summary, and each group deserves its own description with its own number of points. Choose the category because of how the data was produced, not because it gives the prettiest result.

Check your pairs

Both variables must describe the same row. Pairing this week's spending with last week's visits by accident, for example after sorting one list and not the other, destroys or invents a pattern. Sort and filter whole rows, and spot-check a few pairs against the source.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. Pearson correlation near zero means what?

    A strong curved relationship, such as a U shape, can have r near zero.
  2. 2. What does Spearman correlation use?

    Using ranks makes it measure consistent increase or decrease.
  3. 3. What should you do when thousands of points overlap?

    These methods show where points are concentrated.
  4. 4. Which sentence is safest for observational data?

    It describes the association without claiming cause.

Summary

  • Plot first, and describe direction, form, strength and exceptions.
  • Pearson measures linear association; Spearman measures consistent rank order.
  • Curves, outliers, mixed groups and restricted range can mislead.
  • Binned medians reveal the shape of noisy relationships.
  • Association does not establish cause.

Next: Comparing Numbers Across Categories

Seu progresso fica salvo neste navegador. Não precisa de conta.