DS 227 · Week 8

Data Exploration II

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

Outline

Relationships between variables

Key terms · 1 of 2

Six terms for relationships

correlation (r)

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

causation

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

confounder

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

scatter plot

One dot per row: one column across (x), another up (y).

e.g. ax.scatter(students["study_hours"], students["score"])

trend line

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

heatmap

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)

Key terms · 2 of 2

Six terms for building charts

figure / axes

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

subplot

One of several axes arranged in a grid inside one figure.

e.g. plt.subplots(1, 2) makes two side by side

shared axis

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)

hue / facet

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

pair plot

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

grouped / stacked bar

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

Previous session

A trend is hard to see in a table

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({ "study_hours": [2, 5, 1, 8, 6, 3, 7, 4], "sleep_hours": [8, 6, 9, 5, 6, 8, 5, 7], "score": [65, 82, 60, 95, 88, 70, 90, 78], }) print(students) study_hours sleep_hours score 0 2 8 65 1 5 6 82 2 1 9 60 3 8 5 95 4 6 6 88 5 3 8 70 6 7 5 90 7 4 7 78
  • students = pd.DataFrame({…})eight students: hours studied, hours slept, exam score (the lab calls this table df)

The two questions of the week

How strongly two columns move together, and what that relationship looks like.

About the tool

Pearson’s correlation is not Pearson’s alone

1844

Bravais

Auguste Bravais derives and publishes the formula.

1880s

Galton

Francis Galton develops the idea of co-relation.

1890s

Pearson

Karl Pearson builds Galton’s idea into the modern coefficient r.

1904

Spearman

Charles Spearman introduces rank correlation.

SourceWikipedia: Pearson correlation coefficient; Spearman’s rank correlation

About the tool

Where the two coefficients appear today

Sourcepandas: DataFrame.corr; Wikipedia: Spearman’s rank correlation; values from this deck’s DPWH example

Runnable code

Code and charts on these slides run in the browser

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.

What does not run here

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.

import io, sys print("pandas version:", pd.__version__) print("64-bit Python:", sys.maxsize > 2**32) t = pd.read_csv(io.StringIO("city,pop\nCebu,964000")) print(t.dtypes) pandas version: 3.0.5 64-bit Python: True city str pop int64 dtype: object
  • pd.__version__the installed pandas: 3.0.5 on the laptop, 2.2.0 in the browser
  • t.dtypeseach column’s type: str on the laptop, object in the browser
Part A

Correlation

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

Definition

What is Pearson correlation?

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

Formally

r = Σ(xi − x̄)(yi − ȳ)  ÷  √[ Σ(xi − x̄)² × Σ(yi − ȳ)² ]

Pearson (1896); Freedman, Pisani & Purves, Statistics, 4th ed., ch. 8.

PartFor 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 products214
bottom: the √ part√(42 × 1,104) = 215.3; it rescales r to −1…+1
r214 ÷ 215.3 = 0.994
Scatter of the eight students, study hours across and score up, split into four quadrants by dashed lines at the mean study hours (4.5) and the mean score (78.5). Two quadrants, above both means and below both means, are shaded green and marked plus; the other two are shaded red, marked minus, and are empty. For the student with 8 hours and 95 points, arrows show 3.5 hours above the mean and 16.5 points above the mean, a product of 57.75. Title: all 8 products positive, so r = +0.99.
The coefficient r

One scale, from −1 to +1

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.

rReads asExample
+1.0perfect togetherheight in cm vs inches
+0.7strong positivestudy hours vs score
0.0no linear linkshoe size vs exam score
−0.7strong negativeabsences vs grades
−1.0perfect oppositetime used vs time left
The coefficient r

Five clouds, five values of r

Five small scatter plots of 40 dots each. At r = −1.0 the dots lie on a falling line; at −0.7 they fall loosely; at 0 they form a shapeless cloud; at +0.7 they rise loosely; at +1.0 they lie on a rising line.
Exercise · 3 min

.corr() builds the whole matrix

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

Tasks

  1. Predict the sign of the sleep_hours–score correlation.
  2. Select ▶ Run / Edit and run the code.
  3. Change the third student’s sleep from 9 to 4 hours and run again. What happens to that correlation?

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: the eight students from the first slide print(students.corr().round(2))
  • 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)

Reading one cell

study ↔ score = 0.99: in this small dataset, study hours and scores rise together almost perfectly.

Output

Reading the matrix: a diagonal of 1s and a mirror

The students' correlation matrix as a 3 by 3 grid of coloured cells, rows and columns study_hours, sleep_hours and score. The diagonal cells, outlined in amber, read 1.00. study_hours with score is +0.99 (dark blue); sleep_hours with each of the other two is −0.98 (dark red). Each off-diagonal value appears twice, mirrored across the diagonal.
Case study

The flood data, loaded from the course API

The rest of Part A measures relationships among the flood projects’ six numeric columns, including week 6’s duration.

Why not 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.

import io, requests url = "https://portal.latarak.com/api/flood/export.csv" resp = requests.get(url, timeout=60) df = pd.read_csv(io.StringIO(resp.text)) # week 6's derived column: days from start to completion for col in ["start_date", "completion_date"]: df[col] = pd.to_datetime(df[col], errors="coerce") df["duration"] = (df.completion_date - df.start_date).dt.days cols = ["budget", "duration", "progress", "year", "latitude", "longitude"] print(df.shape) (34079, 16)
  • df["duration"] = …days from start to completion; NaN where a date is missing
  • cols = […]the six numeric columns used on the next slides
  • (34079, 16)34,079 projects; 15 columns from the file plus duration
The full matrix

Fifteen pairs, ranked by strength

Lollipop chart of the 15 correlations among budget, duration, progress, year, latitude and longitude, sorted by size. Four stand outside a shaded band from −0.2 to +0.2: latitude–longitude −0.785, progress–year −0.379, budget–duration +0.365, budget–year +0.265. The other eleven are close to 0.
The full matrix

Six columns, every pair at once

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.

Scanning, not concluding

A correlation matrix is a list of things worth plotting. It is not a list of findings.

short = df[cols].rename(columns={"duration": "dur", "progress": "prog", "latitude": "lat", "longitude": "lon"}) print(short.corr().round(3)) budget dur prog year lat lon budget 1.000 0.365 -0.021 0.265 -0.054 0.047 dur 0.365 1.000 -0.096 -0.057 -0.104 0.078 prog -0.021 -0.096 1.000 -0.379 -0.026 0.049 year 0.265 -0.057 -0.379 1.000 0.013 -0.027 lat -0.054 -0.104 -0.026 0.013 1.000 -0.785 lon 0.047 0.078 0.049 -0.027 -0.785 1.000
  • .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)
Main pair

r = 0.365 as a picture, and r² as 13 squares in 100

Left: hexbin density of the 27,664 projects, budget on a log axis from 1 million to 1 billion pesos against duration in days; the darkest cells rise gently from about 100 days at 1 million pesos to about 250 days at 100 million, with a wide spread above. Right: a 10 by 10 grid of squares with 13 filled in blue, labelled r squared = 0.365 squared = 0.133; budget accounts for about 13% of the variation in duration.
Main pair

Larger projects take moderately longer

r = 0.365 across 27,664 finished projects. Positive and plausible: more money usually means more work.

Interpreting r²

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.

sub = df[["budget", "duration"]].dropna() print(len(sub)) print(round(sub.budget.corr(sub.duration), 3)) print(round(0.365**2, 3)) # r squared 27664 0.365 0.133
  • df[["budget", "duration"]].dropna()keep the two columns, then drop every row missing either one
  • sub.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²
Definition

What is Spearman correlation?

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.

Formally

ρ = 1 − 6 Σdi² ÷ [n(n² − 1)]

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.

ProjectBudget (₱M)DaysBudget rankDays rankd
A110110
B23023−1
C32032+1
D440440
E10050550

Five made-up projects. Only B and C are out of order, so Σd² = 2:

ρ = 1 − 12 ÷ 120 = 0.90

Pearson on the same values gives only 0.721, because E’s ₱100M sits far from any straight line.

Two panels for five made-up projects. Top: budget in millions of pesos against duration in days; A to D sit at budgets 1 to 4, E at 100; a dashed straight line fits poorly; titled Values: Pearson r = 0.721. Bottom: budget rank against duration rank; A, D and E lie on the diagonal; B (rank 2, 3) and C (rank 3, 2) sit off it, marked d = minus 1 and d = plus 1; titled Ranks: Spearman = 0.90. A note says E is simply 5th, so the 100 million no longer pulls.
Pearson vs Spearman

Ranks straighten the cloud, so r rises from 0.365 to 0.508

Left: hexbin of budget in millions of pesos (0 to 300) against duration in days; most projects crowd the left third, titled Raw values: Pearson r = 0.365. Right: the same projects as percentile ranks of budget against percentile ranks of duration, both 0 to 100; the cells fill the square evenly and darken toward the lower left and upper right corners, titled Ranks: Spearman = 0.508.
Pearson vs Spearman

Two coefficients for the same pair; the gap is informative

# sub: budget and duration, both present # Pearson: straight-line strength print(round(sub.budget.corr(sub.duration), 3)) 0.365
# Spearman: agreement of the RANKS print(round(sub.budget.rank().corr(sub.duration.rank()), 3)) 0.508
Transforming the shape

Budgets piled on the left; log₁₀ spreads them out

Two histograms. Left: budget in millions of pesos, 0 to 300; most projects pile up below 100 million, with tall spikes at 50 and 100 million; titled r = 0.365. Right: log10 of budget, from about 5.5 to 9; the projects spread across the range with a peak near 50 million pesos; titled r = 0.396.
Transforming the shape

Logging the skewed variable raises Pearson

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.

Two methods, same conclusion

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.

lg = sub[sub.budget > 0] print(round(np.log10(lg.budget).corr(lg.duration), 3)) 0.396
Binning

r = 0.365 examined by budget quartile

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.

6,916 projects in every band

The groups are equal-sized by construction, so the comparison is fair and no band rests on a small sample.

sub["band"] = pd.qcut(sub.budget, 4, labels=["Q1 small", "Q2", "Q3", "Q4 large"]) print(sub.groupby("band", observed=True).duration.median()) band Q1 small 119.0 Q2 189.0 Q3 226.0 Q4 large 269.0 Name: duration, dtype: float64
  • 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
Interpreting 0.508

The pattern behind the rank correlation

Bar chart of median duration for four budget bands of 6,916 projects each: Q1 smallest 119 days, Q2 189 days (1.6 times), Q3 226 days (1.9 times), Q4 largest 269 days (2.3 times). The bars rise at every step.
Limitations

Three things a correlation does not show

Three scatter plots. A perfect curve: 25 dots on a U shape, r = 0.00. Two clusters: a green cloud at the lower left and an orange cloud at the upper right, each with r near 0 inside it (−0.05 and +0.10), but r = 0.92 when combined. One influential point: 20 dots with r = 0.00, and one red point far to the upper right that raises r to 0.79.
Same r, different data

Thirteen datasets, one set of numbers

Thirteen small scatter plots of 142 points each: a dinosaur, a scattered cloud, a bullseye, a circle, a grid of dots, horizontal lines, two high bands, slanted lines down, slanted lines up, a star, vertical lines, two wide bands and an X. A box notes that all thirteen share mean x 54.3, mean y 47.8, standard deviation x 16.8 and y 26.9, and r between −0.06 and −0.07.
A correlation of −0.785

latitude vs longitude

Strong, real and reproducible, but without substantive meaning.

No causal mechanism

Plotted, latitude against longitude is a map

Scatter of 30,884 projects with longitude across (117 to 127 degrees east) and latitude up (5 to 21 degrees north). The dots trace the outline of the Philippines, from Luzon in the north-west to Mindanao in the south-east. A red fitted line runs from upper left to lower right along the archipelago. Title: 30,884 projects, r = −0.785.
No causal mechanism

The correlation reflects the shape of the country

Across 30,884 geocoded projects, latitude and longitude correlate at −0.785, stronger than any other pair in the matrix. No mechanism is involved.

The Philippines runs northwest to southeast

Locations further south are also further east. The correlation is a fact about the archipelago’s outline, not about flood control.

ll = df[["latitude", "longitude"]].dropna() print(len(ll)) print(round(ll.latitude.corr(ll.longitude), 3)) print(ll.latitude.agg(["min", "max"]).round(2).tolist()) print(ll.longitude.agg(["min", "max"]).round(2).tolist()) 30884 -0.785 [5.01, 20.79] [117.06, 126.57]
  • .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
Why this example is useful

No causal explanation is plausible

Review question

Question (select to reveal the answer)

In the matrix, study_hours ↔ sleep_hours = −0.98. What does that number claim?

A · Studying causes sleep loss
B · Students who studied more tended to sleep less — a strong opposite pattern
C · The data is broken; negatives are errors
D · Sleep barely relates to study

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.

Break

  Five minutes

Next: plots that show what the number cannot.

Part B

Visualizing relationships

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.

Exercise · 3 min

The scatter plot: one dot per row

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.

Tasks

  1. Predict the shape the eight dots will make.
  2. Select ▶ Run / Edit and run the code.
  3. Change "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.

# students: the eight students from the first slide fig, ax = plt.subplots() ax.scatter(students["study_hours"], students["score"]) ax.set_xlabel("Study hours") ax.set_ylabel("Score") plt.show()
  • ax.scatter(students["study_hours"], students["score"])one dot per student: x from one column, y from another
  • set_xlabel / set_ylabelname each axis

Lab result

Eight dots rising steadily to the upper right: the shape that r = 0.99 summarizes in one number.

Output

Eight dots rising to the upper right

Scatter plot of study hours (across, 1 to 8) against score (up, 60 to 95) for the eight students; the dots rise almost in a straight line from 1 hour and 60 points to 8 hours and 95 points.
Exercise · 3 min

One straight line through the dots

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.

Description, not explanation

"Each extra study hour goes with about 5.1 more points" in these 8 students. Not "causes": that is Part C.

Tasks

  1. Predict roughly how many points each extra hour of study adds.
  2. Select ▶ Run / Edit and run the code.
  3. Change 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.

# students: the eight students from the first slide import numpy as np slope, intercept = np.polyfit(students["study_hours"], students["score"], 1) print(round(slope, 1), round(intercept, 1)) xs = np.array([1, 8]) fig, ax = plt.subplots() ax.scatter(students["study_hours"], students["score"]) ax.plot(xs, slope * xs + intercept) plt.show()
  • np.polyfit(x, y, 1)fit a straight line (degree 1): returns its slope and intercept
  • slope * xs + interceptthe line’s height at the two ends, 1 and 8 hours
Output

The line passes close to every dot

The same eight-dot scatter with a straight line drawn from about 60.7 points at 1 hour to about 96.3 points at 8 hours; every dot sits close to the line.
27,664 dots

Overplotting in a large scatter plot

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 hides the mass

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") plt.show() # fix: a reproducible sample of 2,000 projects df.sample(2000, random_state=42).plot.scatter(x="budget", y="duration") plt.show() # fix: count the projects in hexagonal cells df.plot.hexbin(x="budget", y="duration", gridsize=40) plt.show()
  • df.plot.scatter(x="budget", y="duration")27,664 dots, most of them on top of each other
  • df.sample(2000, random_state=42)fix 1: a reproducible sample of 2,000 projects
  • df.plot.hexbin(…, gridsize=40)fix 2: count the projects in hexagonal cells; darker = more
Output

27,664 dots forming one solid block

Scatter of budget (across, 0 to about 1.05 billion pesos, marked 1e9) against duration (up, 0 to about 2,700 days); almost all the dots merge into a solid blue block near the bottom-left corner, with a few dots trailing to the right.
Output

Two remedies: fewer dots, or counts in cells

Scatter of a random 2,000 projects, budget against duration; the block thins out so single dots are visible, and the budget axis now ends near 700 million pesos (7 on a 1e8 scale).Hexbin chart of budget against duration: the plot is covered in hexagonal cells shaded from white to dark green by how many projects fall in each; the darkest cells, over 3,000 projects each, sit right next to the origin.
Log axis

The same plot on a log axis

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.

Stating it in the caption

"x-axis is logarithmic" is one clause and prevents a reader from misjudging every distance on the chart.

ax = df.plot.scatter(x="budget", y="duration", alpha=0.05) ax.set_xscale("log") plt.show()
  • alpha=0.05each dot 95% transparent, so crowded areas look darker
  • ax.set_xscale("log")equal steps mean equal ratios: 10M to 100M is as wide as 100M to 1B
Output

Log axis and transparency reveal the dense region

Scatter of budget on a logarithmic x axis (10 to the 6 up to 10 to the 9 pesos) against duration in days, drawn with very faint dots; the dots form a dense band between 10 million and 100 million pesos, and the cloud tilts upward to the right.
Many pairs at once

Heatmap: the matrix in colour

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.

# students: the eight students from the first slide import seaborn as sns sns.heatmap(students.corr(), annot=True, cmap="coolwarm", center=0) plt.show()

Key settings

annot=True prints the numbers on the cells; center=0 anchors white at zero so that the sign is easy to read.

Output

Three columns, nine coloured cells

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.

3-by-3 heatmap of the correlations between study_hours, sleep_hours and score, each cell labelled with its value: dark red cells for 1 and 0.99, dark blue cells for -0.98, with a colour bar on the right.
Every pair plotted

The pair plot: the matrix as scatter plots

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.

Size limit

3 columns make 9 panels; 10 columns make 100. Only the few columns identified by the heatmap are included.

# students: the eight students from the first slide import seaborn as sns g = sns.pairplot(students) print(g.axes.shape) plt.show() # add hue= to colour every panel by a group, # e.g. sns.pairplot(students, hue="passed") (3, 3)
  • 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 panels
  • diagonal panelsa column against itself would be a straight line, so each shows that column's histogram instead
Output

Nine panels: three histograms and six scatter plots

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

Pair plot of study_hours, sleep_hours and score: a 3-by-3 grid with a histogram of each column on the diagonal and scatter plots elsewhere; the study-hours and score panels rise, every sleep-hours panel falls.
Heatmap

The correlation matrix as a heatmap

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.

Diverging colormap, centred on zero

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 sns sns.heatmap(df[cols].corr(), annot=True, fmt=".2f", cmap="RdBu_r", center=0, vmin=-1, vmax=1) plt.show()
  • 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 decimals
  • cmap="RdBu_r", center=0red-blue colours, white exactly at r = 0
  • vmin=-1, vmax=1fix the colour scale to the full −1 to +1 range
Output

Mostly pale cells, with one dark pair

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

6-by-6 heatmap of correlations between budget, duration, progress, year, latitude and longitude, red for positive and blue for negative with white at zero, each cell labelled to two decimals; the darkest off-diagonal cells are latitude with longitude at -0.79 in dark blue, then progress with year at -0.38 and budget with duration at 0.37.
Division of labour

The number ranks pairs; the picture explains them

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.

Step 1 · Scan with r

The matrix (or heatmap) identifies the interesting pairs quickly.

Step 2 · Verify with a scatter

Whether it is linear, whether there are one or two clusters, and whether a single point drives the result.

Step 3 · Then state the claim

"Strong, roughly linear, no obvious outliers": after these checks, the quoted r is meaningful.

A third dimension

Coloring the dots by a category

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: the eight students from the first slide import seaborn as sns students["passed"] = students["score"] >= 75 sns.scatterplot(data=students, x="study_hours", y="score", hue="passed") plt.show()
  • 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 legend

Importance

A trend that holds overall can vanish or reverse inside subgroups. Examining groups separately is the first safeguard against a misleading aggregate.

In the lab

The lab colours the dots by a third column (sleep hours) with matplotlib's c=: the same idea, without seaborn.

Output

Colour adds a third column to the scatter

The eight-student scatter of study hours against score, with the three students below 75 points (1, 2 and 3 hours; 60, 65 and 70 points) in orange and the five at 75 or above in blue; a dotted line marks 75.
A third variable

Colour, size or a separate panel

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.

Colour is for categories, not numbers

Readers cannot rank colours accurately. Position or size is used for quantities.

import seaborn as sns # keep every column, drop rows missing either number d = df.dropna(subset=["budget", "duration"]) # a category becomes colour sns.scatterplot(data=d, x="budget", y="duration", hue="status", alpha=0.3) plt.show()
  • d = df.dropna(subset=["budget", "duration"])keep every column, drop rows missing either number
  • hue="status"a category becomes colour: one colour per status
  • s=… / FacetGrida quantity can become dot size (with care); for many groups, a separate panel each: next slide
Output

Eighteen regions, one shared scale

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

import seaborn as sns # d: the projects with both numbers (previous slide) g = sns.FacetGrid(d, col="region", col_wrap=4) g.map(plt.scatter, "budget", "duration") plt.show()

Open the chart full size

Eighteen small scatter plots of budget against duration, one per region, four per row, all on the same axes (duration 0 to about 2,700 days, budget 0 to about 1 billion pesos); in almost every panel the dots crowd into the bottom-left corner, while the Central Office panel spreads far to the right and upward.
Several charts, one figure

Figure, axes, subplots and a shared axis

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.

# students: the eight students from the first slide fig, axes = plt.subplots(1, 2, figsize=(8, 3), sharey=True) axes[0].scatter(students["study_hours"], students["score"]) axes[1].scatter(students["sleep_hours"], students["score"]) print(axes.shape) print("shared y:", axes[0].get_ylim() == axes[1].get_ylim()) plt.show() (2,) shared y: True
  • plt.subplots(1, 2, …, sharey=True)two axes side by side that share one y scale
  • axes[0] / axes[1]the left and the right panel
  • get_ylim()the y range of each panel: equal, because they share it
Output

Two panels with one scale for score

Two side-by-side scatter plots sharing one y axis for score (60 to 95): on the left, study hours 1 to 8 with the dots rising; on the right, sleep hours 5 to 9 with the dots falling. Only the left panel shows y-axis numbers.
Small multiples

Eighteen small panels with one shared scale

Choice of chart

The comparison determines the chart

QuestionChartCommon problem
One numeric column’s shapeHistogramBin count changes the picture
Two numeric columnsScatterOverplotting; log the skewed axis
One numeric across groupsBoxplot, ordered by medianAlphabetical order hides the pattern
Two categoricalsCrosstab, normalisedRaw counts only show group size
Many pairs at onceHeatmap, diverging, centred on 0Sequential colormaps hide the sign
Many groups, same relationshipSmall multiplesUnshared axis limits
Part C

Correlation and causation

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.

Exercise · 3 min

Split, then summarize

Another form of multivariate EDA: a category splits the rows, and summaries are compared across the split — passers vs non-passers, region vs region.

Tasks

  1. Predict which group studied more on average.
  2. Select ▶ Run / Edit and run the code.
  3. Change 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: the eight students from the first slide students["passed"] = students["score"] >= 75 print(students.groupby("passed")[ ["study_hours", "sleep_hours"] ].mean().round(1))
  • students["score"] >= 75a True/False column that splits the students into two groups
  • .groupby("passed")[[…]].mean()the average study and sleep hours of each group

Interpretation

Passers studied more and slept less, in this data. A difference between groups is a fact; its cause is still an open question.

Output

Split, then summarize, as a picture

Diagram in three steps. 1: the eight students as rows of study hours, sleep hours and score, coloured blue if the score is 75 or more and orange otherwise. 2: groupby sorts them into two boxes, five who passed and three who did not. 3: the mean of each box: passers studied 6.0 hours and slept 5.8; the others studied 2.0 and slept 8.3.
Comparing groups

One box per region, eighteen distributions at once

A histogram shows one distribution well. To compare eighteen, the boxplot is the only chart that stays readable.

Ordering by the median

Alphabetical order hides the pattern. Sorted, the chart shows at a glance where projects are fast and where they are slow.

import seaborn as sns order = (df.groupby("region").duration .median().sort_values().index) sns.boxplot(data=df, x="duration", y="region", order=order) plt.show()
  • groupby("region").duration.median()median duration per region
  • .sort_values().indexsort those medians and keep only the region names, fastest first
  • sns.boxplot(…, order=order)one box per region, drawn in that sorted order
Output

Sorted by median, the boxes shift to the right

Horizontal box plots of project duration in days for 18 regions, sorted by median from Region I at the top to Central Office at the bottom; most boxes sit between about 100 and 400 days, many outlier circles stretch right to about 2,700 days, and the Central Office box is clearly further right than the rest.
Interpreting the boxes

A 93-day gap between the fastest and slowest region on the map

RegionProjectsQ1MedianQ3
Region I2,730100 d167 d246 d
Region III4,428121 d170 d235 d
Region VIII1,586120 d178 d257 d
Region X961179 d252 d348 d
Region VI881169 d260 d390 d
Two categories

Eighteen completion rates, from 65.6% to 92.0%

Horizontal bar chart of the share of each region's projects that are completed, sorted. Region XII is highest at 92.0% (blue); Region IX is lowest at 65.6% (red), just below Central Office; the other sixteen regions fall between about 75% and 89%.
Two categories

Rates, not counts, when the groups differ in size

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

A 26-point spread

Completion rates run from 65.6% in Region IX to 92.0% in Region XII. Normalising makes this visible.

rate = (pd.crosstab(df.region, df.status, normalize="index")["Completed"] .sort_values().round(3)) print(rate.iloc[[0, -1]]) # lowest and highest of 18 region Region IX 0.656 Region XII 0.920 Name: Completed, dtype: float64
  • 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 line
  • rate.iloc[[0, -1]]rows by position: the first (0) and the last (−1) of the sorted list
Two categories in one chart

Grouped bars compare; stacked bars add up

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

What the numbers show

2025 projects are mostly on-going, 2023 projects mostly completed: the same "elapsed time" story as progress vs year.

ct = pd.crosstab(df.year, df.status) few = ct.loc[2023:2025, ["Completed", "On-Going"]] print(few) few.plot.bar() # grouped plt.show() few.plot.bar(stacked=True) # stacked plt.show() status Completed On-Going year 2023 3842 613 2024 3216 1855 2025 375 2615
  • pd.crosstab(df.year, df.status)count projects for every (year, status) combination
  • ct.loc[2023:2025, […]]keep the rows 2023 to 2025 and two status columns
  • few.plot.bar()one group of bars per year, one bar per status: 6 bars
  • stacked=Truethe same 6 pieces piled into 3 bars, one per year
Output

The same six numbers answer two different questions

Grouped bar chart for 2023, 2024 and 2025 with a blue Completed bar and an orange On-Going bar per year: Completed falls from 3,842 to 375 while On-Going rises from 613 to 2,615.Stacked bar chart of the same numbers: one bar per year with Completed in blue at the bottom and On-Going in orange on top; totals are about 4,455, 5,071 and 2,990.
Key principle

Three explanations for "X and Y move together"

Three arrow diagrams. 1, X drives Y: study hours with an arrow to score, studying raises scores. 2, Y drives X: score with an arrow back to study hours, strong students choose to study more. 3, Z drives both: motivation with arrows down to study hours and to score, which are joined only by a dashed line with no arrow. Caption: all three give the same dots and the same r = 0.99.
Limits of EDA

EDA generates hypotheses; it does not confirm them

A strong association is a starting point: it identifies which question merits stronger methods, such as controlled comparisons, experiments and domain knowledge.

EDA can say

"Study hours and scores are strongly associated (r = 0.99, linear, n = 8)."

EDA cannot say

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

Reporting n

Eight students provide weak evidence. Large correlations arise easily in small samples.

A trivial correlation

Newer projects have simply had less time

Bar chart of mean progress by the year a project started, 2016 to 2026. Every year to 2021 is near 99 to 100%; then 98.9 in 2022, 97.2 in 2023, 83.8 in 2024, 57.1 in 2025 and 0.0 in 2026. Bars from 2024 on are orange. Title: newer projects have had less time, r = −0.379.
A trivial correlation

progress vs year, 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.

Time is the mechanism

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.

print(df.groupby("year").progress.mean().round(1).loc[2021:]) year 2021 99.4 2022 98.9 2023 97.2 2024 83.8 2025 57.1 2026 0.0 Name: progress, dtype: float64
One pair, eighteen regions

The national number hides the variation

Dot plot of the budget-duration correlation inside each of the 18 regions, sorted, with a dashed line at the national r = 0.365. NCR is lowest at 0.090, then Region IV-B and Region II near 0.11 to 0.12 (red); Central Office is highest at 0.655 and Region VIII at 0.623 (green); the rest lie between 0.26 and 0.55.
Guideline

Checking whether a relationship holds within groups

Before any correlation is reported, it is recomputed inside the obvious subgroups. If the value changes substantially, the aggregate figure summarizes different relationships.

Simpson’s paradox

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.

r = (df.dropna(subset=["budget", "duration"]) .groupby("region")[["budget", "duration"]] .apply(lambda g: g.budget.corr(g.duration)) .sort_values(ascending=False).round(3)) print(r.iloc[[0, 1, -2, -1]]) # top two, bottom two region Central Office 0.655 Region VIII 0.623 Region IV-B 0.112 National Capital Region 0.090 dtype: float64
  • 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 r
  • Central Office 0.655the top value rests on only 122 projects: exactly the warning in the comment
Simpson’s paradox

When splitting reverses the story: UC Berkeley, 1973

Three bar charts. 1, all six departments together: 44.5% of men admitted against 30.4% of women. 2, department by department, A to F: women's admission rate is higher in departments A, B, D and F, marked with triangles. 3, who applied where: 51.5% of men applied to departments A or B, which admit over 60%, against 7.2% of women.
Exercise · 8 min

Examining a correlation

1 · Pick a pair

Any two numeric columns. Compute Pearson and Spearman on them.

2 · Explain the gap

If they differ by more than about 0.1, explain why. Plot the scatter to check the explanation.

3 · Split it

Recompute within regions (or within years). How much does r change? Report the range, not only the average.

4 · Write the summary sentence

One sentence stating the relationship, the strength, and one thing it does not establish.

Review question

Question (select to reveal the answer)

budget vs duration gives Pearson 0.365 but Spearman 0.508. What does that gap indicate?

A · One of the two calculations is wrong
B · The relationship is monotonic but not linear — consistent with a strongly skewed budget column
C · There is no real relationship; the numbers disagree
D · Spearman always returns a larger value than Pearson
B. Spearman only assumes order; Pearson assumes a straight line. When ranks agree more than the raw values do, the relationship is real but curved, here because budget has skew 5.13. Taking log₁₀(budget) raises Pearson to 0.396, which confirms it. D is false: the order can go either way.
Review question

Question (select to reveal the answer)

latitude and longitude correlate at −0.785 across 30,884 projects. What is the correct interpretation?

A · Southern regions receive systematically different funding
B · It reflects the geographic shape of the archipelago and carries no causal content
C · The coordinates were recorded incorrectly
D · With n = 30,884 the correlation must be meaningful
B. The Philippines runs northwest to southeast, so going south means going east. The coefficient is strong, the sample is large, and it still means nothing about flood control. A large n makes an estimate precise, not meaningful. The greater risk is a pair for which a mechanism can be invented.
Review question

Question (select to reveal the answer)

Across cities: the more firefighters sent to a fire, the larger the fire damage (strong positive r). Should cities send fewer firefighters?

A · Yes — the data says firefighters cause damage
B · No — fire size confounds: big fires get more firefighters AND do more damage
C · Yes, but only for small fires
D · The correlation must be a computation error

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.

Glossary

Terms introduced this week

Relationships

multivariate
several variables at once
correlation (r)
−1 to +1: how closely two columns follow a line
correlation matrix
r for every pair of columns, in a grid
r²
share of the variation a straight line accounts for
Pearson / Spearman
r on the values / r on their ranks
monotonic / linear
always the same direction / a straight line
causation
changing X would change Y; correlation is not causation
confounder
a third variable that drives both X and Y
trend line
best-fitting straight line; its slope is y per unit of x
crosstab
counts for every combination of two categories
tautology
true by definition, so it adds no information
n
the number of rows a statistic rests on

Charts

scatter plot
one dot per row, x across and y up
overplotting
too many dots on top of each other to count
log scale
an axis where each step multiplies (1M, 10M, 100M)
heatmap
grid of cells coloured by value
colormap
numbers to colours; diverging for ± values
pair plot
scatter for every pair, histograms on the diagonal
figure / axes
the whole picture / one plotting area in it
subplot
one axes in a grid of axes
shared axis
every panel uses the same scale
hue / facet
colour by group / one panel per group
small multiples
the same chart repeated per group
grouped / stacked bar
bars side by side / piled into one
This week's lab

Eight students, three variables

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.

Lab tasks

df.corr(), ax.scatter() with labels, and a heatmap drawn with matplotlib's ax.imshow (seaborn does not run in the browser lab).

Optional extension

A scatter coloured by a third column, and two side-by-side panels that share one y axis.

Summary

Four main points

Readings

Preparation for next week

Next week

Data journalism

Finding stories in data: turning associations, gaps and outliers into questions of public interest.

DS 227 · Knowledge Discovery in Data