使用`prComp`输出摘要的`累计比例`部分生成累计对总方差贡献的屏幕图 [英] Generating a scree plot of the cumulative contribution to total variance by using the `Cumulative Proportion` part of the `prcomp` output summary

查看:0
本文介绍了使用`prComp`输出摘要的`累计比例`部分生成累计对总方差贡献的屏幕图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在学习主成分分析和Rprcomp函数。我的代码如下:

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

我想使用gglot生成一个很好的Scree图,显示每个主成分对总方差的累积贡献。我可以手动计算,从协方差矩阵开始,使用类似cumsum(eigenvals)/iris1.cov.trace的内容。但是,根据summary(iris1.PCA)prcomp产量已经为我们计算了累计比例!那么,我们如何利用对象和部分来生成漂亮的屏幕图呢?我知道我们可以手动复制输出值,但我正在寻找一种更自动化的解决方案(因为硬复制值不是好的软件工程实践)。

ifound使用ggplot的Scree图的示例(尽管它不使用累计对总方差的贡献):

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")

这篇关于使用`prComp`输出摘要的`累计比例`部分生成累计对总方差贡献的屏幕图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆