我用 autoplot() 制作了一個 PCA 圖,但我希望只有 2 個組而不是全部 3 個組有橢圓。因此我切換到 ggplot。但是,似乎我的坐標軸在 autoplot 和 ggplot 方法之間是不同的。看看p1和p2的區別:
library(ggplot2)
library(ggfortify)
library(tidyr)
x <- iris[1:4]
pc <- prcomp(x)
df <- cbind(pc$x[,1:2], iris[,5]) %>% as.data.frame()
df$PC1 <- as.numeric(df$PC1)
df$PC2 <- as.numeric(df$PC2)
df$V3 <- as.factor(df$V3)
#ggplot method
p1 <- ggplot(df, aes(PC1, PC2, colour = V3))
geom_point(size = 3, aes(shape = V3))
stat_ellipse(geom = "polygon", aes(fill = after_scale(alpha(colour, 0))),
data = df[df$V3 == "1" | df$V3 == "2",], size = 1)
p1
#autoplot method
y <- prcomp(x)
x2 <- as.data.frame(cbind(x, iris[,5]))
x2$`iris[, 5]` <- as.factor(x2$`iris[, 5]`)
p2<- autoplot(y,
data = x2,
colour = 'iris[, 5]',
label = F,
shape = 'iris[, 5]',
size = 2)
p2
Created on 2022-02-22 by the reprex package (v2.0.1)
為什么我得到不同的軸?
uj5u.com熱心網友回復:
在 autoplot 方法中,主成分被縮放,所以要得到相同的結果,你可以這樣做:
x <- iris[1:4]
pc <- prcomp(x)
df <- cbind(pc$x[,1:2], iris[,5]) %>% as.data.frame()
df$PC1 <- as.numeric(df$PC1) / (pc$sdev[1] * sqrt(nrow(iris)))
df$PC2 <- as.numeric(df$PC2) / (pc$sdev[2] * sqrt(nrow(iris)))
df$V3 <- as.factor(df$V3)
#ggplot method
p1 <- ggplot(df, aes(PC1, PC2, colour = V3))
geom_point(size = 3, aes(shape = V3))
stat_ellipse(geom = "polygon", aes(fill = after_scale(alpha(colour, 0))),
data = df[df$V3 == "1" | df$V3 == "2",], size = 1)
p1

轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/432030.html
