ord <- prcomp(iris[, 1:4])
summary(ord)
#提取不同記錄的PC1~PC4數值,即點的橫縱坐標值;
dt<-ord$x
head(dt)
#將iris數據集的第5列數據合併進來;
df<-data.frame(dt,iris$Species)
head(df)
#生成坐標軸標題;
summ<-summary(ord)
xlab<-paste0("PC1(",round(summ$importance[2,1]*100,2),"%)")
ylab<-paste0("PC2(",round(summ$importance[2,2]*100,2),"%)")
#載入ggplot2包;
library(ggplot2)
p1<-ggplot(data = df,aes(x=df$PC1,y=df$PC2,color=df$iris.Species))+
stat_ellipse(aes(fill=df$iris.Species),
type = "norm", geom ="polygon",alpha=0.2,color=NA)+
geom_point()+labs(x=xlab,y=ylab,color="")+
guides(fill=F)
p1
#載入所需R包;
library(ggord)
#繪製散點圖;repel避免標籤重疊;
p2 <- ggord(ord, iris$Species,coord_fix=F,labcol = 'purple', repel = TRUE)
p2
#改變箭頭(特徵向量)的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')
p3
#隱藏箭頭;
p4 <- ggord(ord, grp_in = iris$Species,coord_fix=F,
arrow=0, vec_ext =0,txt=NULL)
p4
#自定義點的大小和顏色、透明度;
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)
p5
#改變置信橢圓透明度;
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)
p6
#自定義置信橢圓描邊的樣式;
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")
p7
#或者讓描邊與分組建立映射關係;
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)
p8
#添加多邊形區域;
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)
p9
#自定義點的樣式;
#隱藏網格線;
library(ggplot2)
p10<-p9+scale_shape_manual('Groups', values = c(0, 1, 2))+
theme(panel.grid=element_blank())
p10
#所需R包的安裝;
#install.packages('devtools')
library(devtools)
#install_github('fawda123/ggord')
library(ggord)
#安裝ggfortify包;
#install.packages("ggfortify")
#載入ggfortify包;
library(ggfortify)
#快速繪製主成分散點圖;
autoplot(ord, data = iris, colour = 'Species')
#添加特徵向量;
autoplot(ord, data = iris, colour = 'Species',
loadings = TRUE, loadings.colour = 'blue',
loadings.label = TRUE, loadings.label.size = 3)
#載入cluster包;
#添加K-means聚類結果;給定 frame = TRUE,可以把每個集群圈出來。
library(cluster)
autoplot(fanny(iris[-5], 3), frame = TRUE)
#你也可以通過 frame.type 來選擇圈的類型。
#更多選擇請參照ggplot2::stat_ellipse裡面的frame.type的type關鍵詞。
autoplot(pam(iris[-5], 3), frame = TRUE, frame.type = 'norm')
#添加Fisher局部判別分析聚類;
#lfda包支持一系列的Fisher局部判別分析方法,包括半監督lfda,非線性lfda。
#install.packages("lfda")
library(lfda)
# Fisher局部判別分析 (LFDA)
model <- lfda(iris[-5], iris[, 5], 4, metric="plain")
autoplot(model, data = iris, frame = TRUE, frame.colour = 'Species')
實用科研工具推薦
詳實生信軟體教程分享
前沿創新組學文章解讀
獨家生信視頻教程發布