首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >R语言聚类树图小例子

R语言聚类树图小例子

作者头像
用户7010445
发布2020-03-03 15:08:02
9760
发布2020-03-03 15:08:02
举报
参考文章
  • https://rpubs.com/shirokaner/320218
  • http://www.sthda.com/english/wiki/beautiful-dendrogram-visualizations-in-r-5-must-known-methods-unsupervised-machine-learning
数据集

R语言内置数据集USArrests

1973年美国50个州每10万人中因袭击、谋杀和强奸而被捕的人数和居住在城市地区的人口比例 层级聚类法 使用到的函数是hclust()

hc<-hclust(dist(USArrests),method="ave")
使用```ggdendro```包对结构进行展示

安装ggdendro包并查看帮助文档

install.packages("ggdendro")
help(package="ggdendro")

将层级聚类的结果转化为ggdendro作图需要的格式,用到的函数是dendro_data(hc,type="rectangle") type有两个参数可选

  • rectangle
df2<-dendro_data(hc,type="rectangle")
ggplot(segment(df1))+
  geom_segment(aes(x=x,y=y,xend=xend,yend=yend))

image.png

  • triangle
df2<-dendro_data(hc,type="triangle")
ggplot(segment(df2))+
  geom_segment(aes(x=x,y=y,xend=xend,yend=yend))

image.png

简单美化
ggplot(segment(df1))+
  geom_segment(aes(x=x,y=y,xend=xend,yend=yend))+
  geom_text(data=df1$labels,aes(x=x,y=y-1,label=label),
            angle=90,hjust=1,vjust=0.3,size=3)+
  scale_y_continuous(expand=c(0.2,0))+
  theme_bw()+
  geom_point(data=df1$labels,aes(x=x,y=y),color="red")

image.png

给不同的类别添加不同的颜色
df1$labels$Group<-c(rep("A",16),rep("B",14),rep("C",20))
ggplot(segment(df1))+
  geom_segment(aes(x=x,y=y,xend=xend,yend=yend))+
  geom_text(data=df1$labels,aes(x=x,y=y-1,label=label,color=Group),
            angle=90,hjust=1,vjust=0.3,size=3)+
  scale_y_continuous(expand=c(0.2,0))+
  theme_bw()+labs(x="",y="")+
  geom_point(data=df1$labels,aes(x=x,y=y,color=Group,shape=Group))+
  scale_color_brewer("",palette = "Set1")+
  theme(legend.position="none",
        panel.grid=element_blank(),
        panel.border=element_blank(),
        axis.text = element_blank(),
        axis.ticks = element_blank())

image.png

ggplot(segment(df1))+
  geom_segment(aes(x=x,y=y,xend=xend,yend=yend))+
  geom_text(data=df1$labels,aes(x=x,y=y-1,label=label,color=Group),
            angle=90,hjust=1,vjust=0.3,size=3)+
  scale_y_continuous(expand=c(0.2,0))+
  theme_bw()+labs(x="",y="")+
  geom_point(data=df1$labels,aes(x=x,y=y,color=Group,shape=Group))+
  scale_color_brewer("",palette = "Set1")+
  theme(legend.position="none",
        panel.grid=element_blank(),
        panel.border=element_blank(),
        axis.text = element_blank(),
        axis.ticks = element_blank())+
  geom_rect(aes(xmin=0,xmax=16.5,ymin=0,ymax=90),color="red",fill="red",alpha=0.005)+
  geom_rect(aes(xmin=16.5,xmax=30.5,ymin=0,ymax=90),color="blue",fill="blue",alpha=0.003)+
  geom_rect(aes(xmin=30.5,xmax=50,ymin=0,ymax=90),color="green",fill="green",alpha=0.005)
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-01-10,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 小明的数据分析笔记本 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 参考文章
  • 数据集
  • 使用```ggdendro```包对结构进行展示
  • 简单美化
  • 给不同的类别添加不同的颜色
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档