如何以数据帧格式绘制主成分的方差?

问题描述

我正在尝试绘制如下所示的内容,但使用数据框对象。我的特征值采用 DF 格式,如下所示。我们如何绘制这个图?

library("factoextra")
data(iris)
res.pca <- prcomp(iris[,-5],scale = TRUE)
# Extract the  eigenvalues/variances
get_eig(res.pca)
fviz_eig(res.pca,geom="line")

enter image description here

DF <- as.data.frame(res.pca$x)

解决方法

您可以像这样计算解释方差的比例:

library(factoextra)
library(tidyverse)

data(iris)
res.pca <- prcomp(iris[,-5],scale = TRUE)

DF <- as.data.frame(res.pca$x)

new_DF <- tibble(`Percentage of Variance Explained` = c(sd(DF$PC1)^2 / 4,sd(DF$PC2)^2 / 4,sd(DF$PC3)^2 / 4,sd(DF$PC4)^2 / 4),Dimensions = 1:4)
ggplot(new_DF,aes(x = Dimensions,y = `Percentage of Variance Explained`)) +
  geom_line() +
  geom_point() +
  scale_y_continuous(labels = scales::percent_format())

example.png