Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

r - How to use geom_bar for making connected bar plot in ggplot2?

I'm trying to use geom_bar for getting a bar plot

bar plot

connected with lines. How to draw connecting lines between samples?

ggplot()+
  geom_bar(data = data_bar,
           aes(x = Sample, y =Percentage, fill = Taxon),
           colour = 'white', width =0.3, stat="identity")+
  guides(fill= guide_legend(ncol = 1))

I tried it by using both geom_bar and geom_line, but it looks weird

weird plot.

It looks like connected line starts from the center of A sample to the center of B sample.

ggplot()+
  geom_bar(data = data_bar,
           aes(x = Sample, y =Percentage, fill = Taxon),
           colour = 'white', width =0.3, stat="identity")+
  geom_line(data = rev(data),
            aes(x = Sample, y =Percentage, group = Taxon, color = Taxon),
            size = 0.3, stat = 'identity')+
  guides(fill= guide_legend(ncol = 1))

I want to get a better plot like connected line starts from the right edge on the bar of A sample to the left edge on the bar of B sample.

How can I make it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I'm not aware of a built-in way to do this, but you can accomplish the same using geom_segment if you know where the bars are.

First some fake data:

set.seed(0)
data_bar <- data.frame(
  stringsAsFactors = F,
  Sample = rep(c("A", "B"), each = 10),
  Percentage = runif(20),
  Taxon = rep(1:10, by = 2)
)

To make the connections simpler, I spread the data to wide format so each connecting line gets a row, with one column related to the first Sample and the other for the 2nd Sample:

library(tidyverse)
ggplot() +
  geom_bar(data = data_bar,
           aes(x = Sample, y =Percentage, fill = Taxon),
           colour = 'white', width = 0.3, stat="identity") +
  geom_segment(data = tidyr::spread(data_bar, Sample, Percentage)
               colour = "white",
               aes(x = 1 + 0.3/2,
                   xend = 2 - 0.3/2,
                   y = cumsum(A),
                   yend = cumsum(B))) +
  theme(panel.background = element_rect(fill = "black"), # to make connecting points          
        panel.grid = element_blank())                    # show up more clearly

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...