1.概念
层次聚类方法的基本思想是:通过某种相似性测度计算节点之间的相似性,并按相似度由高到低排序,逐步重新连接个节点。该方法的优点是可随时停止划分,主要步骤如下:
(1)移除网络中的所有边,得到有n个孤立节点的初始状态;
(2)计算网络中每对节点的相似度;
(3)根据相似度从强到弱连接相应节点对,形成树状图;
(4)根据实际需求横切树状图,获得社区结构。
2.R语言实现
library(ggdendro)
library(ggplot2)
library(factoextra)
library(ape)
#导入文件\
ADdata<-read.csv("G:\\R_Language\\R-code\\R_bioinformatic-master\\作业\\合并数据.csv",header = TRUE,row.names=2)
#删掉第一列
ADdata<-ADdata[,-1]
#将数据标准化
ADdata<-scale(ADdata)
#层次聚类(全联动:complete)
tree<-hclust(dist(ADdata),method = "complete")
#用plot绘制树状图
plot(tree,cex=0.5)
#利用ape包绘制不同形状的树状图
plot(as.phylo(tree), type = "cladogram", cex = 0.3, label.offset = 0.3)
plot(as.phylo(tree), type = "fan",cex = 0.5)
#用ggplot2包绘制树状图,用ggdendro包进行辅助
df<-dendro_data(tree,type = "rectangle")
df1<-df$segments
df2<-df$labels
ggplot()+
geom_segment(data = df1,aes(x=x,y=y,xend=xend,yend=yend))+
geom_text(data = df2,aes(x=x,y=y-3,label=label),angle=90,size=3)+
labs(title="ADdata",
x="dist",
y="height")
#用factoextra包对树状图进行美化
fviz_dend(tree,
cex=0.5,
k=7,
lwd=0.5,
palette="jco",
rect=TRUE,
lower_rect = -1,
rect_fill = TRUE,
rect_border = "jco",
type = "circular")
3.运行结果
(1)
(2)
(3)