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