Activity 3.4 - Multiple Correspondence Analysis KEY

Problem 1

Consider the following table summarizing students:

Variable Category Count
Part-time job Yes 110
No 90
Major Science 80
Arts 60
Business 50
Education 10
Commute Car 100
Bus 50
Bike 36
Walk 14
Housing On campus 70
Off campus 90
With family 40

A)

What is the total inertia in this table?

(13-4)/4=2.25

B)

How many dimensions are needed to explain 100% of the inertia?

13-4=9

C)

The code below creates a microdata version of this table, one row per student:

library(tidyverse)
set.seed(1)
students <- data.frame(
  Part_time_job = sample(rep(c("Yes", "No"), c(110, 90))),
  Major         = sample(rep(c("Science", "Arts", "Business", "Education"),
                             c(80, 60, 50, 10))),
  Commute       = sample(rep(c("Car", "Bus", "Bike", "Walk"),
                             c(100, 50, 36, 14))),
  Housing       = sample(rep(c("On campus", "Off campus", "With family"),
                             c(70, 90, 40)))
)

head(students)
  Part_time_job    Major Commute     Housing
1           Yes Business     Car With family
2            No     Arts    Bike  Off campus
3            No     Arts     Car  Off campus
4            No  Science     Car   On campus
5           Yes     Arts    Bike  Off campus
6           Yes  Science     Car With family

Perform MCA on this data set, setting ncp= to the number of dimensions you specified in part B. Verify that the sum of the eigenvalues equal your answer to part A.

library(FactoMineR)

students <- students %>% mutate(across(everything(), as.factor))

student_mca <- MCA(students, ncp = 9, graph = FALSE)

student_mca$eig %>% round(4)
      eigenvalue percentage of variance cumulative percentage of variance
dim 1     0.3292                14.6320                           14.6320
dim 2     0.3089                13.7288                           28.3608
dim 3     0.2884                12.8197                           41.1805
dim 4     0.2628                11.6819                           52.8624
dim 5     0.2512                11.1647                           64.0270
dim 6     0.2259                10.0412                           74.0683
dim 7     0.2073                 9.2155                           83.2838
dim 8     0.2004                 8.9080                           92.1918
dim 9     0.1757                 7.8082                          100.0000
sum(student_mca$eig[, 1])
[1] 2.25

Problem 2

In this problem, we consider the hobbies data set which comes preloaded with the FactoMineR package. The data used here concern a questionnaire on hobbies. 8403 individuals were asked questions about their hobbies, as well as demographic information. Use the following subset of the data, called hobbies_use:

library(FactoMineR)
library(tidyverse)
library(factoextra)
Welcome to factoextra!
Want to learn more? See two factoextra-related books at https://www.datanovia.com/library/principal-component-methods
library(patchwork)
library(ggrepel)
data(hobbies)
hobbies_use <- hobbies %>% select(Reading:Fishing, Sex:`Marital status`)
head(hobbies_use)
         Reading Listening music Cinema Show Exhibition Computer Sport Walking
11000210       1               1      1    1          1        0     1       1
11000410       1               0      0    0          1        0     1       1
11000610       1               1      0    0          1        0     0       0
11000710       1               0      0    0          1        0     1       0
11000810       1               1      1    1          0        0     0       1
11000910       0               0      0    0          0        0     0       0
         Travelling Playing music Collecting Volunteering Mechanic Gardening
11000210          1             0          0            1        1         0
11000410          0             0          1            1        1         1
11000610          1             0          0            0        0         0
11000710          1             0          0            0        0         0
11000810          0             0          0            0        0         0
11000910          0             0          0            0        1         0
         Knitting Cooking Fishing Sex     Age Marital status
11000210        0       0       0   F (55,65]        Married
11000410        0       0       0   M (45,55]        Married
11000610        0       0       0   F (25,35]      Remarried
11000710        0       0       0   M (75,85]        Married
11000810        0       0       0   M (55,65]        Married
11000910        0       0       0   M (45,55]        Married

A)

What percent of the inertia is explained by the first two dimensions?

hobbies_mca <- MCA(hobbies_use, 
                   quali.sup = c('Sex', 'Age', 'Marital status'), 
                   graph = FALSE)

hobbies_mca$eig[1:5, ] %>% round(3)
      eigenvalue percentage of variance cumulative percentage of variance
dim 1      0.207                 20.712                            20.712
dim 2      0.085                  8.477                            29.189
dim 3      0.075                  7.528                            36.717
dim 4      0.061                  6.146                            42.863
dim 5      0.060                  6.000                            48.862
# % of inertia explained by the first two dimensions
hobbies_mca$eig[2, 3]
[1] 29.18874
#| fig-alt: "Scree plot for hobbies MCA"
fviz_screeplot(hobbies_mca, geom = 'line') +
  theme_classic(base_size = 16)

B)

Perform MCA on this data set. For each of the first two dimensions of the MCA, find the top-10 variables contributing to these dimensions. Discuss your findings.

# MCA: hobbies active, demographics supplementary
hobbies_mca <- MCA(hobbies_use, 
                   quali.sup = c('Sex', 'Age', 'Marital status'), 
                   graph = FALSE)

# Eigenvalues (first 5 dimensions)
hobbies_mca$eig[1:5, ] %>% round(3)
      eigenvalue percentage of variance cumulative percentage of variance
dim 1      0.207                 20.712                            20.712
dim 2      0.085                  8.477                            29.189
dim 3      0.075                  7.528                            36.717
dim 4      0.061                  6.146                            42.863
dim 5      0.060                  6.000                            48.862
# Top 10 contribution plots
m1 <- fviz_contrib(hobbies_mca, choice = 'var', axes = 1, top = 10) +
  scale_x_discrete(limits = rev) + 
  coord_flip() +
  labs(x = '', title = 'Dimension 1') +
  theme_classic(base_size = 13)

m2 <- fviz_contrib(hobbies_mca, choice = 'var', axes = 2, top = 10) +
  scale_x_discrete(limits = rev) + 
  coord_flip() +
  labs(x = '', title = 'Dimension 2') +
  theme_classic(base_size = 13)

m1 + m2 + plot_annotation(title = 'Top 10 category contributions')

# Top 10 contributions with coordinates (sign = side of axis)
contrib_table <- function(dim) {
  data.frame(
    Category = rownames(hobbies_mca$var$contrib),
    ctr      = hobbies_mca$var$contrib[, dim],
    coord    = hobbies_mca$var$coord[, dim]
  ) %>% 
    arrange(desc(ctr)) %>% 
    head(10) %>% 
    mutate(across(where(is.numeric), \(x) round(x, 3)))
}

contrib_table(1)
                           Category   ctr  coord
Exhibition_1           Exhibition_1 7.880  0.948
Show_1                       Show_1 7.846  0.978
Cinema_1                   Cinema_1 6.664  0.766
Travelling_1           Travelling_1 6.057  0.730
Computer_1               Computer_1 5.773  0.735
Listening music_0 Listening music_0 5.516 -0.815
Sport_1                     Sport_1 5.212  0.706
Playing music_1     Playing music_1 5.029  1.010
Reading_0                 Reading_0 4.538 -0.698
Cinema_0                   Cinema_0 4.438 -0.510
contrib_table(2)
               Category    ctr  coord
Gardening_1 Gardening_1 19.799  0.845
Gardening_0 Gardening_0 13.166 -0.562
Knitting_1   Knitting_1  9.345  0.895
Mechanic_1   Mechanic_1  5.924  0.450
Fishing_1     Fishing_1  5.207  0.817
Cinema_1       Cinema_1  5.127 -0.430
Cooking_1     Cooking_1  5.052  0.407
Mechanic_0   Mechanic_0  4.310 -0.328
Cooking_0     Cooking_0  3.947 -0.318
Walking_1     Walking_1  3.893  0.336

Dimension 1 measures overall hobby activity. Doing active hobbies (Exhibition, Show, Cinema, Travelling, Computer, Sport, and Playing music, all positive), against not listening to music, reading, or going to the cinema, so it separates active people from inactive ones. Dimension 2 contrasts do at home hobbies with going out. It is a lot of Gardening, followed by Knitting, Mechanics, Fishing, Cooking, and Walking on the positive side, with Cinema on the negative side. It separates people with outdoor hobbies from people whose hobby is going to the movies.

C)

Use fviz_mca_var() with repel=TRUE to plot the coordinates of the active variables and supplementary variables. Discuss the shortcomings of this plot.

fviz_mca_var(hobbies_mca, 
             repel = TRUE,
             col.var = '#009ADE',          # active categories
             col.quali.sup = '#E16A86') +  # supplementary categories
  theme_classic(base_size = 13)

The plot shows only position, not importance, so rare categories like ages 85-100 look influential despite contributing nothing to the axes, and it captures only 29% of the total inertia.

D)

Note that the plot from C has too many labels and isn’t doing a good job repelling them even with repel = TRUE. Let’s use ggplot layers to improve this plot; unfortunately this will require some data wrangling to create the data set we need “from scratch.”

Use the MCA() output to create active_df and supp_df, containing the coordinates of the active and supplementary variables, respectively. Keep only the “top 10” levels of the active variables, as measured by the sum-of-squared coordinates. The first 6 rows of each data frame are shown:

head(active_df)
               level       Dim.1       Dim.2 sum_sq_coord        category
1    Playing music_1  1.00952955 -0.12540594    1.0348766 active_variable
2             Show_1  0.97841609 -0.25138634    1.0204931 active_variable
3       Exhibition_1  0.94785218  0.03055321    0.8993572 active_variable
4         Knitting_1  0.23757658  0.89493428    0.8573500 active_variable
5        Gardening_1  0.26247657  0.84523534    0.7833167 active_variable
head(supp_df)
   level       Dim.1       Dim.2 sum_sq_coord category
1       M -0.02387308 -0.04419050  0.002522725      Sex
2       F  0.01958565  0.03625421  0.001697965      Sex
3 [15,25]  0.37173828 -0.87241775  0.899302081      Age
4 (25,35]  0.26667450 -0.32338199  0.175691199      Age
5 (35,45]  0.20477079 -0.01052354  0.042041822      Age
6 (45,55]  0.01785855  0.22042748  0.048907200      Age

Then row-bind these together:

final_plot_df <- bind_rows(active_df, supp_df)

Use final_plot_df to reproduce this plot:

# Active variables: top 10 levels by sum of squared coordinates
active_df <- hobbies_mca$var$coord[, 1:2] %>% 
  data.frame() %>% 
  rownames_to_column('level') %>% 
  mutate(sum_sq_coord = Dim.1^2 + Dim.2^2,
         category = 'active_variable') %>% 
  arrange(desc(sum_sq_coord)) %>% 
  head(10)

# Lookup table: which supplementary variable each level belongs to
supp_vars <- c('Sex', 'Age', 'Marital status')
supp_lookup <- map_dfr(supp_vars, \(v) 
                       tibble(level = levels(factor(hobbies_use[[v]])), category = v))

# Supplementary variables: all levels
supp_df <- hobbies_mca$quali.sup$coord[, 1:2] %>% 
  data.frame() %>% 
  rownames_to_column('level') %>% 
  mutate(sum_sq_coord = Dim.1^2 + Dim.2^2) %>% 
  left_join(supp_lookup, by = 'level') %>% 
  filter(!is.na(category))

head(active_df)
            level     Dim.1       Dim.2 sum_sq_coord        category
1 Playing music_1 1.0095296 -0.12540594    1.0348766 active_variable
2          Show_1 0.9784161 -0.25138634    1.0204931 active_variable
3    Exhibition_1 0.9478522  0.03055321    0.8993572 active_variable
4      Knitting_1 0.2375766  0.89493428    0.8573500 active_variable
5     Gardening_1 0.2624766  0.84523534    0.7833167 active_variable
6        Cinema_1 0.7661541 -0.42991210    0.7718165 active_variable
head(supp_df)
    level       Dim.1       Dim.2 sum_sq_coord category
1       M -0.02387308 -0.04419050  0.002522725      Sex
2       F  0.01958565  0.03625421  0.001697965      Sex
3 [15,25]  0.37173828 -0.87241775  0.899302081      Age
4 (25,35]  0.26667450 -0.32338199  0.175691199      Age
5 (35,45]  0.20477079 -0.01052354  0.042041822      Age
6 (45,55]  0.01785855  0.22042748  0.048907200      Age
final_plot_df <- bind_rows(active_df, supp_df)

ggplot(final_plot_df, aes(x = Dim.1, y = Dim.2, color = category)) +
  geom_hline(yintercept = 0, linetype = 'dashed') +
  geom_vline(xintercept = 0, linetype = 'dashed') +
  geom_point(size = 2) +
  geom_text_repel(aes(label = level), size = 4, show.legend = FALSE) +
  scale_color_discrete(labels = c('Active variable', 'Age', 'Marital status', 'Sex'),
                       name = '') +
  labs(x = 'Dimension 1', y = 'Dimension 2') +
  theme_classic(base_size = 14)

E)

What does this plot suggest about the relationships between hobbies, age, marital status, and sex? Credit will be awarded proportional to thoroughness of response.

Age follows a clear path across the plot, young (15–25) and single people sit near the going out hobbies (Cinema, Computer, Show), middle-aged people (45–65), along with married and remarried people, sit near at home based hobbies (Knitting, Gardening, Fishing), and the oldest groups (75–100) and widowers sit near inactivity (Listening music_0). Marital status therefore largely mirrors age, since being single, married, or widowed tends to go with being young, middle-aged, or older. Sex sits almost exactly at the origin, which suggests men and women differ very little in their overall hobby patterns compared with the strong differences by age and life stage.

Problem 3

On the public television show The Joy of Painting Bob Ross taught people how to paint lovely scenic landscapes consisting of “snowcapped peaks” and “happy little clouds.” This dataset is a table consisting of different elements (e.g. mountain, river, waterfall, etc.) commonly found within in his paintings. Thus each painting can be thought of as survey respondent where they are asked a series of yes (1) or no (0) questions. This data set contains characteristics of paintings created in 316 of the 403 “Joy of Painting” episodes. Note that MCA requires everything to be factors (aka “categorical”) variables, hence the mutate() command below.

bobross <- read.csv('Data/BobRossCommon.csv') %>% 
  column_to_rownames('TITLE') %>% 
  mutate(across(everything(), as.factor))

Our goal is to understand what elements Ross tended to use together in paintings, and to find representative paintings with various characteristics.

A)

Perform MCA on the data set, and plot the first two dimensions of the variable coordinates. How would you characterize paintings in each of the four quadrants of this plot? Where are the “summer” and “winter” paintings?

bobross_mca <- MCA(bobross, graph = FALSE)

bobross_mca$eig[1:5, ] %>% round(3)
      eigenvalue percentage of variance cumulative percentage of variance
dim 1      0.124                 12.375                            12.375
dim 2      0.102                 10.215                            22.590
dim 3      0.077                  7.681                            30.271
dim 4      0.068                  6.812                            37.083
dim 5      0.065                  6.525                            43.608
fviz_mca_var(bobross_mca, 
             repel = TRUE,
             col.var = '#009ADE',
             labelsize = 3) +
  theme_classic(base_size = 13)

The upper-right quadrant holds cabin scenes (Cabin, Structure, Fence, Sun), and the upper-left holds summer meadow scenes (Flowers, Deciduous trees, Grass, River). The lower-left holds waterfall and rocky-stream scenes (Waterfall, Rocks, Bushes, Cumulus clouds), and the lower-right holds classic mountain-lake scenes (Snowy Mountain, Conifer, Lake, Cirrus clouds). The winter paintings (Winter, Snow) sit on the far right of Dimension 1 with the cabins and fences, while the summer paintings sit in the upper left, on the opposite side of Dimension 1.

B)

Plot the MCA scores, the coordinates of the individual paintings, filtering to paintings that are “most representative” of each quadrant using the cos2 values. From here, Google image search to find one painting that is representative of each quadrant. Include screenshots of these in your submission, along with discussion of how your selected paintings exemplify the quadrant.

# Individual painting coordinates + cos2 (quality of representation on Dims 1-2)
paintings <- data.frame(
  title = rownames(bobross_mca$ind$coord),
  Dim.1 = bobross_mca$ind$coord[, 1],
  Dim.2 = bobross_mca$ind$coord[, 2],
  cos2  = bobross_mca$ind$cos2[, 1] + bobross_mca$ind$cos2[, 2]
) %>% 
  mutate(quadrant = case_when(
    Dim.1 >= 0 & Dim.2 >= 0 ~ 'Upper right: cabin',
    Dim.1 <  0 & Dim.2 >= 0 ~ 'Upper left: summer meadow',
    Dim.1 <  0 & Dim.2 <  0 ~ 'Lower left: waterfall',
    Dim.1 >= 0 & Dim.2 <  0 ~ 'Lower right: mountain lake'
  ))

# Top 3 most representative paintings per quadrant
top_paintings <- paintings %>% 
  group_by(quadrant) %>% 
  slice_max(cos2, n = 3) %>% 
  ungroup()

top_paintings %>% 
  arrange(quadrant, desc(cos2)) %>% 
  mutate(across(where(is.numeric), \(x) round(x, 3)))
# A tibble: 12 × 5
   title                Dim.1  Dim.2  cos2 quadrant                  
   <chr>                <dbl>  <dbl> <dbl> <chr>                     
 1 FINAL_GRACE         -0.016 -0.709 0.717 Lower left: waterfall     
 2 DOUBLE_OVAL_FANTASY -0.016 -0.709 0.717 Lower left: waterfall     
 3 MOUNTAIN_WATERFALL1 -0.157 -0.719 0.532 Lower left: waterfall     
 4 ARCTIC_WINTER_DAY    0.886 -0.359 0.801 Lower right: mountain lake
 5 FROZEN_SOLITUDE      0.84  -0.434 0.751 Lower right: mountain lake
 6 PERFECT_WINTERS_DAY  0.816 -0.353 0.684 Lower right: mountain lake
 7 LAZY_RIVER          -0.328  0.373 0.566 Upper left: summer meadow 
 8 HIDDEN_CREEK        -0.328  0.373 0.566 Upper left: summer meadow 
 9 CYPRESS_CREEK       -0.328  0.373 0.566 Upper left: summer meadow 
10 WINTER_NIGHT         0.826  0.145 0.699 Upper right: cabin        
11 SNOWY_MORN           0.826  0.145 0.699 Upper right: cabin        
12 PURPLE_SPLENDOR      0.85   0.064 0.698 Upper right: cabin        
# Plot: all paintings in grey, most representative ones highlighted
ggplot(paintings, aes(x = Dim.1, y = Dim.2)) +
  geom_hline(yintercept = 0, linetype = 'dashed') +
  geom_vline(xintercept = 0, linetype = 'dashed') +
  geom_point(color = 'grey75', alpha = 0.6) +
  geom_point(data = top_paintings, aes(color = quadrant), size = 3) +
  geom_text_repel(data = top_paintings, aes(label = title, color = quadrant),
                  size = 3.5, show.legend = FALSE, max.overlaps = 20) +
  labs(x = paste0('Dimension 1 (', round(bobross_mca$eig[1, 2], 1), '%)'),
       y = paste0('Dimension 2 (', round(bobross_mca$eig[2, 2], 1), '%)'),
       color = '', title = 'Most representative paintings by quadrant (cos2)') +
  theme_classic(base_size = 13) +
  theme(legend.position = 'bottom')

Top Right:

Bottom Right:

Top Left:

Bottom Left: