…
…
Statistics and Data Analysis Fundamentals · Lesson 36 / 44 · Correlation and causation
PreviewIn this lesson you will
corrYou can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
The inference unit is finished, and Bazaar's management now hears two claims from two teams. Marketing says: "The more we spend on ads, the more visitors come to the site." Logistics says: "The longer delivery takes, the less satisfied customers are." Both claims are about a relationship between two numeric variables. In this lesson you will first see these relationships, then measure them, and then separate what the measure says from what it does not say.
By the end of this lesson you will draw the chart below yourself and read it with four questions. The direction is rising. The form is roughly a straight line. The strength is high (r = 0.80). There are two unusual things: a separate group on the left, the days when ads were cut, and weekend days that gather at the top of each group.
In this lesson you will:
corr.So far you mostly looked at the distribution of one variable (histogram, boxplot) or at the difference in one variable between groups (two means, two proportions). Marketing's claim asks a different question: when one number grows, does the other number grow too? The file marketing.csv has 181 days, and each day has an ad spend and a visitor count side by side. Nobody can scan 181 rows by eye and say "yes, they rise together." Averages do not help either: the mean ad spend and the mean visitor count are two separate numbers, and neither tells you how the two move together.
In lesson 17 you saw which chart fits this kind of question: if the verb is "look for a relationship," the chart is a scatterplot. In this lesson you will look at that chart in detail and learn to summarize what you see in one number.
In a scatterplot, every observation is one point. In our data, every day is a point: the horizontal position is that day's ad spend and the vertical position is that day's visitor count. In matplotlib you draw it with ax.scatter(x, y). Which variable goes on the horizontal axis is a decision. The explanatory variable (the one you think affects the other, here ad spend) goes on the horizontal axis, and the response variable (the one you try to explain, here visitors) goes on the vertical axis. This layout is not evidence of cause and effect. It only shows how you framed the question. Do not forget to put the unit in the axis names.
import pandas as pd import matplotlib.pyplot as plt mk = pd.read_csv("marketing.csv") fig, ax = plt.subplots() ax.scatter(mk["ad_spend"], mk["visitors"], alpha=0.5) ax.set_xlabel("Ad spend ($)") ax.set_ylabel("Visitors (people)") ax.set_title("Visitors rise as ad spend rises") print(len(ax.collections[0].get_offsets())) print(mk[["ad_spend", "visitors"]].agg(["min", "max"]))
Output181
ad_spend visitors
min 0.5 1058
max 354.0 1963ax.collections[0].get_offsets() holds the coordinates of the drawn points: 181 days, 181 points. Ad spend runs from $0.50 to $354.00, and visitors run from 1,058 to 1,963 people. alpha=0.5 makes the points half transparent, so points that overlap look darker.
When you look at a scatterplot, always ask the same four questions:
| Question | What you look at | Ads and visitors |
|---|---|---|
| Direction | Do the points rise as you go right (increasing) or fall (decreasing)? | Increasing |
| Form | Do the points follow roughly a straight line, or do they draw a curve? | Roughly linear |
| Strength | How close are the points to that line: a thin band or a wide cloud? | A fairly narrow band |
| Unusual | Are there single points far from the rest, or separate groups? | A group on the left from May to June when ads were cut; weekends at the top of each group |
The "unusual" row matters. In lessons 10 and 22 you saw that the ad campaign ended in May. On the chart, this appears as a separate group sitting low on the left. Weekends are in the upper part of both groups: with the same ad spend, more visitors come on a weekend. You will study this second observation separately in lesson 37.
Now draw the same chart yourself and change the response variable:
Try it now· not graded; doesn't affect progress
When you switch to the order count, the points spread vertically: with the same ad spend, one day can bring 2 orders and another day 9. The direction is still slightly increasing, but the band is now a cloud. The "strength" question asks exactly about this difference, and the way to put it into a number is the correlation coefficient.
The Pearson correlation coefficient, or r for short, tells you the direction and strength of the linear relationship between two numeric variables in a single number. It is always between −1 and 1. The sign gives the direction: positive means increasing and negative means decreasing. The size gives the strength: at 1 or −1, all points lie exactly on a straight line, and as you get closer to 0, the points move away from a linear pattern. As a rough vocabulary, people call |r| below 0.3 weak, between 0.3 and 0.7 moderate, and above 0.7 strong. These limits are not a law. They are a habit that changes from field to field.
Train your eye before you calculate. The cell below draws four scatterplots from Bazaar. Look at the charts first, guess an r for each one, and then do the matching.
Try it now· not graded; doesn't affect progress
Match the four charts in the cell with their r values.
For each row, pick its match from the list, then check.
Chart D is a good teacher. Satisfaction takes whole values like 2, 3, 4, and 5, so the points line up on a grid and sit on top of each other. Without transparency (alpha=0.1), the grid would look like a neat rectangle and you could not see any trend. The dark areas show where the points pile up. A guess by eye can only be this good for a scatterplot, and that is why we need a number.
Knowing how r is calculated is the key to reading it correctly. In lesson 16 you met the z-score: how many standard deviations a value is from the mean, z = (value − mean) / standard deviation. The recipe for r is this: turn each point's x and y values into z-scores, multiply the two z-scores, add up the products, and divide by n − 1. So r is the average of the products of z-scores (divided by n − 1, as in the standard deviation).
Why a product? The sign of the product tells you where the point sits relative to the two means. If a point is above the mean in both x and y, both z-scores are positive and the product is positive. If it is below the mean in both, both z-scores are negative and the product is positive again. If it is above in one and below in the other, the product is negative. The cross formed by the two means splits the plane into four regions:
If most points are in the upper right and lower left regions, the positive parts dominate and r is positive. If most are in the upper left and lower right, r is negative. If the points spread evenly over the four regions, the parts cancel each other and r moves toward zero. Points far from the means have large z-scores, so their products are large too: a distant point affects r much more than the points near the center. You will use this in section 6.
Follow the calculation step by step with a small example of five points: x = 1, 2, 3, 4, 5 and y = 2, 4, 5, 4, 5.
Run the code line by line: see which line runs next, the variable boxes and the output.
x = [1, 2, 3, 4, 5] y = [2, 4, 5, 4, 5] n = len(x) mean_x = sum(x) / n mean_y = sum(y) / n sd_x = (sum((v - mean_x) ** 2 for v in x) / (n - 1)) ** 0.5 sd_y = (sum((v - mean_y) ** 2 for v in y) / (n - 1)) ** 0.5 products = [] for a, b in zip(x, y): zx = (a - mean_x) / sd_x zy = (b - mean_y) / sd_y products.append(round(zx * zy, 2)) total = sum(products) r = total / (n - 1) print(products, round(total, 2), round(r, 3))
You can do the same calculation with pandas too, using the z-score lines from lesson 16:
import pandas as pd x = pd.Series([1, 2, 3, 4, 5]) y = pd.Series([2, 4, 5, 4, 5]) zx = (x - x.mean()) / x.std() zy = (y - y.mean()) / y.std() print(zx.round(2).tolist()) print(zy.round(2).tolist()) print((zx * zy).round(2).tolist()) print(round((zx * zy).sum() / (len(x) - 1), 3))
Output[-1.26, -0.63, 0.0, 0.63, 1.26]
[-1.63, 0.0, 0.82, 0.0, 0.82]
[2.07, -0.0, 0.0, 0.0, 1.03]
0.775The products are 2.07, 0, 0, 0, and 1.03 (the -0.0 in second place is zero; when Python multiplies a negative number by zero, it keeps the minus sign). The total is 3.10, and divided by four, r = 0.775. Almost all of the contribution comes from the two end points: the point (1, 2) is below both means (lower left, positive part), and the point (5, 5) is above both (upper right, positive part). The points in the middle add nothing, because they sit exactly at the mean in x or in y.
In this five-point example, you move the last point (5, 5) further right and up, for example to (6, 7). What happens to r?
Let's correct a misunderstanding here: a strong r does not mean the points lie on a line or that the prediction is exact. For ads and visitors, r = 0.80, which is strong. But go back to the chart: on the 36 days when ad spend was between $200 and $225, the visitor count ranged from 1,375 to 1,793. The same spend came with a visitor count that varied by more than 400 people. r = 0.80 means "the points are not a scattered cloud but a clear band." It does not mean "if I know the spend, I know the visitors exactly."
corr, the matrix, and the p-valueYou do not need to do the calculation by hand each time. In pandas, the Pearson correlation of two columns comes from x.corr(y):
import pandas as pd mk = pd.read_csv("marketing.csv") print(round(mk["ad_spend"].corr(mk["visitors"]), 3)) print(round(mk["visitors"].corr(mk["ad_spend"]), 3)) print(round((mk["ad_spend"] / 1000).corr(mk["visitors"]), 3))
Output0.797
0.797
0.797Three lines, and 0.797 three times. The second line swapped the order: correlation has no direction, so the correlation of x with y equals the correlation of y with x. This is why r says nothing about which variable affects which. The third line converted the spend to thousands of dollars: correlation has no unit. The reason is in section 4: r is calculated with z-scores, and a z-score does not depend on the unit. Dividing all values by 1000 divides both the mean and the standard deviation by 1000, and the z-scores stay the same.
If I write the ad spend in thousands of dollars instead of dollars (all values divided by 1000), what happens to r between ads and visitors?
Do not confuse the slope with r. r answers the question "how close are the points to a line?" It does not answer "when x increases by one unit, how much does y increase?" Two relationships can have the same r but very different slopes.
When there are many columns, you want to see all the pairwise correlations in one table. If you apply .corr() to a DataFrame, you get a correlation matrix: each cell is the r of the row variable and the column variable. The diagonal is always 1 (each variable is perfectly related to itself), and the table is symmetric about the diagonal. With the three numeric columns in the survey file:
import pandas as pd from scipy import stats sv = pd.read_csv("survey.csv") print(sv[["delivery_days", "satisfaction", "recommend_score"]].corr().round(3)) r, pv = stats.pearsonr(sv["delivery_days"], sv["satisfaction"]) print(round(r, 3), f"{pv:.1e}")
Output delivery_days satisfaction recommend_score
delivery_days 1.000 -0.569 -0.473
satisfaction -0.569 1.000 0.821
recommend_score -0.473 0.821 1.000
-0.569 3.6e-27Logistics' claim holds up: between delivery time and satisfaction, r = −0.57, a moderate decreasing relationship. Between satisfaction and the recommend score, r = 0.82, a strong increasing relationship.
Here we picked the columns one by one. If you had applied sv.corr() to the whole file, you would get an error: survey.csv has text columns such as survey_id, device, and carrier, and the correlation of text cannot be calculated. The fix is sv.corr(numeric_only=True): pandas takes only the numeric columns.
The stats.pearsonr in the last line comes from SciPy, with the from scipy import stats line you have used since lesson 26. Next to r, it also gives a p-value: "if there is really no linear relationship (r = 0), the probability of seeing an r this extreme in a sample of 300 customers." 3.6e-27 means 26 zeros after the decimal point. But remember lesson 33: in a large sample, p is almost always small. p lets us be sure the relationship is not zero, while r tells you how strong the relationship is. Writing "significant correlation" in a report without giving r hides the most important part of the result.
Now try it yourself. Find the weakest pair in the matrix of the four numeric columns of the marketing file:
Try it now· not graded; doesn't affect progress
The weakest pair is ad spend and revenue: 0.24. Ads follow visitors strongly (0.80), but a visitor does not always mean an order (0.37) or revenue (0.26). The links of a chain can weaken one by one.
r is a very useful number, but it can mislead you in two places. The fix for both is the same: always read r together with the chart.
First trap: r = 0 does not mean "no relationship." r measures only linear relationships. Look at a perfect but U-shaped relationship such as y = x²:
import pandas as pd x = pd.Series(range(-5, 6)) y = x ** 2 print(y.tolist()) print(round(x.corr(y), 3))
Output[25, 16, 9, 4, 1, 0, 1, 4, 9, 16, 25]
0.0y depends completely on x: anyone who knows x can give y without error. Still, r = 0. You know the reason from section 4: on the left arm, where x is negative, the points are in the upper left region (negative part), and on the right arm they are in the upper right region (positive part). The two arms cancel each other exactly. The correct sentence is: "r = 0, so there is no linear relationship." Only a chart can tell you the form of the relationship.
Second trap: a single point can change r completely. In section 4 you saw that the products of distant points are large. The block below has two small data sets. The first has ten points; change the y value of the last point. The second has five scattered points; add a point far away, at (30, 30).
Change two values: the y value of the last point in the ten-point data (last_y) and adding a far point to five scattered points (add_far). How much does r move?
Pick a value; predict the output first, then look.
1import pandas as pd23last_y = 94add_far = False5x = pd.Series([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])6y = pd.Series([3, 4, 5, 6, 6, 7, 5, 7, 8, last_y])7print("10 points: r =", round(x.corr(y), 3))8x5 = [1, 2, 3, 4, 5]9y5 = [3, 1, 4, 2, 3]10if add_far:11 x5 = x5 + [30]12 y5 = y5 + [30]13r5 = pd.Series(x5).corr(pd.Series(y5))14print(len(x5), "points: r =", round(r5, 3))
10 points: r = 0.905 5 points: r = 0.139
Faded lines didn't run with this value. In the ten-point data, changing a single y value from 9 to −10 moves r from 0.905 to −0.287. In the five scattered points, r is 0.139; when the point (30, 30) is added, it becomes 0.989. The distant point pulls both means toward itself, and its z product overwhelms all the other products. Do not report r without looking at the chart.
In the ten-point data, r is 0.905, but when a single y value drops from 9 to −10, it becomes −0.287: a strong increasing relationship turned into a weak decreasing one on paper. It works in the other direction too: the r of five scattered points is 0.139, which means almost no relationship, but when one extreme point is added, r jumps to 0.989 and looks like a "near-perfect relationship." That single point pulls both means toward itself, and its product overwhelms all the other products.
Remember Anscombe's four data sets from lesson 11: four data sets with the same means and standard deviations but completely different charts. The r values of those four data sets are the same too (about 0.82): one is a neat cloud, one is a curve, one is a line bent by a single extreme point, and in one a single point creates the relationship. The same number, four different stories.
So what do you do with a relationship that is curved but always goes in the same direction, or with data that has extreme values? Or when one of your variables is an ordinal scale like a survey score? Satisfaction is a score from 1 to 5, and nobody guarantees that the "distance" between 5 and 4 equals the distance between 3 and 2.
Spearman rank correlation is for these cases. The idea is simple: turn the values of each variable into their ranks (1 for the smallest, 2 for the next, and so on), and then apply Pearson's r to those ranks. Because the order of the values matters and not the values themselves, Spearman:
In pandas, it is enough to write corr(method="spearman"):
import pandas as pd sv = pd.read_csv("survey.csv") print(round(sv["delivery_days"].corr(sv["satisfaction"]), 3)) print(round(sv["delivery_days"].corr(sv["satisfaction"], method="spearman"), 3)) print(sv.groupby("delivery_days")["satisfaction"].mean().round(2))
Output-0.569
-0.565
delivery_days
1 4.77
2 4.29
3 3.95
4 3.50
5 3.04
6 2.00
7 3.00
Name: satisfaction, dtype: float64Pearson is −0.569 and Spearman is −0.565: almost the same. So the relationship logistics found is not an artifact of satisfaction being an ordinal scale. The group means tell the same story: as delivery time goes from one day to five days, average satisfaction falls from 4.77 to 3.04. There is only one survey each for 6 and 7 days; read those two rows as one person's answer, not as a trend.
Look at the extreme-value example through Spearman:
import pandas as pd x = pd.Series([1, 2, 3, 4, 5, 30]) y = pd.Series([3, 1, 4, 2, 3, 30]) print("Pearson without extreme:", round(x[:5].corr(y[:5]), 3), "with extreme:", round(x.corr(y), 3)) print("Spearman without extreme:", round(x[:5].corr(y[:5], method="spearman"), 3), "with extreme:", round(x.corr(y, method="spearman"), 3))
OutputPearson without extreme: 0.139 with extreme: 0.989
Spearman without extreme: 0.103 with extreme: 0.493Pearson jumps from 0.14 to 0.99, and Spearman rises from 0.10 to 0.49. Spearman is affected too (in a data set of six points, one point is not a small share), but much less, because Spearman says the extreme point is only "at the end," not "30 times further away." The same happens in the ten-point example above: whether the last y value is 0 or −10, its rank is "smallest," so Spearman is the same in both cases (0.343), while Pearson falls from 0.071 to −0.287.
If the two measures give very different results, take it as an alarm: either the relationship is curved or an extreme point is carrying the result. Go back to the chart.
Which correlation measure fits each situation better?
For each row, pick its match from the list, then check.
Correlation shows up everywhere. Here are the weekly study hours and exam scores of 10 students in a class (fictional sample data):
import pandas as pd students = pd.DataFrame({ "hours": [2, 3, 4, 5, 6, 7, 8, 9, 10, 12], "exam": [52, 58, 55, 64, 61, 72, 70, 79, 74, 88], }) print(round(students["hours"].corr(students["exam"]), 3)) print(round(students["hours"].corr(students["exam"], method="spearman"), 3))
Output0.956
0.952r = 0.956: a very strong, increasing, linear relationship, and Spearman is almost the same, so no single extreme point is carrying the result. What does this number say? In these 10 students, those who study more also have high scores, and the points are very close to a line. What does it not say? Two things. First, it does not say how many points one more hour of study adds to the score. That is the slope, and it comes with regression in lesson 38. Second, it does not say that studying raises the score. Maybe students who already like the subject both study more and score higher. You will deal with the difference between relationship and cause in lesson 37. Now look at how this number is used in an advertisement:
A tutoring center brochure says: "Among our students, study hours and exam score have a 0.96 correlation. Study 5 more hours a week and your score will soar!" A friend shows you the brochure and asks what you think.
Pick an option and see what happens. There are no points; you can try the other options too.
Back to the two teams' claims. Marketing seems right: between ad spend and visitors, r = 0.80, a strong increasing relationship. Logistics seems right too: between delivery time and satisfaction, r = −0.57, and Spearman says the same. But the word "seems" was chosen on purpose. You saw one more thing in the scatterplot: weekend days gather in the upper part, where both ad spend and visitors are high. Do ads bring visitors, or does the weekend raise both ads and visitors? r cannot answer this question; it tells you strength and direction, not cause. In the next lesson you will test this question with data.
The file marketing.csv has a text column date; numeric_only=True drops it and also adds the 0/1 column weekend to the matrix.
import pandas as pd mk = pd.read_csv("marketing.csv") print(mk.corr(numeric_only=True).round(2))
Output ad_spend visitors weekend orders revenue
ad_spend 1.00 0.80 0.17 0.39 0.24
visitors 0.80 1.00 0.64 0.37 0.26
weekend 0.17 0.64 1.00 0.17 0.15
orders 0.39 0.37 0.17 1.00 0.61
revenue 0.24 0.26 0.15 0.61 1.00The diagonal is 1, and the table is symmetric. The 0.64 between weekend and visitors stands out: visitors rise clearly on weekends. You will study the effect of this column on the ads-visitors relationship in lesson 37.
When delivery time gets longer, does the order amount change? In the file orders.csv, canceled orders have an empty delivery time.
import pandas as pd import matplotlib.pyplot as plt od = pd.read_csv("orders.csv") fig, ax = plt.subplots() ax.scatter(od[], od[], alpha=0.3) ax.set_xlabel() ax.set_ylabel() (od[].isna().(), (od)) ((od[].corr(od[]), 3))
Trusting r without looking at the chart. Before you say "r = 0.02, so the two variables are unrelated," draw the scatterplot: if the points draw a U or an upside-down U, there is a strong but curved relationship, and r cannot see it. In the same way, before you say "r = 0.99, a perfect relationship," check whether a single extreme point is carrying the whole result. The right way: first draw the chart with ax.scatter, answer the four questions (direction, form, strength, unusual points), and then calculate r; if you have any doubt, compare it with Spearman.
method="spearman").Next lesson: if the weekend raises both ads and visitors, what is the real effect of the ads? You will see with data why correlation is not causation.
Exercises and quiz are for members
This lesson has 7 coding exercises and a 10-question quiz. Sign up free to solve them, save your progress and move on to the next lesson.
Output34 885
0.0Of 885 orders, 34 have no delivery time; corr uses the 851 rows where both values are filled and skips the missing ones on its own. r = 0.0: there is no linear relationship between delivery time and amount. The chart confirms it: for every delivery day, the amounts spread over the same range.
The correlation of satisfaction and the recommend score, and the distribution of satisfaction scores:
import pandas as pd sv = pd.read_csv("survey.csv") print(round(sv["satisfaction"].corr(sv["recommend_score"]), 3)) print(sv["satisfaction"].value_counts().sort_index().tolist())
Output0.821
[14, 72, 135, 79]r = 0.821. Satisfaction takes only the values 2, 3, 4, and 5 (14, 72, 135, and 79 people); in a scatterplot, this means four horizontal rows of points. With an ordinal scale like this, it is a good habit to calculate Spearman too and compare the two results; in the first exercise you will look at this chart and guess r yourself.