如何在 R 中将新向量绘制到 PCA space
How to plot a new vector onto a PCA space in R
我是 R 中主成分分析的新手,我的问题很幼稚。我已经使用 R 中的函数 'prcomp' 完成了矩阵 (A) 的 PCA。现在我想将一个向量绘制到 A 的 PC1 和 PC2 的 PCA space 上。我该怎么做矢量的绘图?
使用双标图(红色箭头是原始space中的维度):
a <- princomp(iris[1:4])
biplot(a, cex=0.5)
您也可以自己对 PCA space 进行投影,如下所示:
library(ggplot2)
data <- iris[1:4]
labels <- iris[,5]
res <- princomp(data)
res.proj <- as.matrix(data) %*% res$loadings[,1:2]
ggplot(as.data.frame(res.proj), aes(Comp.1, Comp.2, col=labels)) + geom_point()
使用 prcomp 的同一图(数值更稳定):
data <- iris[1:4]
labels <- iris[,5]
res <- prcomp(data)
res.proj <- as.matrix(data) %*% res$rotation[,1:2]
ggplot(as.data.frame(res.proj), aes(PC1, PC2, col=labels)) + geom_point()
更喜欢 ggbiplot:
library(ggbiplot)
g <- ggbiplot(res, obs.scale = 1, var.scale = 1,
groups = labels, ellipse = TRUE,
circle = TRUE)
g <- g + scale_color_discrete(name = '')
g <- g + theme(legend.direction = 'horizontal',
legend.position = 'top')
print(g)
我是 R 中主成分分析的新手,我的问题很幼稚。我已经使用 R 中的函数 'prcomp' 完成了矩阵 (A) 的 PCA。现在我想将一个向量绘制到 A 的 PC1 和 PC2 的 PCA space 上。我该怎么做矢量的绘图?
使用双标图(红色箭头是原始space中的维度):
a <- princomp(iris[1:4])
biplot(a, cex=0.5)
您也可以自己对 PCA space 进行投影,如下所示:
library(ggplot2)
data <- iris[1:4]
labels <- iris[,5]
res <- princomp(data)
res.proj <- as.matrix(data) %*% res$loadings[,1:2]
ggplot(as.data.frame(res.proj), aes(Comp.1, Comp.2, col=labels)) + geom_point()
使用 prcomp 的同一图(数值更稳定):
data <- iris[1:4]
labels <- iris[,5]
res <- prcomp(data)
res.proj <- as.matrix(data) %*% res$rotation[,1:2]
ggplot(as.data.frame(res.proj), aes(PC1, PC2, col=labels)) + geom_point()
更喜欢 ggbiplot:
library(ggbiplot)
g <- ggbiplot(res, obs.scale = 1, var.scale = 1,
groups = labels, ellipse = TRUE,
circle = TRUE)
g <- g + scale_color_discrete(name = '')
g <- g + theme(legend.direction = 'horizontal',
legend.position = 'top')
print(g)