Joining means on a boxplot with a line (ggplot2)

Viewed 33501

I have a boxplot showing multiple boxes. I want to connect the mean for each box together with a line. The boxplot does not display the mean by default, instead the middle line only indicates the median. I tried

ggplot(data, aes(x=xData, y=yData, group=g)) 
    + geom_boxplot() 
    + stat_summary(fun.y=mean, geom="line")

This does not work.

Interestingly enough, doing

stat_summary(fun.y=mean, geom="point") 

draws the median point in each box. Why would "line" not work?

Something like this but using ggplot2, http://www.aliquote.org/articles/tech/RMB/c4_sols/plot45.png

2 Answers

Another longer approach (in case if the data is in two different ) is:

library(dplyr); library(ggplot2)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union

x <- factor(rep(1:10, 100)); y <- rnorm(1000);
df <- data.frame(x=x, y=y);
df_for_line <- df %>% group_by(x) %>% summarise(mean_y = mean(y));
ggplot(df, aes(x = x, y = y)) + geom_boxplot() + 
    geom_path(data = df_for_line, aes(x = x, y = mean_y, group = 1))

Created on 2021-04-15 by the reprex package (v1.0.0)


Again, `group = 1` is the key.
Related