如何在ggplot中为stat_summary生成的均值点添加y轴变量均值标签?
Hey there! Adding mean value labels to your existing ggplot is straightforward—you can either extend your use of stat_summary or precompute the means and add them with geom_text. Here are two solid approaches:
Method 1: Extend with stat_summary (Quick & Integrated)
This keeps everything within the ggplot pipeline, no extra data wrangling needed:
library(ggplot2) # Set seed for reproducibility so your random data matches set.seed(123) df_1 <- data.frame(group=rep(c("A","B","C"),3),value=rnorm(9)) ggplot(df_1,aes(x=group,y=value)) + # Bootstrap confidence interval error bars stat_summary(fun.data=mean_cl_boot, geom="errorbar", width=0.1) + # Mean point (slightly enlarged for visibility) stat_summary(fun.y=mean, geom="point", size=3) + # Mean value labels, rounded to 2 decimals, placed above the point stat_summary( fun.y=mean, geom="text", aes(label=round(..y.., 2)), vjust=-1 # Adjust this to move labels up/down (use 1.5 to place below) )
The ..y.. variable inside aes() refers to the computed mean value from stat_summary, and rounding makes the labels clean. Tweak vjust or add hjust if you need to adjust positioning to avoid overlap with error bars.
Method 2: Precompute Means (More Control)
If you want to customize the labels further (like changing color, formatting, or reusing the mean values elsewhere), precompute them first with dplyr:
library(ggplot2) library(dplyr) set.seed(123) df_1 <- data.frame(group=rep(c("A","B","C"),3),value=rnorm(9)) # Calculate group means group_means <- df_1 %>% group_by(group) %>% summarise(mean_value = mean(value)) ggplot(df_1,aes(x=group,y=value)) + stat_summary(fun.data=mean_cl_boot, geom="errorbar", width=0.1) + stat_summary(fun.y=mean, geom="point", size=3) + # Add labels from the precomputed data frame geom_text( data = group_means, aes(y=mean_value, label=round(mean_value, 2)), vjust=-1, color="darkred" # Customize label color here )
This approach gives you full control over the label dataset—you can add extra formatting (like adding "Mean: " before the number) or adjust values before plotting.
Either method will get you the labeled mean points you need!
内容的提问来源于stack exchange,提问作者Jens Stach

