# R语言主成分分析（PCA）加置信椭圆

### 使用ggplot2绘制

``````head(iris)
ord <- prcomp(iris[,1:4])
summary(ord)
dt <- ord\$x
df <- data.frame(dt,iris\$Species)
summ <- summary(ord)
xlab <- paste0("PC1(",round(summ\$importance[2,1]*100,2),"%)")
ylab <- paste0("PC2(",round(summ\$importance[2,2]*100,2),"%)")
library(ggplot2)
(p1 <- ggplot(df,aes(df\$PC1,df\$PC2,color=df\$iris.Species))+stat_ellipse(aes(fill=df\$iris.Species),type="norm",geom="polygon",alpha=0.2,color=NA)+guides(fill=F)+geom_point()+labs(x=xlab,y=ylab,color=""))
``````

### 使用ggord绘制

R包安装和载入

``````#install.packages('devtools')
library(devtools)
#devtools::install_github('fawda123/ggord')
library(ggord)
``````

``````library(ggord)
#绘制散点图；repel避免标签重叠
(p2 <- ggord(ord,iris\$Species,coord_fix=F,labcol='purple',repel=TRUE))
``````
``````#改变箭头（特征向量）的scaling（箭头大小），arrow length（箭头长度），line color，size（粗细），type：
(p3 <- ggord(ord,iris\$Species,coord_fix=F,labcol='purple',repel=TRUE,arrow=0.25,vec_ext=2,veccol='blue',veclsz=0.5,vectyp='solid'))
``````
``````#隐藏箭头
(p4 <- ggord(ord,grp_in = iris\$Species,coord_fix=F,arrow=0,vec_ext=0,txt=NULL))
``````
``````#自定义点的大小、颜色、透明度
(p5 <- ggord(ord,iris\$Species,coord_fix=F,cols=c('purple','orange','blue'),size=2,alpha=0.7,arrow=0,vec_ext=0,txt=NULL))
``````
``````#取消填充
(p6 <- ggord(ord,iris\$Species,coord_fix=F,cols=c('purple','orange','blue'),size=2,alpha=0.7,arrow=0,vec_ext=0,txt=NULL,poly=FALSE))
``````
``````#自定义椭圆描边样式
(p7 <- ggord(ord,iris\$Species,coord_fix=F,cols=c('purple','orange','blue'),size=2,alpha=0.7,arrow=0,vec_ext=0,txt=NULL,poly=FALSE,polylntyp='dashed'))
``````
``````#描边与分组建立映射
(p8 <- ggord(ord,iris\$Species,coord_fix=F,cols=c('purple','orange','blue'),size=2,alpha=0.7,arrow=0,vec_ext=0,txt=NULL,poly=FALSE,polylntyp=iris\$Species))
``````
``````#添加多边形区域
(p9 <- ggord(ord,iris\$Species,coord_fix=F,cols=c('purple','orange','blue'),size=2,alpha=0.7,arrow=0,vec_ext=0,txt=NULL,ellipse=FALSE,hull=TRUE))
``````
``````#隐藏网格线
(p10 <- p9+scale_shape_manual('Groups',values = c(0,1,2))+theme(panel.grid=element_blank()))
``````