问题描述
我目前正在研究主成分分析并尝试使用 R prcomp
函数。我的代码如下:
library(dplyr)
iris1 = mutate( iris,Species = factor( Species),logSepalLength = log10( Sepal.Length ),logSepalWidth = log10( Sepal.Width ),logPetalLength = log10( Petal.Length ),logPetalWidth = log10( Petal.Width ),) %>%
dplyr::select(Species,starts_with("log") )
iris1.PCA = prcomp( ~ logSepalLength +
logSepalLength +
logSepalWidth +
logPetalLength +
logPetalWidth,data = iris1,scale. = FALSE )
summary(iris1.PCA)
summary(iris1.PCA)
的输出如下:
Importance of components:
PC1 PC2 PC3 PC4
Standard deviation 0.4979 0.06009 0.05874 0.02337
Proportion of Variance 0.9702 0.01413 0.01350 0.00214
Cumulative Proportion 0.9702 0.98436 0.99786 1.00000
我想使用 ggplot 生成一个漂亮的碎石图,显示每个主成分对总方差的累积贡献。我可以手动进行这个计算,从协方差矩阵开始,使用类似 cumsum(eigenvals)/iris1.cov.trace
的东西。但是,根据summary(iris1.PCA)
,prcomp
输出已经为我们计算了累积比例!那么我们如何利用 summary(iris1.PCA)
对象和 ggplot
的那部分来生成漂亮的碎石图?我知道我们可以手动复制输出值,但我正在寻找更自动化的解决方案(因为硬复制值不是好的软件工程实践)。
我 found 这个使用 ggplot
的碎石图示例(尽管它不使用对总方差的累积贡献):
var_explained_df %>%
ggplot(aes(x=PC,y=var_explained,group=1))+
geom_point(size=4)+
geom_line()+
labs(title="Scree plot: PCA on scaled data")
解决方法
这是一个使用 PCA 输出的示例。摘要中的 sdev
元素是解释的标准偏差。解释的方差是平方标准偏差(即方差)除以所有平方标准偏差之和。
s <- summary(iris1.PCA)
dat <- data.frame(
component = factor(1:length(s$sdev),labels=paste0("PC",1:length(s$sdev))),var_explained = s$sdev^2/sum(s$sdev^2)
)
library(scales)
ggplot(dat,aes(y=var_explained)) +
geom_line(aes(x=component,group=1)) +
geom_point(aes(x=component)) +
labs(x="Component",y="% Variance Explained") +
scale_y_continuous(labels=percent) +
theme_bw() +
ggtitle("Scree plot: PCA on Scaled Data")