我想使用包autoplot()
的函数ggfortify
在PC3上绘制PC2。默认情况下,只显示PC1和PC2:
library(ggfortify)
myPCA <- prcomp(iris[-5])
autoplot(myPCA)
我可以通过重新排序和重命名prcomp对象中的列来获得我想要的东西:
myPCAtrunc <- myPCA
myPCAtrunc[[1]] <- myPCAtrunc[[1]][c(2,3,1,4)]
myPCAtrunc[[2]] <- myPCAtrunc[[2]][,c(2,3,1,4)]
colnames(myPCAtrunc[[2]]) <- c("PC1","PC2","PC3","PC4") # fake names
myPCAtrunc[[5]] <- myPCAtrunc[[5]][,c(2,3,1,4)]
colnames(myPCAtrunc[[5]]) <- c("PC1","PC2","PC3","PC4") # fake names
autoplot(myPCAtrunc, xlab = "PC2", ylab="PC3")
我知道这是正确的,因为它与plot(myPCA$x[, c(2,3)])
相同。
但必须有一种更清洁的方法来解决它。一些想法?
答案 0 :(得分:9)
最近解决了这个问题(here)。
autoplot(myPCA, # your prcomp object
x = 2, # PC2
y = 3) # PC3
答案 1 :(得分:1)
在查看被调用的方法时,看起来它只是为了绘制PC1和PC2而设计:
getS3method("autoplot", class(myPCA) )
> ...
> if (is_derived_from(object, "prcomp")) {
> x.column <- "PC1"
> y.column <- "PC2"
> loadings.column <- "rotation"
> }
> ...
如果这是您的选项,我建议您使用ggbiplot
包并设置choices
参数:
library(ggbiplot)
ggbiplot(myPCA, choices = 2:3 , var.axes =FALSE)
答案 2 :(得分:1)
您可以做的只是修改您的prcomp对象。然后像这样更改y标签:
pca_test=pca
pca_test$x=pca_test$x[,c(1,3)]
colnames(pca_test$x)=c("PC1","PC2")
pca_test$rotation=pca_test$rotation[,c(1,3)]
colnames(pca_test$rotation)=c("PC1","PC2")
autoplot(pca_test,data=df,colour='study',shape='species')+scale_color_manual(values=c("Red","Blue","Green","Purple","Brown","Orange","Black"))+scale_fill_manual(values=c("Red","Blue","Green","Purple","Brown","Orange","Black"))+theme_bw()+ylab("PC3")
希望它有所帮助!
JC