通过ggplot2绘制一个美观的堆砌条形图,并添加聚类树,关注公众号R语言数据分析指南
后台回复treebar获得实例数据及代码,废话不多说直接看代码
定义颜色卡
rm(list=ls())
pacman::p_load(tidyverse,reshape,RColorBrewer,ggtree,aplot)
colors <-c("#E41A1C","#1E90FF","#FF8C00","#4DAF4A","#984EA3",
"#40E0D0","#FFC0CB","#00BFFF","#FFDEAD","#90EE90",
"#EE82EE","#00FFFF","#F0A3FF", "#0075DC",
"#993F00","#4C005C","#2BCE48","#FFCC99",
"#808080","#94FFB5","#8F7C00","#9DCC00",
"#426600","#FF0010","#5EF1F2","#00998F",
"#740AFF","#990000","#FFFF00")
读入数据绘制行聚类树
data <- read.delim("data.xls",header = T,row.names = 1,
check.names = F,sep="\t") %>%
mutate(sum= rowSums(.),ID=row.names(.),
persent = sum/sum(sum)*100,sum=NULL) %>%
filter(persent >=1) %>% select(-persent) %>%
select(ID, everything())
p <- data %>% select(-ID) %>% t()
tree <- hclust(dist(p)) %>%
ggtree(layout="rectangular",branch.length="none")+
geom_tiplab(hjust = -.5,size=3,fontface="plain")+
xlim_tree(9)
a1 <- melt(data)
a2 <- "group.xls" %>% read.delim()
a4 <- NULL
for (i in seq_len(nrow(a1))) {
a4[i] <- a2[which(a2[,1] == a1[i, 2]),2] }
a1[,4] <- a4
绘制水平柱状图
bar <- a1 %>% ggplot(aes(variable,value,fill=ID))+
geom_bar(stat="identity",position="fill")+
labs(x="",y="")+
theme_minimal()+expand_limits(x=0,y=0)+
theme(axis.title.x=element_blank(),
axis.text.x=element_blank(),
axis.text.y=element_blank(),
axis.ticks.y=element_blank(),
axis.ticks.x=element_blank(),
legend.title=element_blank())+
scale_fill_manual(values = colors)+
scale_y_continuous(expand=c(0,0))+
coord_flip()
aplot包将聚类树与柱状图拼接
bar %>% insert_left(tree,width=.5)