可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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.
