1
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

Balina
  • 81
  • 5
  • 3
    Do you mean literally that you ran code with part of it in quotation marks, or you just added those here to highlight the line? Marking it off with comments would probably be clearer. Regardless, you probably want something like [this](https://stackoverflow.com/q/3989987/5325862)? – camille Feb 15 '23 at 15:36
  • 3
    It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input that can be used to test and verify possible solutions. – MrFlick Feb 15 '23 at 15:37
  • 1
    There's another [here](https://stackoverflow.com/q/18599411/5325862) – camille Feb 15 '23 at 15:49

1 Answers1

1

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
zephryl
  • 14,633
  • 3
  • 11
  • 30