prcomp 之后 ggplot2 和 autoplot() 的区别?
我用 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)
为什么我得到不同的轴?
I made a PCA plot with autoplot(), but I wanted to have ellipses around only 2 of the groups instead of all 3. Therefore I switched to ggplot. However, it seems that my axes are different between autoplot and ggplot methods. Look at the difference between p1 and 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]))
x2I made a PCA plot with autoplot(), but I wanted to have ellipses around only 2 of the groups instead of all 3. Therefore I switched to ggplot. However, it seems that my axes are different between autoplot and ggplot methods. Look at the difference between p1 and p2:
iris[, 5]` <- as.factor(x2I made a PCA plot with autoplot(), but I wanted to have ellipses around only 2 of the groups instead of all 3. Therefore I switched to ggplot. However, it seems that my axes are different between autoplot and ggplot methods. Look at the difference between p1 and p2:
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)
Why do I get different axes?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在自动绘图方法中,主成分被缩放,因此要获得相同的结果,您可以这样做:
In the autoplot method, the principal components are scaled, so to get the same result you would do: