0

I would like to add for my ggplot boxplot a mean with a legend, but I don't know how.

The follwing R script is include in a function for a single variable:


p2 <- ggplot(df, aes("",!!sym(x))) +
    geom_boxplot() +
    stat_summary(fun=mean, geom="crossbar", color="steelblue2") 
    

Thanks.

1 Answers1

0

adapted from this solution Use stat_summary to annotate plot with number of observations you could try something like this:

fun_mean <- function(x) {return(data.frame(y = mean(x), 
                                           label = paste0("mean = ", round(mean(x), 2))))}
ggplot(mtcars, aes(factor(cyl), mpg, label = rownames(mtcars))) +
geom_boxplot(fill = "grey80", colour = "#3366FF") + 
stat_summary(fun.data = fun_mean, geom = "text")

Hope that helps!

SamuelR
  • 121
  • 6