library(tidyverse)
## -- Attaching packages ----------------------------------------------------------------- tidyverse 1.3.0 --
## √ ggplot2 3.3.2 √ purrr 0.3.4
## √ tibble 3.0.3 √ dplyr 1.0.1
## √ tidyr 1.1.2 √ stringr 1.4.0
## √ readr 1.4.0 √ forcats 0.5.0
## Warning: package 'readr' was built under R version 4.0.3
## -- Conflicts -------------------------------------------------------------------- tidyverse_conflicts() --
## x dplyr::filter() masks stats::filter()
## x dplyr::lag() masks stats::lag()
df <- data.frame(
Phylum=c("Ruminococcaceae","Bacteroidaceae","Eubacteriaceae","Lachnospiraceae","Porphyromonadaceae"),
GroupA=c(37.7397,31.34317,222.08827,5.08956,3.7393),
GroupB=c(113.2191,94.02951,66.26481,15.26868,11.2179),
GroupC=c(123.2191,94.02951,46.26481,35.26868,1.2179),
GroupD=c(37.7397,31.34317,222.08827,5.08956,3.7393)
)
df.long <- df %>% gather(group, abundance, -Phylum)
##
link_dat <- df %>%
arrange(by=desc(Phylum)) %>%
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)
df.long
## Phylum group abundance
## 1 Ruminococcaceae GroupA 37.73970
## 2 Bacteroidaceae GroupA 31.34317
## 3 Eubacteriaceae GroupA 222.08827
## 4 Lachnospiraceae GroupA 5.08956
## 5 Porphyromonadaceae GroupA 3.73930
## 6 Ruminococcaceae GroupB 113.21910
## 7 Bacteroidaceae GroupB 94.02951
## 8 Eubacteriaceae GroupB 66.26481
## 9 Lachnospiraceae GroupB 15.26868
## 10 Porphyromonadaceae GroupB 11.21790
## 11 Ruminococcaceae GroupC 123.21910
## 12 Bacteroidaceae GroupC 94.02951
## 13 Eubacteriaceae GroupC 46.26481
## 14 Lachnospiraceae GroupC 35.26868
## 15 Porphyromonadaceae GroupC 1.21790
## 16 Ruminococcaceae GroupD 37.73970
## 17 Bacteroidaceae GroupD 31.34317
## 18 Eubacteriaceae GroupD 222.08827
## 19 Lachnospiraceae GroupD 5.08956
## 20 Porphyromonadaceae GroupD 3.73930
link_dat
## y.1 y.2 x.1 x.2
## 1 37.73970 113.21910 1.35 1.65
## 2 113.21910 123.21910 2.35 2.65
## 3 123.21910 37.73970 3.35 3.65
## 4 41.47900 124.43700 1.35 1.65
## 5 124.43700 124.43700 2.35 2.65
## 6 124.43700 41.47900 3.35 3.65
## 7 46.56856 139.70568 1.35 1.65
## 8 139.70568 159.70568 2.35 2.65
## 9 159.70568 46.56856 3.35 3.65
## 10 268.65683 205.97049 1.35 1.65
## 11 205.97049 205.97049 2.35 2.65
## 12 205.97049 268.65683 3.35 3.65
## 13 300.00000 300.00000 1.35 1.65
## 14 300.00000 300.00000 2.35 2.65
## 15 300.00000 300.00000 3.35 3.65
ggplot(df.long, aes(x=group, y=abundance, fill=Phylum)) +
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)

#######ref https://mp.weixin.qq.com/s/eaVdaj3ubDdhKsKyfzK1Sg