Joining means on a boxplot with a line (ggplot2)

后端 未结 2 540
逝去的感伤
逝去的感伤 2020-12-02 11:26

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

2条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-02 12:08

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

    library(dplyr); library(ggplot2)
    
    x <- factor(rep(1:10, 100)); y <- rnorm(1000);
    df <- data.frame(x=x, y=y);
    df_for_line <- 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))
    

    Again, group = 1 is the key.

提交回复
热议问题