Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: ggfortify: "Objects of type prcomp not supported by autoplot"

Tags:

r

pca

ggfortify

I am trying to use ggfortify to visualize the results of a PCA I did using prcomp.

sample code:

iris.pca <- iris[c(1, 2, 3, 4)] 
autoplot(prcomp(iris.pca))  

Error: Objects of type prcomp not supported by autoplot. Please use qplot() or ggplot() instead.

What is odd is that autoplot is specifically designed to handle the results of prcomp - ggplot and qplot can't handle objects like this. I'm running R version 3.2 and just downloaded ggfortify off of github this AM.

Can anyone explain this message?

like image 800
JR Flanders Avatar asked May 05 '15 14:05

JR Flanders


2 Answers

I'm guessing that you didn't load the required libraries, the code below:

library(devtools)
install_github('sinhrks/ggfortify')
library(ggfortify); library(ggplot2)
data(iris)
iris.pca <- iris[c(1, 2, 3, 4)] 
autoplot(prcomp(iris.pca))

will work enter image description here

like image 67
Konrad Avatar answered Nov 14 '22 17:11

Konrad


Even if ggfortify simplicity is charming, I discourage its use for some overlap with standard ggplot2 functions (e.g. the warning replacing previous import ‘dplyr::vars’ by ‘ggplot2::vars’ when loading ‘ggfortify’). A smart workaround would be to use directly ggplot2.

Here I propose the two versions and their results.

# creating the PCA obj using iris data set
iris.pca <- iris[c(1, 2, 3, 4)] 
pca.obj <- prcomp(iris.pca)

# ggfortify way - w coloring
library(ggfortify)
autoplot(pca.obj) + theme_minimal()  


# ggplot2 way - w coloring
library(ggplot2)
dtp <- data.frame('Species' = iris$Species, pca.obj$x[,1:2]) # the first two componets are selected (NB: you can also select 3 for 3D plottings or 3+)
ggplot(data = dtp) + 
       geom_point(aes(x = PC1, y = PC2, col = Species)) + 
       theme_minimal() 

NB: the colouring with straightforward ggplot2 data frame structure is much easier.

theplot

like image 44
Garini Avatar answered Nov 14 '22 17:11

Garini