[英]R: ggfortify: “Objects of type prcomp not supported by autoplot”
我正在嘗試使用ggfortify來顯示我使用prcomp做的PCA的結果。
示例代碼:
iris.pca <- iris[c(1, 2, 3, 4)]
autoplot(prcomp(iris.pca))
錯誤:autoplot不支持prcomp類型的對象。 請改用qplot()或ggplot()。
奇怪的是,autoplot專門用於處理prcomp - ggplot的結果,qplot無法處理這樣的對象。 我正在運行R版本3.2,剛剛從github上下載了ggfortify。
有誰能解釋這個消息?
我猜你沒有加載所需的庫,代碼如下:
library(devtools)
install_github('sinhrks/ggfortify')
library(ggfortify); library(ggplot2)
data(iris)
iris.pca <- iris[c(1, 2, 3, 4)]
autoplot(prcomp(iris.pca))
將工作
即使ggfortify
簡單性很迷人,我也不鼓勵使用它與標准ggplot2函數重疊( 例如 , replacing previous import 'dplyr::vars' by 'ggplot2::vars' when loading 'ggfortify'
,警告replacing previous import 'dplyr::vars' by 'ggplot2::vars' when loading 'ggfortify'
)。 一個聰明的解決方法是直接使用ggplot2
。
在這里,我提出了兩個版本及其結果。
# 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()
注意:使用簡單的ggplot2數據幀結構着色要容易得多。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.