R中的多重对应分析使用ggplot2绘制补充分类变量

时间:2015-06-02 09:09:25

标签: r ggplot2

我最近使用以下脚本来执行MCA分析并可视化绘图(我在http://gastonsanchez.com/blog/how-to/2012/10/13/MCA-in-R.html上找到了它)。

数据来自数据框架" Tea"包含在R包中" FactoMineR"。

# load data tea
data(tea)

# select these columns
newtea = tea[, c("Tea", "How", "how", "sugar", "where", "always")]

# number of categories per variable
cats = apply(newtea, 2, function(x) nlevels(as.factor(x)))

# apply MCA
mca1 = MCA(newtea, graph = FALSE)

# data frame with variable coordinates
mca1_vars_df = data.frame(mca1$var$coord, Variable = rep(names(cats), cats))

# data frame with observation coordinates
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")

运行完美,但我想知道如何在分析中引入定性补充变量。由于我根本不熟悉ggplot2,我在这里有点迷失。

例如,如果我想要" Tea"作为补充变量,我该如何修改脚本?

#apply MCA
mca1 = MCA(newtea, graph = FALSE,quali.sup=1)

但是如何在ggplot脚本中保留这些信息呢?

1 个答案:

答案 0 :(得分:0)

您需要获取MCA对象中补充变量的坐标。它们位于mca1$quali.sup$coord中,就像活动变量的坐标位于mca1$var$coord中一样。

mca1 = MCA(newtea, graph = FALSE,quali.sup=1)

mca1_vars_df = data.frame(rbind(mca1$var$coord,
                                mca1$quali.sup$coord), 
                          Variable = rep(names(cats), cats))