Search code examples
ggplot2bar-chartline

ggplot2_ combining line and barplot in one graph


Let's say I'm creating the grouped barplot by something like this:

data <- data.frame(time = factor(1:3), type = LETTERS[1:4], values = runif(24)*10)
ggplot(data, aes(x = type, y = values, fill = time)) +
  stat_summary(fun=mean, geom='bar', width=0.55, size = 1, position=position_dodge(0.75))

Inside each type I want to connect all bar tops (meaning to connect 3 bars for A, 3 bars for B, and so on) with the line. I'd like to get something like that as a result: enter image description here

Is there a way to do that ? Thank you!


Solution

  • I changed the code to another logic that I prefer, that is to prepare the data before using ggplot().

    Code

    library(dplyr)
    library(ggplot2)
    
    data <- data.frame(time = factor(1:3), type = LETTERS[1:4], values = runif(24)*10)
    
    pdata <- data %>% group_by(type,time) %>% summarise(values = mean(values,na.rm = TRUE)) %>% ungroup()
    
    pdata %>% 
      ggplot(aes(x = type, y = values)) +
      geom_col(
        mapping = aes(fill = time, group = time),
        width = 0.55,
        size = 1,
        position = position_dodge(0.75)
      )+
      geom_line(
        mapping = aes(group = type),
        size = 1,
        position = position_dodge2(.75)
      )
    

    Output

    enter image description here