我对R中的主成分分析还是新手,我的提问可能有点简单。我已经使用R中的’prcomp’函数对矩阵A进行了PCA分析。现在我想将一个向量绘制到A的PC1和PC2的PCA空间中。我该如何进行这个向量的绘制呢?
回答:
使用biplot(红色箭头表示原始空间的维度):
a <- princomp(iris[1:4])biplot(a, cex=0.5)
你也可以自己进行投影到PCA空间,如下所示:
library(ggplot2)data <- iris[1:4]labels <- iris[,5]res <- princomp(data)res.proj <- as.matrix(data) %*% res$loadings[,1:2]ggplot(as.data.frame(res.proj), aes(Comp.1, Comp.2, col=labels)) + geom_point()
使用prcomp绘制相同的图(数值上更稳定):
data <- iris[1:4]labels <- iris[,5]res <- prcomp(data)res.proj <- as.matrix(data) %*% res$rotation[,1:2]ggplot(as.data.frame(res.proj), aes(PC1, PC2, col=labels)) + geom_point()
更高级的ggbiplot:
library(ggbiplot)g <- ggbiplot(res, obs.scale = 1, var.scale = 1, groups = labels, ellipse = TRUE, circle = TRUE)g <- g + scale_color_discrete(name = '')g <- g + theme(legend.direction = 'horizontal', legend.position = 'top')print(g)