Activity 27 — PCA I: Many Measurements, Few Axes
Six stats per Pokémon, two invented axes, and how to tell whether they mean anything
Hands-on companion to the first PCA lecture, written for students with no previous statistics, on all 1,025 Pokemon. A rotating 3-D plot of three stats, the correlation table and why correlated columns are kept, where PC1 comes from, scaling, running prcomp(), variance explained, a scree plot, checking PC1 against who sits at each end, and a hover-to-name plot of the scores. Homework repeats it on Generation I only.
In-class Activity 27: Many Measurements, Few Axes 🔴
Today’s Objectives
- See the data in 3-D, and why six columns cannot be drawn
- Notice the six stats are correlated — and why that is what makes PCA work
- Understand where a principal component comes from, in words
- Know why you must scale before you run it
- Run it — one line,
prcomp() - Read variance explained, and draw a scree plot
- Check PC1 by looking at who sits at each end — and hover to find them
- In-class skeleton:
27_pca_skeleton.R→ save it asscripts/27_pca.R - Homework:
27_pca_homework.R→ save it under that same name. This is what you turn in. - Data:
pokemon_1025.csv→ yourdata/folder. Class and homework both use it. - Packages:
tidyverseandplotly— both already installed from earlier weeks.
- The skeleton has a numbered section for every Part below, and almost nothing else.
- ▶ Type this — type the code into that section yourself, then run it. The code is short on purpose.
- ▶ Already in your skeleton — a few long or unfamiliar blocks are written for you. Just run them.
- The explanations live here, on this page, not in the script.
- 💭 Think lines are for talking over with your neighbour. Nothing to write down; nothing graded.
- You do not turn in
scripts/27_pca.R. You turn in the homework.
PCA is not a test. No null hypothesis, no p-value, no assumptions to check. Nothing passes and nothing fails.
You judge the result by whether you can explain what the axes mean.
Part 1 · Why Pokémon
Because you can check the answer.
PCA hands back new axes that it invented, and you have to decide whether they mean anything. That is nearly impossible on data you do not know. But if an axis puts Magikarp at one end and Mewtwo at the other, you know exactly what it found.
The six stats we will use:
| Column | What it is |
|---|---|
hp |
hit points |
attack |
physical attack |
defense |
physical defence |
sp_attack |
special attack |
sp_defense |
special defence |
speed |
speed |
Game-design numbers, but they behave exactly like six measurements off an animal — length, mass, wingspan. Treat them that way.
Part 2 · Read it in, and mark the legendaries
▶ Already in your skeleton (section 2) — just run it:
library(tidyverse)
library(plotly)
pokemon <- read_csv("data/pokemon_1025.csv") %>%
mutate(status = case_when(
is_legendary ~ "legendary",
is_mythical ~ "mythical",
TRUE ~ "regular"))
pokemon %>% count(status)- 1,025 rows, one per Pokémon: 71 legendary, 23 mythical, 931 regular
statussqueezes two TRUE/FALSE columns into one column we can colour bycase_when()reads top to bottom — the first line that matches wins, andTRUE ~catches everything left- PCA will never see
status. We only use it to colour the results afterwards
Part 3 · Three stats in 3-D
▶ Already in your skeleton (section 3) — just run it:
plot_ly(pokemon, x = ~attack, y = ~defense, z = ~speed,
color = ~status, text = ~name,
colors = c("firebrick", "darkorange", "grey60"),
type = "scatter3d", mode = "markers", marker = list(size = 3))The plot opens in the Viewer pane. Every dot is one Pokémon, placed by three of its stats.
- Click and drag to rotate it. From some angles the cloud is a shapeless blob; from others it is long and spread out. Same data, different amount you can see.
- Hover over a dot to see its name. The red and orange ones (legendary, mythical) sit out at the big end.
plot_ly()uses~columnwhere ggplot usesaes(column). That is the only new idea here.
Turning the cloud to find the angle with the most spread is exactly what PCA does.
But this plot shows only 3 of the 6 stats. hp, sp_attack and sp_defense are missing, and there is no way to add them — there is no six-dimensional plot. Drawing all the pairs instead takes 15 scatterplots, and “which Pokémon are similar?” is a question about all six numbers at once.
PCA does the rotating for us, in six dimensions.
💭 Think: Find an angle where the cloud looks most spread out. Which direction does the long side of the cloud run — towards Pokémon that are high on everything, or something else?
Part 4 · Pull the six stats into their own table
▶ Type this (section 4):
poke_stats <- pokemon %>%
select(hp, attack, defense, sp_attack, sp_defense, speed)
dim(poke_stats)- 1,025 rows, 6 columns. Numbers only — no names, no
status. PCA cannot handle text - The rows are in the same order as
pokemon. That is what lets us glue results back onto the names in Part 11
If you arrange() pokemon but not poke_stats, nothing will warn you — and every name will be attached to the wrong Pokémon.
Part 5 · Do the stats move together?
▶ Type this (section 5):
poke_stats %>%
cor() %>%
round(2)A correlation matrix — every column against every column. +1 = perfectly together, 0 = no relationship, −1 = perfectly opposite. The diagonal is all 1.00 (each column against itself) — ignore it.
| Pair | r | Reading |
|---|---|---|
defense & sp_defense |
0.50 | move together |
sp_attack & sp_defense |
0.49 | move together |
hp & attack |
0.48 | move together |
speed & defense |
0.01 | nothing at all |
So the six columns are not six independent facts. They overlap. Correlation is redundancy, and PCA’s whole job is to squeeze the redundancy out.
That rule comes from regression, where two correlated predictors fight over the same slope.
In PCA, correlation is the fuel. Correlated stats simply land on the same new axis — that is the squeezing. In fact, with scale. = TRUE, PCA is built directly from this correlation table.
The one real caution: do not put the same thing in twice — say, a “total stats” column next to the six stats it was added up from. Here the biggest r is 0.50, nowhere near a duplicate.
💭 Think: speed and defense are at 0.01 — completely unrelated. Why might the game designers have wanted that?
Part 6 · Where a principal component comes from
No code in this Part. Read it, then look back at your 3-D plot.
With two stats
Picture a scatterplot of attack against defense (r = 0.47). Because they are correlated, the cloud of points is stretched along a diagonal, like a rugby ball.
- PC1 is the line running along the longest stretch of the cloud. For these two stats it holds 73% of the spread.
- PC2 is at right angles to PC1 and holds what is left (27%).
- The stronger the correlation, the longer and thinner the cloud, and the more PC1 holds.
With six stats
Exactly the same, just in six dimensions we cannot picture:
- PC1 = the direction through the 6-D cloud with the most spread
- PC2 = the most spread left over, at right angles to PC1
- PC3 = the next leftover, and so on — six columns in, six PCs out, in order of usefulness
Each PC is a blend of the old columns:
\[\text{PC1} = a_1\,\text{hp} + a_2\,\text{attack} + a_3\,\text{defense} + \ldots\]
The shadow analogy 🔦
Hold your hand in front of a lamp. Your hand is 3-D, the shadow is 2-D — but you can still tell it is a hand. Rotate your hand and some angles give a shadow you recognise instantly; others give a blob. PCA finds the angle that casts the most informative shadow of the cloud — the one you were hunting for in Part 3.
Loading — how much an original stat contributes to a PC (the \(a\)’s). What the axis is made of.
Score — where one Pokémon sits along that PC. Its new measurement.
Loadings describe the axis; scores describe the Pokémon.
💭 Think: PC2 is built from what PC1 left behind. Why does that mean PC2 can never hold more than PC1?
Part 7 · First you must scale
▶ Type this (section 7):
poke_stats %>%
summarise(across(everything(), ~ sd(.x)))That is the standard deviation of each stat — how spread out each column is in its own raw points. For Pokémon they are similar (about 27 to 30), because the game designers used one scale for everything. Real data almost never is.
PCA chases spread. Hand it unscaled columns and the column with the biggest numbers wins by default.
Measure animals in grams and kilometres. Body mass runs into the thousands; home range might be 0.4. Unscaled, PC1 would be entirely mass — and would tell you nothing except which unit you typed.
The fix is one argument, scale. = TRUE. It turns every column into standard deviations from its own mean, so every column has mean 0 and sd 1 and all six compete fairly.
The argument is scale. — with a full stop — because scale was already an R function. Leave the dot off and you get an error.
Part 8 · Run it
▶ Type this (section 8):
poke_pca <- prcomp(poke_stats, center = TRUE, scale. = TRUE)
summary(poke_pca)Nothing prints from the first line — that is correct; the result is stored in poke_pca. That one line is the entire analysis. Everything after it is reading it.
From summary(), ignore the first row and read these two:
| PC1 | PC2 | PC3 | |
|---|---|---|---|
Proportion of Variance |
44.1% | 18.4% | 14.7% |
Cumulative Proportion |
44.1% | 62.5% | 77.2% |
Two invented axes carry 62.5% of everything in six columns. One flat scatterplot of PC1 against PC2 shows nearly two-thirds of the whole dataset.
Variance just means how spread out things are. PC1 holding 44.1% means: throw away all six stats, keep only each Pokémon’s PC1 score, and you still have 44% of how they differ. One number instead of six. It is not 44% of the Pokémon, and not 44% accuracy.
💭 Think: The cumulative total for all six PCs is always exactly 100%. Why must that be true?
Part 9 · The scree plot
▶ The first block is already in your skeleton (section 9). Type the ggplot() under it:
var_df <- tibble(
PC = paste0("PC", 1:6),
percent = round(100 * poke_pca$sdev^2 / sum(poke_pca$sdev^2), 1)
)
var_dfggplot(var_df, aes(x = PC, y = percent)) +
geom_col() +
geom_text(aes(label = percent), vjust = -0.4)var_dfis the same percentagessummary()printed, but in a data frame — which is what lets ggplot draw them- A scree plot is variance explained per axis, in order. (“Scree” is the rubble at the foot of a cliff — the shape the bars make.)
- Look for the elbow, where the bars stop dropping steeply. Here PC1 towers over the rest, then PC2 onwards step down gently. Keep two — and know you are holding 62.5%
Rough guides: keep PCs until the cumulative total passes ~70–80%; keep the ones before the flat part; keep the ones you can interpret. That last one is the most useful.
💭 Think: If all six bars were the same height (16.7% each), what would that say about the six stats? Would PCA have helped?
Part 10 · What is PC1 made of?
▶ Type this (section 10):
round(poke_pca$rotation[, 1:2], 2)The loadings — one row per stat, one column per PC.
- Every number in the PC1 column is positive (0.31 to 0.44). A Pokémon scores high on PC1 by being high on all six stats at once. PC1 is an “overall power” axis.
- PC2 has minus signs:
defense+0.58,speed−0.70. A big plus and a big minus on one axis means a trade-off, not a total. That is next class.
Part 11 · Glue the scores back on, and look at the ends
▶ Type this (section 11):
poke_scores <- pokemon %>%
mutate(PC1 = poke_pca$x[, 1],
PC2 = poke_pca$x[, 2])
poke_scores %>%
arrange(desc(PC1)) %>%
select(name, status, PC1) %>%
head(6)
poke_scores %>%
arrange(PC1) %>%
select(name, status, PC1) %>%
head(6)poke_pca$xholds the scores — one row per Pokémon, in the same order as the data, somutate()glues them straight on- Scores are in standard deviations: 0 is average. A negative score is not “bad”, just below average
This is the whole validation 🎣
| End of PC1 | Who is there |
|---|---|
| Top | Arceus, Ho-Oh, Giratina, Lunala, Eternatus, Reshiram — every one legendary or mythical |
| Bottom | Wishiwashi, Blipbug, Sunkern, Magikarp, Snom, Weedle |
Nobody told PCA which Pokémon were strong. There is no “power” column in the file. It was handed six columns of numbers and sorted them by overall strength on its own.
You cannot test whether an axis is “real” — there is no p-value for that. But you can look at what sits at each end and ask whether it lines up with something you already know. If it does not, be very careful what you claim.
Part 12 · Put a number on it
▶ Type this (section 12):
poke_scores %>%
group_by(status) %>%
summarise(n = n(),
mean_PC1 = mean(PC1))| status | n | mean PC1 |
|---|---|---|
| legendary | 71 | 2.38 |
| mythical | 23 | 2.25 |
| regular | 931 | −0.24 |
The rare ones sit about 2.5 standard deviations above the crowd — on an axis that was built without ever being told they existed.
Part 13 · The picture — hover to find them
▶ Type this (section 13):
pca_plot <- ggplot(poke_scores,
aes(x = PC1, y = PC2, color = status, text = name)) +
geom_point(alpha = 0.6)
ggplotly(pca_plot, tooltip = "text")- Every dot is one Pokémon on the two invented axes. Left ↔︎ right is weak ↔︎ strong (PC1, 44.1%). Up ↔︎ down is something else (PC2, 18.4%)
text = nameis not a real ggplot aesthetic — ggplot ignores it,ggplotly()picks it up, andtooltip = "text"shows only the name- ggplot may warn about
text— that warning is expected - Two dots close together = two Pokémon with similar stats overall — the all-six-at-once question we could not answer in Part 3
💭 Think: Hover to find Magikarp, Mewtwo and Pikachu. Then find the dot way up at the top, on its own. Look up its stats in pokemon — what is weird about it? (That is a clue to PC2.)
Where we got to, and what is missing
We have: two axes holding 62.5% of six columns; PC1 = “overall power”, checked against Magikarp and the legendaries; a picture you can hover over.
We do not have: any idea what PC2 means, or a way to see the six original stats on the picture. Both are next class.
Homework — does Gen 1 tell the same story?
This is what you turn in: scripts/27_pca_homework.R
The original game had 151 Pokémon (Generation I). Today you used all 1,025 from nine generations. The homework asks: if you only had the first 151, would PCA have found the same axes?
- The questions are at the top, with answer boxes. Answer in
#comments. - Below them, the code runs top to bottom in numbered sections.
- Helper code is written for you where something is new — the main one is a single
filter()that keeps only Generation I. - Where it says
YOUR CODE, copy the matching section from today’sscripts/27_pca.R. It is the same code; only the data changed.
Session > Restart R, then run the whole file top to bottom. It must run clean, and your scree plot and hover plot must draw.
Built from PokéAPI (pokeapi.co), a free, open API with no account needed. You are handed the finished CSV; the download script is kept with the course materials.