Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show non-default principal components using autoplot (ggfortify)

I would like to plot PC2 against PC3 using the function autoplot() of the package ggfortify. By default just PC1 and PC2 are shown:

library(ggfortify)
myPCA <- prcomp(iris[-5])
autoplot(myPCA)

I can get what I want by reordering and renaming columns in the prcomp object:

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")

I know it is correct, because it is the same as plot(myPCA$x[, c(2,3)]).

But there must be a cleaner way to solve it. Some ideas?

like image 761
albifrons Avatar asked Dec 02 '22 15:12

albifrons


1 Answers

This issue was recently solved (here).

autoplot(myPCA,    # your prcomp object
         x = 2,    # PC2
         y = 3)    # PC3
like image 117
eotp Avatar answered Dec 29 '22 17:12

eotp