带连接线的堆积柱状图

堆积柱状图加上连接线能够更好地看出变化情况,参照“宏基因组”的教程改写了代码,封装成了一个函数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
bar_percent_segemnt <- function(df){

library(tidyverse)
library(ggsci)

colnames(df)[1] = 'cat'

sum_group = apply(df[,2:ncol(df)], 2, sum)
for (i in 1:length(sum_group)) {
df[,i+1] = df[,i+1] / sum_group[i]
}

df.long <- df %>% reshape2::melt(id.vars = 1)
colnames(df.long) <- c('cat','group','value')

## 组间连线数据:
## 假设第一列是Phylum
link_dat <- df %>%
arrange(by=desc(cat)) %>%
mutate_if(is.numeric, cumsum)

bar.width <- 0.7
link_dat <- link_dat[, c(1,2,rep(3:(ncol(link_dat)-1),each=2), ncol(link_dat))]

link_dat <- data.frame(y=t(matrix(t(link_dat[,-1]), nrow=2)))

link_dat$x.1 <- 1:(ncol(df)-2)+bar.width/2
link_dat$x.2 <- 1:(ncol(df)-2)+(1-bar.width/2)

p <- ggplot(df.long, aes(x = group, y = value, fill = cat)) +
geom_bar(stat = "identity", width=bar.width,
col='black') +
geom_segment(data=link_dat,
aes(x=x.1, xend=x.2, y=y.1, yend=y.2), inherit.aes = F) +
scale_y_continuous(expand = c(0,0),labels = scales::percent) +
scale_fill_aaas() +
theme_bw() +
theme(legend.title = element_blank(),
legend.text = element_text(color = 'black',size = 10, family = 'Arial', face = 'plain'),
panel.background = element_blank(),
panel.grid = element_blank(),
axis.text = element_text(color = 'black',size = 10, family = 'Arial', face = 'plain'),
axis.title = element_text(color = 'black',size = 10, family = 'Arial', face = 'plain'),
axis.ticks = element_line(color = 'black'))

return(p)
}

💌lixiang117423@gmail.com

💌lixiang117423@foxmail.com


带连接线的堆积柱状图
https://lixiang117423.github.io/article/3a1c1c6c/
作者
小蓝哥
发布于
2021年1月17日
许可协议