2

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?

alistaire
  • 42,459
  • 4
  • 77
  • 117
A.Choe
  • 23
  • 5

1 Answers1

4

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

Jon Spring
  • 55,165
  • 4
  • 35
  • 53
  • Hi @jon-spring any hint on how to expand this to three or more categories (A, B, C)? Thanks – Tapper May 04 '21 at 00:37
  • (There is this as a base R alternative: https://gist.github.com/JEFworks/20ba5bed2aa3ac92556085da9b2be35b#file-connectedbarplot-r) – Tapper May 04 '21 at 02:25