Multivariate EDA and visualization: how variables move together, how to show it, and the one conclusion that the data cannot support.
Knowledge Discovery in Data · University of the Philippines Cebu
Co-movement in one number from −1 to +1, and the full matrix in one call.
Scatter plots and heatmaps: the shapes and clusters that the number cannot show.
Groups, confounders, and why "related" does not by itself mean "caused".
Last week covered each variable alone. This week covers pairs and groups, because most findings concern relationships between columns. Multivariate means "several variables at once".
Last week described each student's height; this week asks whether taller students also tend to be heavier, and whether that holds in every class.
Eight students: hours studied, hours slept, exam score. The dataset is small enough to inspect fully, yet it can still mislead.
Also called Pearson’s r. A number from −1 to +1 for how closely two columns follow a straight line together. The sign says which way.
e.g. study hours vs score, r = 0.99: they rise together
X causes Y if changing X would change Y. Correlation alone never shows this: correlation is not causation.
e.g. ice cream sales and drownings rise together; summer causes both
A third variable that drives both X and Y, making them move together without one causing the other.
e.g. fire size drives both firefighters sent and damage done
One dot per row: one column across (x), another up (y).
e.g. ax.scatter(students["study_hours"], students["score"])
The straight line that best fits the dots in a scatter; its slope says how much y changes per step of x.
e.g. score ≈ 5.1 × study hours + 55.6
A grid whose cells are coloured by their value; for a correlation matrix, colour shows sign and strength.
e.g. sns.heatmap(students.corr(), annot=True, center=0)
The figure is the whole saved picture; an axes is one plotting area inside it, with its own x and y.
e.g. fig, ax = plt.subplots() gives one of each
One of several axes arranged in a grid inside one figure.
e.g. plt.subplots(1, 2) makes two side by side
Panels that use exactly the same scale on an axis, so their heights can be compared fairly.
e.g. plt.subplots(1, 2, sharey=True)
Two ways to add a grouping column: hue colours the dots by group; facet draws one panel per group.
e.g. hue="passed"; sns.FacetGrid(df, col="region")
A grid of scatter plots for every pair of columns, with each column's histogram on the diagonal.
e.g. sns.pairplot(df) on 3 columns gives a 3 × 3 grid
Bar charts for two categories at once: grouped puts bars side by side, stacked piles them into one bar.
e.g. completed vs on-going projects, per year
Eight rows may suggest that more study goes with higher scores, but not clearly. Multivariate EDA replaces visual guessing with two tools: a number and a picture.
The printout is a DataFrame (a table): one row per student, numbered 0, 1, 2… on the left, and one column per measurement.
students = pd.DataFrame({…})eight students: hours studied, hours slept, exam score (the lab calls this table df)How strongly two columns move together, and what that relationship looks like.
Auguste Bravais derives and publishes the formula.
Francis Galton develops the idea of co-relation.
Karl Pearson builds Galton’s idea into the modern coefficient r.
Charles Spearman introduces rank correlation.
Naming a method after someone other than its first discoverer is common enough to have a name: Stigler’s law.
Spearman’s version only uses the order of the values, which is why it handles skewed data such as budgets better.
SourceWikipedia: Pearson correlation coefficient; Spearman’s rank correlation
df.corr() computes Pearson unless told method="spearman".
Spearman is Pearson’s formula applied to the ranks of the values.
Both run from −1 to +1, so they can be compared directly.
This week compares them on DPWH budgets and durations: 0.365 (Pearson) against 0.508 (Spearman).
Sourcepandas: DataFrame.corr; Wikipedia: Spearman’s rank correlation; values from this deck’s DPWH example
As in weeks 6 and 7, a block with a ▶ Run / Edit button runs in the browser and can be changed; a chart appears as a picture under the code. The first run downloads Python, pandas and matplotlib, which takes 10 to 20 seconds.
seaborn is not available in the browser, and the flood data cannot be downloaded there. Those blocks have no button; the companion notebook runs them, and every chart in this deck was drawn by the code on its slide.
pd.__version__the installed pandas: 3.0.5 on the laptop, 2.2.0 in the browsert.dtypeseach column’s type: str on the laptop, object in the browserCo-movement summarized in a single number.
Last week summarised one column with a mean and a standard deviation. This part adds one number for two columns: how closely they rise and fall together.
In plain words: Pearson correlation (r), usually just called correlation, is one number that says how closely two columns rise and fall together along a straight line. +1: always together; −1: always opposite; 0: no straight-line link.
In pandas, df.corr() computes Pearson unless given method="spearman".
Pearson (1896); Freedman, Pisani & Purves, Statistics, 4th ed., ch. 8.
| Part | For the eight students |
|---|---|
| x̄, ȳ (the means) | 4.5 hours, 78.5 points: the dashed lines |
| (xi − x̄)(yi − ȳ) | one student's product: + when both are above or both below the means. All 8 are + |
| top: Σ of products | 214 |
| bottom: the √ part | √(42 × 1,104) = 215.3; it rescales r to −1…+1 |
| r | 214 ÷ 215.3 = 0.994 |
Correlation (written r) measures how tightly two variables follow a straight line together. The sign (+ or −) gives direction; the size, ignoring the sign, gives strength.
Two dancers move in perfect step at +1, mirror each other at −1, and move independently at 0.
| r | Reads as | Example |
|---|---|---|
+1.0 | perfect together | height in cm vs inches |
+0.7 | strong positive | study hours vs score |
0.0 | no linear link | shoe size vs exam score |
−0.7 | strong negative | absences vs grades |
−1.0 | perfect opposite | time used vs time left |
the sign is the direction the cloud tilts; the size is how tightly the dots hug a straight line. At 0 there is no tilt at all. Each cloud has exactly the r printed above it.
.corr() builds the whole matrixEvery numeric column against every other. The result is a correlation matrix: a grid with one row and one column per variable. The diagonal is always 1, since a variable moves perfectly with itself, and the matrix is symmetric about it.
Result on the lecture laptop (select to reveal)
Negative, −0.98: more sleep goes with lower scores in these eight students, and study hours with higher ones (0.99). With one student changed to 4 hours of sleep, the correlation falls to −0.28: one row out of eight can change it completely.
students.corr()correlate every numeric column with every other one.round(2)show two decimal places-0.98study and sleep: strongly opposite (more study, less sleep)study ↔ score = 0.99: in this small dataset, study hours and scores rise together almost perfectly.
each cell is r for its row and its column. The amber diagonal is a column with itself, always 1. Every other number appears twice, mirrored across the diagonal, so only the three cells above it are new information: +0.99, −0.98 and −0.98.
The rest of Part A measures relationships among the flood projects’ six numeric columns, including week 6’s duration.
pd.read_csv(url)?pandas downloads with urllib, which this site’s bot protection answers with 403 Forbidden. requests gets through.
The browser cannot download the data, so the flood blocks have no Run button; the companion notebook runs them.
df["duration"] = …days from start to completion; NaN where a date is missingcols = […]the six numeric columns used on the next slides(34079, 16)34,079 projects; 15 columns from the file plus duration
six columns give 15 pairs. Only four reach beyond ±0.2, and each is examined in turn: budget–duration next, then latitude–longitude and progress–year later this week. The next slide shows the one line of code that computes all fifteen.
One call gives every pairwise correlation. cols is a list of six numeric column names; df[cols] keeps only those columns. It is read for large absolute values (either sign), each of which is then examined.
A correlation matrix is a list of things worth plotting. It is not a list of findings.
.rename(columns={…})shorter column names (old → new), only so the grid fits on screen-0.785lat vs lon: the largest value off the diagonal (discussed below)
left: the cloud drifts upward but is wide at every budget, which is what a moderate r looks like. Right: r² = 0.133, so budget's straight line accounts for 13 of every 100 parts of the variation in duration; the other 87 come from everything else.
r = 0.365 across 27,664 finished projects. Positive and plausible: more money usually means more work.
r² (r squared) is the share of the ups and downs in one column that a straight line on the other can account for.
0.365² = 0.133. Budget accounts for about 13% of the variation in how long a project takes. The other 87% comes from other factors.
df[["budget", "duration"]].dropna()keep the two columns, then drop every row missing either onesub.budget.corr(sub.duration)the correlation of exactly these two columns (rounded to 3 decimals)0.365**2** means "to the power of": square r to get r²In plain words: Spearman correlation (ρ, “rho”) asks one question: when x goes up, does y go up too, every time? It ignores by how much. Each value is replaced by its place in line (smallest = 1), and the places are compared.
di is row i’s rank in x minus its rank in y (no tied values). It equals Pearson’s r computed on the ranks.
Spearman (1904), American Journal of Psychology 15(1), 72–101.
| Project | Budget (₱M) | Days | Budget rank | Days rank | d |
|---|---|---|---|---|---|
| A | 1 | 10 | 1 | 1 | 0 |
| B | 2 | 30 | 2 | 3 | −1 |
| C | 3 | 20 | 3 | 2 | +1 |
| D | 4 | 40 | 4 | 4 | 0 |
| E | 100 | 50 | 5 | 5 | 0 |
Five made-up projects. Only B and C are out of order, so Σd² = 2:
Pearson on the same values gives only 0.721, because E’s ₱100M sits far from any straight line.
left, raw values: a long tail of large budgets squeezes most projects into the left edge, so a straight line fits poorly. Right, the same projects replaced by their ranks: the points spread evenly, and the lower-left to upper-right tilt is clearer. Spearman is Pearson computed on these ranks.
Pearson r is the usual correlation, on the raw values. Spearman correlation first replaces each value by its rank (smallest = 1, next = 2…) and correlates the ranks. Spearman is much higher here. That means the relationship is monotonic (always moving the same way) but not linear (not a straight line), as expected for a budget column with skew 5.13. Pearson is lowered by the shape, not by the absence of a relationship.
Spearman when either variable is skewed or has outliers. Pearson when the scatter has been checked and it does look like a line.
left, raw budgets: a few large projects stretch the scale and most sit in a pile on the left, so a straight line on raw budget fits poorly (r = 0.365). Right, log₁₀: the same projects spread out, and the straight-line correlation with duration rises to 0.396.
The same transform as last week (log₁₀: the power of 10 that gives the value). On log₁₀(budget), the linear correlation rises from 0.365 to 0.396, closer to what the ranks already indicated. lg keeps the positive budgets, because the log of 0 does not exist.
Either use Spearman, or transform and use Pearson. Reporting 0.365 as "weak" without checking whether a straight line is the right model is an error.
The projects are grouped into four budget bands and the median duration of each is computed. The pattern hidden under 27,664 dots in a scatter plot becomes clear. d is a copy of sub, the 27,664 finished projects.
The groups are equal-sized by construction, so the comparison is fair and no band rests on a small sample.
pd.qcut(sub.budget, 4, labels=[…])four bands with the same number of projects: from the cheapest quarter to the most expensive.duration.median()the typical duration in each band: it rises in every step, 119 to 269 days
The largest quarter of projects take more than twice as long as the smallest quarter. This is not apparent from "r = 0.365". Binning is not inferior to correlation; often it is the more informative method.
r measures straight-line co-movement only. A curve can score 0, two clusters can fake a trend that neither has, and one point can create a strong r. Anscombe's quartet from last week makes the same point.
No conclusion is drawn from a correlation without a scatter plot (Part B).
the Datasaurus Dozen (Matejka & Fitzmaurice, CHI 2017; the dinosaur is Alberto Cairo’s). All thirteen have the same means, the same spreads and r between −0.06 and −0.07, yet no two look alike. Anscombe’s quartet from last week made the same point with four datasets; this makes it with thirteen. The number alone never identifies the pattern.
Strong, real and reproducible, but without substantive meaning.
every dot is a project placed at its own coordinates, so the scatter plot draws the Philippines. The country runs north-west to south-east, so the best straight line falls to the right: r = −0.785. The number describes geography, not flood control.
Across 30,884 geocoded projects, latitude and longitude correlate at −0.785, stronger than any other pair in the matrix. No mechanism is involved.
Locations further south are also further east. The correlation is a fact about the archipelago’s outline, not about flood control.
.agg(["min", "max"])two summaries at once: lowest and highest latitude (degrees north); .tolist() prints them as a plain list[5.01, 20.79]from Mindanao's south to Luzon's north; longitude (degrees east) runs 117 to 127(A coefficient is a number that measures something; here, r.)
−0.785 would stand out in any correlation table. Strength is not evidence of anything.
30,884 rows. A large n makes a coefficient precise, not meaningful.
No one would claim that latitude causes longitude. With two variables of real interest, such a claim would be more tempting.
The last point is the key warning. The risk lies less in a correlation that cannot be explained than in one that can, because a plausible explanation ends further investigation. (n is the number of rows the statistic uses.)
Correlation is not causation: two things moving together shows that they are linked, not which one affects the other, or whether a third variable affects both.
In the matrix, study_hours ↔ sleep_hours =
−0.98. What does that number claim?
B: a strong pattern, and only a pattern.
The magnitude (0.98) says the opposite movement is very consistent; the sign says which way. What it does not say is why; a fixed number of evening hours may force the trade-off. Causes are the subject of Part C.
r states only this: "these move together this consistently, in this direction."
With only r as evidence, the correct phrase is "is associated with," not "causes."
Next: plots that show what the number cannot.
One point per row shows the full pattern.
Part A gave r, one number per pair. This part plots the pairs to show the curves, clusters and unusual points that r hides.
A scatter plot draws one dot per row: x (across) from one column, y (up) from another. Trend, tightness, curves and outlying points are all visible at once.
"study_hours" to "sleep_hours" in the scatter line. What changes?Result on the lecture laptop (select to reveal)
Eight dots rising almost in a straight line from (1 hour, 60) to (8 hours, 95). With sleep hours across, the dots fall instead: more sleep, lower score, the −0.98 of the matrix. The next slide shows the study-hours chart.
ax.scatter(students["study_hours"], students["score"])one dot per student: x from one column, y from anotherset_xlabel / set_ylabelname each axisEight dots rising steadily to the upper right: the shape that r = 0.99 summarizes in one number.
every dot is one student. They rise from the bottom left to the top right almost in a straight line; this tight, rising line is the picture behind r = 0.99.
A trend line is the straight line that fits the dots best (closest overall). Its slope is how much y changes when x goes up by 1; its intercept is where it crosses x = 0.
A string stretched through a cloud of pins to pass as close to all of them as possible, whose tilt is the slope.
"Each extra study hour goes with about 5.1 more points" in these 8 students. Not "causes": that is Part C.
xs to np.array([1, 10]). What score does the line predict at 10 hours?Result on the lecture laptop (select to reveal)
About 5 points per hour: slope 5.1, intercept 55.6. At 10 hours the line predicts 106.5, above the maximum score of 100: a line fitted to 1–8 hours says nothing reliable outside that range.
np.polyfit(x, y, 1)fit a straight line (degree 1): returns its slope and interceptslope * xs + interceptthe line’s height at the two ends, 1 and 8 hours
the line rises about 5 points for every extra hour, and no dot is far from it. This chart has no axis names because the code does not call set_xlabel / set_ylabel; they should be added in practice.
When budget is plotted against duration for every finished project, the middle becomes a solid block. Density (how crowded each area is) is not visible, only the outline.
Overplotting: so many dots on top of each other that they cannot be counted.
The plot is least readable exactly where most of the data lies.
df.plot.scatter(x="budget", y="duration")27,664 dots, most of them on top of each otherdf.sample(2000, random_state=42)fix 1: a reproducible sample of 2,000 projectsdf.plot.hexbin(…, gridsize=40)fix 2: count the projects in hexagonal cells; darker = more
almost every project lies inside the solid block in the bottom-left corner, so the most crowded area cannot be identified. The 1e9 under the x axis means the tick labels count billions of pesos (0.2 = 200 million).


left, df.sample(2000, random_state=42): with fewer dots, single projects are visible, and the largest ones were not drawn, so the axis stops near 700 million (1e8 = hundreds of millions). Right, hexbin: the darkest cells, next to the origin, are where thousands of projects are concentrated; the colour bar on the right gives the counts.
The column need not be transformed to improve the picture; only the axis is changed. On a log scale each equal step multiplies (1M, 10M, 100M). The tick labels stay in pesos, so the reader needs no translation.
"x-axis is logarithmic" is one clause and prevents a reader from misjudging every distance on the chart.
alpha=0.05each dot 95% transparent, so crowded areas look darkerax.set_xscale("log")equal steps mean equal ratios: 10M to 100M is as wide as 100M to 1B
the dark band between 107 (10 million) and 108 (100 million pesos) contains most projects, and the cloud now tilts upward: bigger budgets tend to take longer. Read 107 as "1 followed by 7 zeros".
Color encodes each correlation — warm for positive, cool for negative, pale near zero. Ten variables give 45 pairs, and the strongest ones are quickly visible.
A weather map of the matrix, in which hot and cold regions are visible before any number is read.
annot=True prints the numbers on the cells; center=0 anchors white at zero so that the sign is easy to read.
red cells are pairs that rise together, blue cells the pair that moves in opposite directions. Nothing is pale, because every pair here is strongly related. The diagonal is 1: each column against itself.
A heatmap gives one colour per pair. A pair plot
draws the actual scatter for every pair of columns, in a grid, with each column's
histogram on the diagonal. It is the picture behind every number in .corr().
The heatmap is the table of contents and the pair plot is the book; the first is used to choose, the second to check.
3 columns make 9 panels; 10 columns make 100. Only the few columns identified by the heatmap are included.
sns.pairplot(df)seaborn draws one panel for every pair of numeric columns (in Colab; not the browser lab)g.axes.shapethe grid of axes it made: (3, 3) means 3 rows by 3 columns of panelsdiagonal panelsa column against itself would be a straight line, so each shows that column's histogram insteadeach off-diagonal panel is one pair. Study hours and score climb together; every panel with sleep hours falls. The panels above the diagonal repeat the ones below it with x and y swapped, and the diagonal shows each column's own histogram.
Six columns is fifteen pairs. A heatmap colours each cell of the matrix by its value, so the strong ones stand out without reading a grid of numbers.
A colormap turns numbers into colours. A diverging one runs blue → white → red, so negative and positive look different. A sequential one (pale → dark) renders −0.785 and +0.785 nearly the same.
import seaborn as snsload seaborn, a chart library built on matplotlib (in Colab; not in the browser lab)annot=True, fmt=".2f"write each r on its cell, with two decimalscmap="RdBu_r", center=0red-blue colours, white exactly at r = 0vmin=-1, vmax=1fix the colour scale to the full −1 to +1 rangealmost every cell off the diagonal is pale: most pairs barely move together. Latitude vs longitude is the one dark blue pair (−0.79, which is −0.785 rounded by fmt=".2f"); progress vs year and budget vs duration are the only other visible tints.
Correlation is compact and suited to scanning many pairs. The scatter is detailed and required before any single pair is trusted. They are used in that order.
The matrix (or heatmap) identifies the interesting pairs quickly.
Whether it is linear, whether there are one or two clusters, and whether a single point drives the result.
"Strong, roughly linear, no obvious outliers": after these checks, the quoted r is meaningful.
A scatter takes two variables; hue, seaborn's word for "colour the dots by this column", adds a third. If the study–score trend differs between students who passed and those who did not, colored dots show it clearly.
students["passed"] = students["score"] >= 75a True/False column: did the student score 75 or more?hue="passed"colour each dot by that column; seaborn adds the legendA trend that holds overall can vanish or reverse inside subgroups. Examining groups separately is the first safeguard against a misleading aggregate.
The lab colours the dots by a third column (sleep hours) with matplotlib's
c=: the same idea, without seaborn.
the same eight dots, now coloured by passed: orange below 75, blue at 75 or above. Every passer studied 4 hours or more. Drawn here with matplotlib, because seaborn does not run in the browser; seaborn's hue= gives the same picture on a laptop.
With both axes in use, there are three sound ways to add one more variable, and one misleading way. To facet is to repeat the same chart once per group, in a grid of small panels: those panels are called small multiples.
Readers cannot rank colours accurately. Position or size is used for quantities.
d = df.dropna(subset=["budget", "duration"])keep every column, drop rows missing either numberhue="status"a category becomes colour: one colour per statuss=… / FacetGrida quantity can become dot size (with care); for many groups, a separate panel each: next slidebecause every panel uses the same axes, they can be compared directly. Central Office is the only region whose projects reach far to the right (up to about 1 billion pesos), and it tilts upward most clearly; most other panels show a tall cluster near zero budget.
The figure is the whole saved picture. Each
axes is one plotting area inside it. When plt.subplots creates a grid, each cell is a subplot.
With sharey=True the panels get a shared axis: one y
scale for all.
The figure is a sheet of paper and each axes is a box for one chart; sharing the y axis means every box uses the same ruler.
plt.subplots(1, 2, …, sharey=True)two axes side by side that share one y scaleaxes[0] / axes[1]the left and the right panelget_ylim()the y range of each panel: equal, because they share it
only the left panel prints score numbers: with sharey=True both panels use that one scale, so the same height means the same score in both. Score rises with study hours (left) and falls with sleep hours (right).
Unreadable: eighteen colours cannot be distinguished reliably, and the dots overlap.
Each is simple, and the comparison happens between panels. Differences in shape are easy to see.
Identical axis limits on every panel. Free scales make panels look alike when they are not.
A shared axis means every panel uses the same scale on that axis. Faceting compares many groups without requiring the reader to decode a legend. It works only if the scales are shared; otherwise the result is eighteen unrelated charts presented as comparable.
| Question | Chart | Common problem |
|---|---|---|
| One numeric column’s shape | Histogram | Bin count changes the picture |
| Two numeric columns | Scatter | Overplotting; log the skewed axis |
| One numeric across groups | Boxplot, ordered by median | Alphabetical order hides the pattern |
| Two categoricals | Crosstab, normalised | Raw counts only show group size |
| Many pairs at once | Heatmap, diverging, centred on 0 | Sequential colormaps hide the sign |
| Many groups, same relationship | Small multiples | Unshared axis limits |
The choice starts from the left column, not from a chart gallery. The question comes first, and the chart follows from it.
A common error in data analysis: concluding "so it must cause."
Parts A and B covered measuring and plotting a relationship. This part compares groups and considers what could have produced the relationship.
Another form of multivariate EDA: a category splits the rows, and summaries are compared across the split — passers vs non-passers, region vs region.
75 to 85. How do the two groups change?Result on the lecture laptop (select to reveal)
Those who passed studied 6.0 hours and slept 5.8; the others studied 2.0 and slept 8.3. With a pass mark of 85, only 3 students pass: they studied 7.0 hours on average, the other five 3.0.
students["score"] >= 75a True/False column that splits the students into two groups.groupby("passed")[[…]].mean()the average study and sleep hours of each groupPassers studied more and slept less, in this data. A difference between groups is a fact; its cause is still an open question.
.groupby("passed") sorts the rows into two groups; .mean() then reduces each group to one row. Passers studied 6.0 hours and slept 5.8; the others studied 2.0 and slept 8.3.
A histogram shows one distribution well. To compare eighteen, the boxplot is the only chart that stays readable.
Alphabetical order hides the pattern. Sorted, the chart shows at a glance where projects are fast and where they are slow.
groupby("region").duration.median()median duration per region.sort_values().indexsort those medians and keep only the region names, fastest firstsns.boxplot(…, order=order)one box per region, drawn in that sorted order
reading down, each box sits a little further right than the one above: slower regions are lower. Central Office, at the bottom, is clearly the slowest. The circles are single projects far longer than their region's usual range (outliers).
| Region | Projects | Q1 | Median | Q3 |
|---|---|---|---|---|
| Region I | 2,730 | 100 d | 167 d | 246 d |
| Region III | 4,428 | 121 d | 170 d | 235 d |
| Region VIII | 1,586 | 120 d | 178 d | 257 d |
| Region X | 961 | 179 d | 252 d | 348 d |
| Region VI | 881 | 169 d | 260 d | 390 d |
Region VI’s median project takes 93 days longer than Region I’s, and its spread is far wider (IQR 169–390 against 100–246). This raises a question for further inquiry; it is not an answer. (Central Office, the national headquarters, is not on the map; its 122 finished projects are slower still, median 448 days.)
one bar per region, each a rate: completed projects divided by that region's total. Region III (5,412 projects) and Central Office (180) now sit on the same 0–100% scale, so the 26-point spread between Region IX and Region XII is visible.
Region III has 5,412 projects and Central Office 180. Raw completed counts would show only which region is larger. A crosstab counts the rows for every combination of two categories (region × status).
Completion rates run from 65.6% in Region IX to 92.0% in Region XII. Normalising makes this visible.
normalize="index"divide each row by its row total, so each region's statuses add up to 1["Completed"]keep one column: the share of each region's projects that are completed( … )the outer brackets let the command continue onto the next linerate.iloc[[0, -1]]rows by position: the first (0) and the last (−1) of the sorted listA crosstab of year × status is two categories at once. A grouped bar chart puts one bar per status side by side for each year: easy to compare statuses. A stacked bar chart piles them into one bar per year: easy to see the total, harder to compare the upper pieces.
2025 projects are mostly on-going, 2023 projects mostly completed: the same "elapsed time" story as progress vs year.
pd.crosstab(df.year, df.status)count projects for every (year, status) combinationct.loc[2023:2025, […]]keep the rows 2023 to 2025 and two status columnsfew.plot.bar()one group of bars per year, one bar per status: 6 barsstacked=Truethe same 6 pieces piled into 3 bars, one per year

left, grouped: easy to see Completed shrink and On-Going grow from 2023 to 2025. Right, stacked: easy to see that 2024 had the most projects in total (5,071), but hard to compare the orange On-Going pieces, because each starts at a different height.
All three produce identical correlation matrices. Nothing inside
.corr() can distinguish between them, which is why this error is common.
Causation means changing X would change Y; a
confounder is a third variable Z that drives both.
Correlation is not causation. Analogy: the rooster crows every morning before sunrise, but it does not make the sun rise.
Ice cream sales correlate with drowning deaths. Neither causes the other; summer causes both.
A strong association is a starting point: it identifies which question merits stronger methods, such as controlled comparisons, experiments and domain knowledge.
"Study hours and scores are strongly associated (r = 0.99, linear, n = 8)."
"One more study hour causes 5.1 more points." (5.1 is the slope of the trend line.) That claim needs a design, such as an experiment, not a scatter.
Eight students provide weak evidence. Large correlations arise easily in small samples.
almost every project started by 2021 is finished; the bars drop only for the most recent years, because those projects are still under way. This picture is the whole story behind r = −0.379.
Newer projects show less progress. Stated as a coefficient it sounds like a finding. Stated as a sentence it is a tautology: true by definition, so it adds no new information.
A project started in 2025 has had less time to finish than one started in 2021. The correlation is real, but it adds nothing to what was already known.
In Region VIII, budget predicts duration reasonably well. In NCR it barely predicts duration, plausibly because urban projects are constrained by permits and traffic rather than by size. One coefficient for the whole country describes no region in particular.
Before any correlation is reported, it is recomputed inside the obvious subgroups. If the value changes substantially, the aggregate figure summarizes different relationships.
A relationship that flips sign inside every group is Simpson’s paradox. Here it does not reverse, but it ranges from 0.09 (NCR) to 0.66 (Central Office, only 122 projects), which is enough to make the average misleading.
dropna(subset=[…])drop rows missing a budget or a duration.apply(lambda g: …)run a small function on each region's pile of rows g (only the two columns picked in [[…]]): here, its own rCentral Office 0.655the top value rests on only 122 projects: exactly the warning in the comment
graduate admissions in Berkeley’s six largest departments (Bickel, Hammel & O’Connell, Science, 1975; R’s UCBAdmissions). Combined, men were admitted far more often (44.5% against 30.4%). Within departments, women did as well or better in four of six. The reason is panel 3: most women applied to the departments that admit few. The department is the confounder, and the combined number told the opposite story to most of the groups inside it.
Any two numeric columns. Compute Pearson and Spearman on them.
If they differ by more than about 0.1, explain why. Plot the scatter to check the explanation.
Recompute within regions (or within years). How much does r change? Report the range, not only the average.
One sentence stating the relationship, the strength, and one thing it does not establish.
Step 4 summarizes the approach of the course: a claim, a number and an explicit limit.
budget vs duration gives Pearson 0.365 but Spearman 0.508. What does that gap indicate?
latitude and longitude correlate at −0.785 across 30,884 projects. What is the correct interpretation?
Across cities: the more firefighters sent to a fire, the larger the fire damage (strong positive r). Should cities send fewer firefighters?
B: the confounder is the fire itself.
Fire size drives both variables, creating a real correlation with an absurd causal reading. When damage is compared within fires of similar size, the "firefighters cause damage" explanation disappears.
When a correlation implies an implausible conclusion, look for a third variable; it is usually an obvious one.
Data journalism, covered next week, depends on exactly this reasoning.
Build the frame, read its correlation matrix, scatter the strongest pair, and draw the heatmap. Then explain a negative correlation without the word "causes." About 45 minutes.
df.corr(), ax.scatter() with labels, and a heatmap drawn with
matplotlib's ax.imshow (seaborn does not run in the browser lab).
A scatter coloured by a third column, and two side-by-side panels that share one y axis.
Sign gives direction and magnitude gives consistency, for linear relationships only.
A heatmap finds the pairs; a scatter plot confirms them. Curves, clusters and influential points are hidden by r.
X→Y, Y→X, or Z→both. The matrix cannot distinguish them.
EDA raises the question; causal answers need stronger designs.
In summary: relationships are found, plotted and described exactly as strongly as the evidence allows, and no more strongly.
Exploration is complete. Weeks 9 and 10 cover communicating the results.
seaborn tutorial, "Visualizing statistical relationships": scatterplots, hue and related options, with runnable examples.
seaborn.pydata.org
Tyler Vigen's "Spurious Correlations": unrelated variable pairs with high r values, which illustrate the difference between correlation and causation.
Both are linked on the course page beside this deck and the lab.
Spurious correlations are easier to appreciate after a real one has been computed in the lab.
Finding stories in data: turning associations, gaps and outliers into questions of public interest.
DS 227 · Knowledge Discovery in Data