R: ggfortify: “Objects of type prcomp not supported by autoplot”

五迷三道 提交于 2019-12-07 04:38:34

问题


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?


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/30056144/r-ggfortify-objects-of-type-prcomp-not-supported-by-autoplot

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!