R语言实现PCA降维

R代码实现PCA降维过程

链接: http://blog.sciencenet.cn/blog-3448646-1270918.html
数据集是经典的鸢尾花
做简单的记录,只附代码和结果,
下面展示一些 内联代码片

具体自行操作,可交流
install.packages("ggplot2")
library(ggplot2)
df <- iris[c(1, 2, 3, 4)]
head(df)
df_pca <- prcomp(df) #计算主成分
df_pcs <-data.frame(df_pca$x,Species=iris$Species)  
head(df_pcs,3)  #查看主成分结果
#3.2 ggplot2 绘制PCA图
#1) Species分颜色
ggplot(df_pcs,aes(x=PC1,y=PC2,color=Species))+ geom_point()
#2)去掉背景及网格线
ggplot(df_pcs,aes(x=PC1,y=PC2,color=Species))+ 
  
  geom_point()+ 
  
  theme_bw() +
  
  theme(panel.border=element_blank(),
        
        panel.grid.major=element_blank(),
        
        panel.grid.minor=element_blank(),
        
        axis.line= element_line(colour = "black"))
#3) 添加PC1  PC2的百分比
percentage<-round(df_pca$sdev/sum(df_pca$sdev) * 100,2)

percentage<-paste(colnames(df_pcs),"(",
                  
                  paste(as.character(percentage), "%", ")", sep=""))

ggplot(df_pcs,aes(x=PC1,y=PC2,color=Species))+
  
  geom_point()+ 
  
  xlab(percentage[1]) +
  
  ylab(percentage[2])



#4) 添加置信椭圆
ggplot(df_pcs,aes(x=PC1,y=PC2,color = Species))+ 
  
  geom_point()+stat_ellipse(level = 0.95, show.legend = F) + 
  
  annotate('text', label = 'setosa', x = -2, y = -1.25, 
           
           size = 5, colour = '#f8766d') +
  
  annotate('text', label = 'versicolor', x = 0, y = - 0.5, 
           
           size = 5, colour = '#00ba38') +
  
  annotate('text', label = 'virginica', x = 3, y = 0.5,
           
           size = 5, colour = '#619cff')
#5) 查看各变量对于PCA的贡献

df_r <- as.data.frame(df_pca$rotation)

df_r$feature <- row.names(df_r)

df_r 
#贡献度绘图

ggplot(df_r,aes(x=PC1,y=PC2,label=feature,color=feature )) + 
  
  geom_point()+ geom_text(size=3)
#四 PCA绘图汇总展示

ggplot(df_pcs,aes(x=PC1,y=PC2,color=Species )) +
  
  geom_point()+xlab(percentage[1]) +
  
  ylab(percentage[2]) + 
  
  stat_ellipse(level = 0.95, show.legend = F) +
  
  annotate('text', label = 'setosa', x = -2, y = -1.25,
           
           size = 5, colour = '#f8766d') +
  
  annotate('text', label = 'versicolor', x = 0, y = - 0.5, 
           
           size = 5, colour = '#00ba38') +
  
  annotate('text', label = 'virginica', x = 3, y = 0.5, 
           
           size = 5, colour = '#619cff') +
  
  labs(title="Iris PCA Clustering", 
       
       subtitle=" PC1 and PC2 principal components ",    
       
       caption="Source: Iris") + theme_classic()


screeplot(df_pca,type = "line",lwd=3)#碎石图


!

在这里插入图片描述

  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值