测试文件
链接:https://pan.baidu.com/s/1DF8QgKKtgbEhh2OH5L5GXw 密码:j3zy
#读表,含分组信息(第10列)
pca<-read.csv("pca.csv",row.names = 1)
#定义数据集
df <- pca[c(1, 2, 3, 4,5,6,7,8,9)]
df_pca <- prcomp(df) #计算主成分
df_pcs <-data.frame(df_pca$x, class = pca$class) #定义分组
普通作图
library(ggplot2)
ggplot(df_pcs,aes(x=PC1,y=PC2,color=class))+ geom_point()

#定义百分比
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=class))+
geom_point()+
xlab(percentage[1]) +
ylab(percentage[2])

#加圈95%置信区间,level = 0.95
ggplot(df_pcs,aes(x=PC1,y=PC2,color=class )) + geom_point()+xlab(percentage[1]) + ylab(percentage[2]) + stat_ellipse(level = 0.95, show.legend = F) + theme_bw()

网友评论