# load packages
require(FactoMineR)
require(ggplot2)
# load data tea
data(tea)
# select these columns
newtea = tea[, c("Tea", "How", "how", "sugar", "where", "always")]
# take a look
head(newtea)
# number of categories per variable
cats = apply(newtea, 2, function(x) nlevels(as.factor(x)))
cats
# apply MCA
mca1 = MCA(newtea, graph = FALSE)
# table of eigenvalues
mca1$eig
# data frames for ggplot
mca1_vars_df = data.frame(mca1$var$coord, Variable = rep(names(cats),
cats))
mca1_obs_df = data.frame(mca1$ind$coord)
# plot of variable categories
ggplot(data = mca1_vars_df,
aes(x = Dim.1, y = Dim.2, label = rownames(mca1_vars_df))) +
geom_hline(yintercept = 0, colour = "gray70") + geom_vline(xintercept = 0,
colour = "gray70") +
geom_text(aes(colour = Variable)) +
ggtitle("MCA plot of variables using R package FactoMineR")
# XXX ---------------------------------------------------------------------
Base_acm <- Base %>% select(P1_1, P3_1, P3_2, P3_3)
Base_acm$P1_1 <- as.factor(Base_acm$P1_1)
Base_acm$P3_1 <- as.factor(Base_acm$P3_1)
Base_acm$P3_2 <- as.factor(Base_acm$P3_2)
Base_acm$P3_3 <- as.factor(Base_acm$P3_3)
cats=apply(Base_acm, 2, function(x) nlevels(as.factor(x)))
mca2 = MCA(Base_acm, graph = FALSE)
# data frames for ggplot
mca2_vars_df = data.frame(mca2$var$coord, Variable = rep(names(cats),
cats))
mca2_obs_df = data.frame(mca2$ind$coord)
# plot of variable categories
ggplot(data = mca2_vars_df,
aes(x = Dim.1, y = Dim.2, label = rownames(mca2_vars_df))) +
geom_hline(yintercept = 0, colour = "gray70") + geom_vline(xintercept = 0,
colour = "gray70") +
geom_text(aes(colour = Variable)) +
ggtitle("MCA plot of variables using R package FactoMineR")
factoextra::fviz_screeplot(mca2, addlabels = TRUE, ylim = c(0, 45))
Comments
@JasonWestAussie - Tue Feb 22 2022 09:06:56 GMT+0000 (UTC)Thank you Boreal, took me a long while to work out how to get "BMI (kg/m^2)" to print as the x-axis label with a superscript numeral 2. I thought I was only allowed to have m^2 outside quotation marks, hence I had the following code: df <- data.frame( LifeExp = c(60, 70, 80), BMI = c(27, 25, 28) ) ggplot(df, aes(BMI, LifeExp)) + geom_col() + xlab(bquote("BMI (kg/"~m^2~")" )) Unfortunately, that code generates a non-breaking space where the tildes are located. To get around this, I finally found out, by trial and error, that I can rewrite the xlab function as follows: xlab(bquote("BMI"~(kg/m^{2}) )) Hope this helps other readers. Cheers, Jason Boyanup, Western Australia
This is my first time using this website, so I sure hope there is a better way to leave a comment, with formatted breaks, tabs, etc.!!