如何在R中使用autoplot绘制旋转的组件?

时间:2018-04-30 17:53:58

标签: r ggplot2 pca

我正在使用R中的autoplot函数(来自ggfortify包)来绘制PCA的前两个组件,如下所示,使用iris数据集作为示例:

data<-iris
data_dims<-(data[, 1:4])
data$Species<-as.factor(data$Species)
plot1<-autoplot(prcomp(data_dims, center = TRUE, scale = TRUE), data = data, colour = 'Species', frame = TRUE)

但是,我想知道是否有人可以帮助我绘制旋转的解决方案?我知道要获得这样的旋转解决方案:

pcompanalysis<-prcomp(data, center = TRUE, scale = TRUE)

pcompanalysis_rot <- varimax(pcompanalysis$rotation)

但是,我不确定如何在autoplot()函数中使用这个旋转的解决方案?

编辑:示例现在使用虹膜数据集来允许再现。

1 个答案:

答案 0 :(得分:2)

Here is a possibile solution:

library(ggfortify)
library(pracma)

# Generate a dataset
set.seed(1234) 
n <- 20
p <- 25
ncomp <- 2
data_dims <- matrix(rnorm(n*p),nrow=n)
data <- data.frame(data_dims, Species=cut(runif(n), breaks=4))

# Perform PCA and calculate varimax rotated scores
pca.obj <- prcomp(data_dims, center=T, scale=T)
rawLoadings <- pca.obj$rotation[,1:ncomp] %*% diag(pca.obj$sdev, ncomp, ncomp)
varimax.obj <- varimax(rawLoadings)
rotatedLoadings <- varimax.obj$loadings

# Create a prcomp object with varimax rotated scores
pca_obj <- list(sdev=pca.obj$sdev, rotation=t(varimax.obj$rotmat), 
              center=NULL, scale=NULL, x=scale(pca.obj$x[,1:ncomp]))
name.pcs <- paste0("PC",1:ncomp)
dimnames(pca_obj$rotation) <- list(name.pcs,name.pcs)
dimnames(pca_obj$x) <- list(rownames(data_dims),name.pcs)
class(pca_obj) <- "prcomp"

plot1 <- autoplot(pca_obj, data=data, colour='Species', 
                  frame=TRUE, variance_percentage=F)
plot1

For more details see here中的HREF属性。

enter image description here