gpt4 book ai didi

r - 有没有办法将总和添加到 fviz_eig 图中?

转载 作者:行者123 更新时间:2023-12-04 09:45:56 29 4
gpt4 key购买 nike

我正在尝试实现一个很好的 PC 绘图以及解释的累积方差。
我正在处理的数据框位于 https://www.kaggle.com/miroslavsabo/young-people-survey?select=responses.csv

df.responses <- read.csv("Data/responses.csv")
pref <- colnames(df.responses[0:63]) #columns for Music, Movies and Hobbies preferences
for(i in 1:length(pref)){
df.responses[is.na(df.responses[,i]), i] <- median(df.responses[,i], na.rm = TRUE)
}
df.movies <- data.frame(df.responses[20:31])

上面我刚刚加载了 df,删除了我感兴趣的 cols 的 na 并选择了我想要 PCA 的子集。
library(ggplot2)
library(factoextra)

pca.movies <- prcomp(df.movies, scale = TRUE,)
pca.movies$rotation <- -pca.movies$rotation
pca.movies$x <- -pca.movies$x

fviz_pca_var(pca.movies,
col.var = "contrib",
gradient.cols = c("#00AFBB", "#E7B800", "#FC4E07"),
repel = TRUE
)

pv.movies <- pca.movies$sdev^2
pvp.movies <- pv.movies/sum(pv.movies)

pvp.movies

fviz_eig(pca.movies,
addlabels = T,
barcolor = "#E7B800",
barfill = "#E7B800",
linecolor = "#00AFBB",
choice = "variance",
ylim=c(0,25))

plot(cumsum(pvp.movies),xlab = "Cumulative proportion of Variance Explained", ylim=c(0,1),type = 'b')

有了上面的内容,我设法为 PCA 获得了两个不错的图,我想在第二个图中添加累积总和线(第三个丑图中显示的那个)
有没有办法将这样的行添加到 fviz_eig 图中?
我知道这个 PCA 并不是很有效,我只是用一些 dataviz 来挑战自己。

最佳答案

fviz_eig 返回的对象是 ggplot对象,因此您可以按如下方式合并两个图:

p <- fviz_eig(pca.movies,
addlabels = T,
barcolor = "#E7B800",
barfill = "#E7B800",
linecolor = "#00AFBB",
choice = "variance",
ylim=c(0,25))

df <- data.frame(x=1:length(pvp.movies),
y=cumsum(pvp.movies)*100/4)
p <- p +
geom_point(data=df, aes(x, y), size=2, color="#00AFBB") +
geom_line(data=df, aes(x, y), color="#00AFBB") +
scale_y_continuous(sec.axis = sec_axis(~ . * 4,
name = "Cumulative proportion of Variance Explained") )
print(p)

enter image description here

关于r - 有没有办法将总和添加到 fviz_eig 图中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62117449/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com