Search code examples
rggplot2facet-wrap

mean line in every facet_wrap


ggplot(data = results, aes(x = inst, y = value, group = inst)) +
  geom_boxplot() +
  facet_wrap(~color) +
  #geom_line(data = mean, 
          #mapping = aes(x = inst, y = average, group = 1))
  theme_bw()

When I run the code above with the code line commented, it runs and gives the graph below but I want a joining mean lines on the boxplots based on its own color category for each group in facet wraps. Any ideas how can I do that?

enter image description here


Solution

  • Your code is generally correct (though you'll want to add color = color to the aes() specification in geom_line()), so I suspect your mean dataset isn't set up correctly. Do you have means grouped by both your x axis and faceting variable? Using ggplot2::mpg as an example:

    library(dplyr)   # >= v1.1.0
    library(ggplot2)
    
    mean_dat <- summarize(mpg, average = mean(hwy), .by = c(cyl, drv))
    
    ggplot(mpg, aes(factor(cyl), hwy)) +
      geom_boxplot() + 
      geom_line(
        data = mean_dat, 
        aes(y = average, group = 1, color = drv),
        linewidth = 1.5,
        show.legend = FALSE
      ) +
      facet_wrap(~drv) +
      theme_bw()
    

    Alternatively, you could use stat = "summary" and not have to create a means dataframe at all:

    ggplot(mpg, aes(factor(cyl), hwy)) +
      geom_boxplot() + 
      geom_line(
        aes(group = 1, color = drv),
        stat = "summary",
        linewidth = 1.5,
        show.legend = FALSE
      ) +
      facet_wrap(~drv) +
      theme_bw()
    # same result as above