Skip to main content

Lecture 27 — PCA I: Many Measurements, Few Axes

Six numbers per Pokémon, where the new axes come from, and what ‘variance explained’ means

pca
multivariate
prcomp
ggplot
plotly
pokemon

A first, gentle pass at principal component analysis on all 1,025 Pokemon, assuming no statistics background at all. Three stats in an interactive 3-D plot (and why six cannot be drawn), the correlation table, why correlated columns are not dropped, where PC1 comes from using two stats, the shadow analogy, scaling, running prcomp(), variance explained, the scree plot, checking PC1 against who sits at each end, and a hover-to-name plot of the new axes.

Author

Bill Perry

Published

November 30, 2026

Something Completely Different

  • Everything this term had one response variable
    • t-test: one measurement, two groups
    • regression: one measurement against one other
    • ANOVA: one measurement across several groups
  • Today: six measurements at once, and no groups to compare
    • not “is A different from B?”
    • but “what is the shape of this whole dataset?” 🔴

Today Has No p-Values

  • PCA is not a test
    • no null hypothesis
    • no p-value
    • no assumptions to check
    • nothing passes or fails
  • It is a way of looking at data that has too many columns to plot
  • The question is never “is it significant?”
    • it is always “does this make sense?”
Important

⚠️ Set down one habit

For nine weeks, “did it work?” meant “is p small?”

Today you judge your result by whether you can explain what the axes mean.

Goals for Today

  • See the data in 3-D — and why six columns cannot be drawn
  • Notice that the columns are correlated
  • See where a principal component comes from
  • Know why you must scale first
  • Run it: prcomp()
  • Read variance explained, draw a scree plot
  • Check PC1 against Pokémon you already know
  • Hover over the new picture to find them

Tools today:

  • tidyverse
  • plotly — you installed it for the mapping weeks

Data: 🔴 all 1,025 Pokémon, six battle stats each

Tip

No new packages. prcomp() is built into R.

Why Pokémon

  • Because you can check the answer
    • PCA hands back new axes that it invented
    • you have to decide whether they mean anything
    • that is nearly impossible on data you do not know
  • If an axis puts Magikarp at one end and Mewtwo at the other, you know exactly what it found
  • 1,025 is plenty of data — and hovering tells you who any dot is
  • Same method as gene expression, soil chemistry, skull measurements
Note

📖 The six stats

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

🧩 Chunk 1 of 4 · Look at the Data First

We will cover:

  • reading the data and marking the legendaries
  • three stats in 3-D — and why six is impossible

Read It In

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)
# A tibble: 3 × 2
  status        n
  <chr>     <int>
1 legendary    71
2 mythical     23
3 regular     931
  • 1,025 rows — one per Pokémon
  • status is one column built from two TRUE/FALSE ones
    • first matching line wins
    • TRUE ~ catches everything left over
  • We will colour by status — PCA never sees it
Note

🧠 Mythical?

A second “rare and special” group in the game — Mew is mythical, Mewtwo is legendary.

Three Stats, in 3-D

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

What That Plot Shows

  • Drag to rotate it — every dot is one Pokémon
    • from some angles: a shapeless blob
    • from others: a long, spread-out cloud
    • same data, different amount you can see
  • Hover — the name pops up
    • red / orange (legendary, mythical) sit out at the big end
  • But this is only 3 of the 6 stats
    • hp, sp_attack, sp_defense are missing
Important

✅ Hold on to this

Rotating to find the angle that shows the most spread is exactly what PCA does.

It just does it in six dimensions, where we cannot rotate anything by hand.

Six Columns Is Too Many to Plot

  • One measurement → a histogram
  • Two → a scatterplot
  • Three → the 3-D plot you just spun
  • Six → nothing
    • there is no six-dimensional plot, and never will be
  • All the pairs instead? 15 scatterplots
    • nobody can hold 15 plots in their head
Warning

⚠️ The real problem

“Which Pokémon are similar to each other?” is a question about all six numbers at the same time.

Looking at them two at a time cannot answer it.

Make Them a Table of Their Own

poke_stats <- pokemon %>%
  select(hp, attack, defense, sp_attack, sp_defense, speed)

dim(poke_stats)
[1] 1025    6
Note

🧠 Why a separate table

  • PCA needs numbers only — no names, no types, no status
  • The rows stay in the same order as pokemon
    • that is what lets us glue the results back on later
    • never sort one and not the other

🧩 Chunk 2 of 4 · Where the New Axes Come From

We will cover:

  • the correlation table — the raw material
  • why you do not drop correlated columns
  • PC1 drawn with just two stats, then the shadow analogy

Do the Stats Move Together?

poke_stats %>%
  cor() %>%
  round(2)
             hp attack defense sp_attack sp_defense speed
hp         1.00   0.48    0.30      0.36       0.37  0.18
attack     0.48   1.00    0.47      0.28       0.23  0.35
defense    0.30   0.47    1.00      0.21       0.50  0.01
sp_attack  0.36   0.28    0.21      1.00       0.49  0.42
sp_defense 0.37   0.23    0.50      0.49       1.00  0.21
speed      0.18   0.35    0.01      0.42       0.21  1.00

Reading That Matrix

  • The diagonal is all 1.00 — each column against itself. Ignore it
  • The strongest pairs:
    • defense & sp_defense: 0.50
    • sp_attack & sp_defense: 0.49
    • hp & attack: 0.48
    • attack & defense: 0.47
  • And one that is nothing at all:
    • speed & defense: 0.01
  • So six columns are not six independent facts
    • they overlap — knowing one tells you something about another
Important

✅ This is what makes PCA work

Correlation is redundancy.

PCA’s whole job is to squeeze the redundancy out.

If all six were completely unrelated, there would be nothing to squeeze — six axes in, six equally useless axes out.

“Shouldn’t I Drop the Correlated Ones?”

  • No. That rule is from regression
    • there, two correlated predictors fight over one slope
  • In PCA, correlation is the fuel, not a problem
    • correlated stats simply land on the same axis
    • that is the redundancy being squeezed out
  • PCA is built from this correlation table
    • with scale. = TRUE, that table is literally the input
Warning

⚠️ The one real caution

Do not put in the same thing twice.

A “total stats” column next to the six stats it was added up from would count everything twice.

Here the biggest correlation is 0.50 — nowhere near a duplicate.

Where PC1 Comes From — With Two Stats

  • attack vs defense, r = 0.47
    • the cloud is stretched along a diagonal
  • PC1 (red) = the line along the longest stretch
    • it holds 73% of the spread in these two stats
  • PC2 (blue) = right angles to PC1
    • it holds the leftover 27%
  • Strong correlation → long, thin cloud → PC1 holds a lot

The Same Idea, in Six Dimensions

  • Your data is a cloud of 1,025 points in 6-D space
  • PC1 = the direction through that cloud with the most spread
  • PC2 = the most spread that is left, 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} + \ldots\]

Note

🧠 Two words you need

Loading — how much an original stat contributes to a PC. What the axis is made of — the \(a\)’s.

Score — where one Pokémon sits along that PC. Its new measurement.

Loadings describe the axis. Scores describe the Pokémon.

The Shadow Analogy 🔦

  • Hold your hand in front of a lamp
    • your hand is 3-D, the shadow is 2-D
    • you lost a dimension — but it still looks like a hand
  • Rotate your hand
    • some angles: you recognise it instantly
    • others: a shapeless blob
  • Same hand. Same wall. Different amount kept
  • That is the 3-D plot you spun — now in six dimensions
Tip

🎯 That is PCA

PCA finds the angle that casts the most informative shadow of the 6-D cloud — the one where the points stay as spread out as possible.

Then it reports what that shadow is made of.

First: You Must Scale

poke_stats %>%
  summarise(across(everything(),
                   ~ sd(.x)))
# A tibble: 1 × 6
     hp attack defense sp_attack sp_defense speed
  <dbl>  <dbl>   <dbl>     <dbl>      <dbl> <dbl>
1  26.6   29.8    29.3      29.7       26.6  28.7
  • PCA chases spread
    • unscaled, the column with the biggest numbers wins by default
  • Pokémon stats happen to be on similar scales (sd 27–30)
    • real data almost never is
Warning

⚠️ A worked disaster

Measure animals in grams and kilometres.

  • body mass in grams: thousands
  • home range in km: maybe 0.4

Unscaled, PC1 would be entirely mass — it would only tell you which unit you typed.

Scaling, In One Argument

  • scale. = TRUE turns every column into standard deviations from its own mean
  • After scaling, every column has
    • mean 0
    • standard deviation 1
  • All six compete fairly, and the units cancel out
Important

⚠️ Mind the full stop

The argument is scale. — with a dot:

prcomp(poke_stats, scale. = TRUE)

scale was already an R function. Leave the dot off and you get an error.

Almost always use scale. = TRUE.

🧩 Chunk 3 of 4 · Run It and Read It

We will cover: prcomp(), summary(), variance explained, and the scree plot.

One Line

poke_pca <- prcomp(poke_stats, center = TRUE, scale. = TRUE)
Note

🧠 That is the entire analysis

  • center = TRUE — subtract each column’s mean
  • scale. = TRUE — divide by each column’s standard deviation
  • Nothing prints — the result is stored in poke_pca
  • Everything from here on is reading the result — the part that takes judgement

What Came Back

summary(poke_pca)
Importance of components:
                          PC1    PC2    PC3    PC4     PC5
Standard deviation     1.6265 1.0509 0.9391 0.8192 0.65141
Proportion of Variance 0.4409 0.1841 0.1470 0.1119 0.07072
Cumulative Proportion  0.4409 0.6250 0.7719 0.8838 0.95451
                           PC6
Standard deviation     0.52243
Proportion of Variance 0.04549
Cumulative Proportion  1.00000

Reading summary()

  • Ignore the first row (Standard deviation)
  • Proportion of Variance — share of the total spread each PC holds
    • PC1: 44.1%
    • PC2: 18.4%
    • PC3: 14.7%
  • Cumulative Proportion — the running total
    • PC1 alone: 44.1%
    • PC1 + PC2: 62.5%
    • all six: 100%, always
Important

✅ The headline

Two invented axes carry 62.5% of everything in six columns.

So one flat scatterplot of PC1 against PC2 shows you nearly two-thirds of the whole dataset.

“Variance Explained”, In Plain Words

  • Variance = how spread out things are
  • Total variance = every way these 1,025 Pokémon differ, across all six stats
  • PC1 holds 44.1% of that
    • throw away all six stats
    • keep only each Pokémon’s PC1 score
    • you still have 44% of how they differ
  • One number instead of six, for 44% of the picture
Warning

⚠️ Not 44% of the Pokémon

And not 44% accuracy.

It is 44% of the total variation — of the differences between them.

How Much Variance Per Axis

var_df <- tibble(
  PC      = paste0("PC", 1:6),
  percent = round(100 * poke_pca$sdev^2 / sum(poke_pca$sdev^2), 1)
)

var_df
# A tibble: 6 × 2
  PC    percent
  <chr>   <dbl>
1 PC1      44.1
2 PC2      18.4
3 PC3      14.7
4 PC4      11.2
5 PC5       7.1
6 PC6       4.5
Note

🧠 Where that came from

  • poke_pca$sdev = each PC’s standard deviation
  • square it → variance; ÷ total → a share; × 100 → a percent
  • Same numbers summary() printed — but in a data frame, so we can plot them

The Scree Plot

ggplot(var_df, aes(x = PC, y = percent)) +
  geom_col() +
  geom_text(aes(label = percent), vjust = -0.4)

Reading a Scree Plot

  • Scree = 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 stands way above the rest
    • PC2 onwards step down gently
  • Keep two: the big one, plus the one we will learn to name
    • and know you are holding 62.5%
Warning

⚠️ There is no rule

People argue about the elbow constantly. 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.

🧩 Chunk 4 of 4 · Does PC1 Mean Anything?

We will cover:

  • what PC1 is made of
  • who sits at each end of it
  • the picture, with names on hover

What PC1 Is Made Of

round(poke_pca$rotation[, 1:2], 2)
            PC1   PC2
hp         0.42  0.10
attack     0.43  0.07
defense    0.39  0.58
sp_attack  0.43 -0.36
sp_defense 0.44  0.16
speed      0.31 -0.70
Important

✅ Look at the PC1 column: every number 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 — it is doing something different. Next class

Where Does Each Pokémon Sit?

poke_scores <- pokemon %>%
  mutate(PC1 = poke_pca$x[, 1],
         PC2 = poke_pca$x[, 2])

poke_scores %>%
  select(name, hp, attack, speed, PC1, PC2) %>%
  head(3)
# A tibble: 3 × 6
  name         hp attack speed    PC1     PC2
  <chr>     <dbl>  <dbl> <dbl>  <dbl>   <dbl>
1 bulbasaur    45     49    45 -1.53  -0.0589
2 ivysaur      60     62    60 -0.286 -0.152 
3 venusaur     80     82    80  1.43  -0.244 
Note

🧠 poke_pca$x holds the scores

  • one row per Pokémon, one column per PC, same row order as the data
  • that is why mutate() can glue them straight on
  • scores are in standard deviations: 0 = average, negative = below average

The Top of PC1

poke_scores %>%
  arrange(desc(PC1)) %>%
  select(name, status, PC1) %>%
  head(6)
# A tibble: 6 × 3
  name             status      PC1
  <chr>            <chr>     <dbl>
1 arceus           mythical   4.17
2 ho-oh            legendary  3.79
3 giratina-altered legendary  3.74
4 lunala           legendary  3.71
5 eternatus        legendary  3.70
6 reshiram         legendary  3.70

The Bottom of PC1

poke_scores %>%
  arrange(PC1) %>%
  select(name, status, PC1) %>%
  head(6)
# A tibble: 6 × 3
  name            status    PC1
  <chr>           <chr>   <dbl>
1 wishiwashi-solo regular -3.64
2 blipbug         regular -3.57
3 sunkern         regular -3.55
4 magikarp        regular -3.52
5 snom            regular -3.45
6 weedle          regular -3.42

That Is the Validation 🎣

  • Top of PC1: Arceus, Ho-Oh, Giratina, Lunala, Eternatus, Reshiram
    • every one a legendary or mythical
  • Bottom of PC1: Wishiwashi, Blipbug, Sunkern, Magikarp, Snom, Weedle
    • the famously useless ones
  • Nobody told PCA which Pokémon were strong
    • there is no “power” column in the file
    • it sorted them by overall strength on its own
Important

✅ Why this matters beyond Pokémon

This is the check you run on every PCA.

You cannot test whether an axis is “real”. 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.

Put a Number on It

poke_scores %>%
  group_by(status) %>%
  summarise(n = n(),
            mean_PC1 = round(mean(PC1), 2))
# A tibble: 3 × 3
  status        n mean_PC1
  <chr>     <int>    <dbl>
1 legendary    71     2.38
2 mythical     23     2.25
3 regular     931    -0.24
Note

🧠 Reading it

  • 71 legendaries average PC1 = 2.38; 23 mythicals 2.25; the other 931 −0.24
  • Scores are in standard deviations → the rare ones sit about 2.5 sd above the crowd
  • On an axis built without ever being told they existed

The Picture — Hover Over It

pca_plot <- ggplot(poke_scores,
                   aes(x = PC1, y = PC2, color = status, text = name)) +
  geom_point(alpha = 0.6)

ggplotly(pca_plot, tooltip = "text")

Reading That Picture

  • Every dot is one Pokémon, on two invented axes
    • left ↔︎ right = weak ↔︎ strong (PC1, 44.1%)
    • up ↔︎ down = something else (PC2, 18.4%)
  • Legendaries and mythicals pile up on the right
  • Hover to check:
    • Magikarp on the far left
    • Mewtwo on the far right
    • who is that one way up at the top?
  • text = name is not a real ggplot aesthetic — ggplotly() picks it up for the hover
Tip

🎯 Close dots = similar Pokémon

Two dots near each other have similar stat profiles overall — the all-six-at-once question we could not answer with 15 scatterplots.

And this one plot holds 62.5% of the six columns.

What We Have, 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
  • a way to see the six original stats on the picture

Both are next class.

Tip

🎯 A hint about PC2

In PC2, defense is +0.58 and speed is −0.70.

A big positive and a big negative on the same axis means a trade-off, not a total.

Which trade-off? Next class.

Your Homework

  • Same analysis, on only the original 151 (Generation I)
  • One line is new — a filter() right after you read the file
  • The question: does Gen 1 alone tell the same story?
    • does PC1 still mean overall power?
    • how much does it hold — more or less than 44%?
    • what changes when there are only 4 legendaries?
Note

📂 How it works

  • The questions are at the top of the homework file
  • Helper code is written along the way
  • Where it says YOUR CODE, copy the matching section from today’s script

Recap

  • PCA is not a test — no p-value, nothing to reject
  • Six columns cannot be plotted; three in 3-D already need rotating
  • PCA works because the columns are correlated — do not drop them
  • PC1 = the direction of most spread; PC2 = most of what is left, at right angles
  • Think shadows: the most informative angle on a cloud you cannot see
  • Always scale. = TRUE
  • PC1 = 44.1%, PC2 = 18.4%, together 62.5%
  • The scree plot shows where to stop — judgement, not a rule
  • Validate by looking at the ends — Magikarp at one end, the legendaries at the other ✅
Note

✅ Next

Open the activity and type it in. Next class: what PC2 means, and the biplot. 🔴