如何用ggplot2绘制分类箱线图并添加阈值相关汇总注释?
解决方法
首先修正你计算注释文本的代码——原代码在第一次分组汇总后丢失了y列,导致后续mutate(below_thresh)会报错,这里给出更简洁且正确的计算方式:
# 假设V是你定义的阈值,先计算标签数据框 label_df <- df %>% group_by(x) %>% summarise( n_per_grp = n(), # 每组总样本量 n_below_thresh = sum(y < V), # 每组低于阈值的样本数 .groups = "drop" ) %>% mutate( perc_below_thresh = round(n_below_thresh/n_per_grp*100, 3), final_lbl = paste0(perc_below_thresh, "% (", n_below_thresh, "/", n_per_grp, ")") )
绘制箱线图并添加注释
不需要用stat_summary,因为你已经提前计算好了注释文本,直接用geom_text或geom_label就能把注释放在每个分类的上方,步骤如下:
- 先绘制基础箱线图
- 调用
geom_text,指定数据源为刚才计算的label_df,并设置注释的位置(比如箱线图的上方)
完整示例代码(含模拟数据):
library(tidyverse) library(ggplot2) # 模拟测试数据 set.seed(123) df <- tibble( x = rep(c("组A", "组B", "组C"), each = 50), y = c(rnorm(50, 10, 2), rnorm(50, 8, 3), rnorm(50, 12, 1.5)) ) V <- 7 # 自定义阈值 # 计算注释标签 label_df <- df %>% group_by(x) %>% summarise( n_per_grp = n(), n_below_thresh = sum(y < V), .groups = "drop" ) %>% mutate( perc_below_thresh = round(n_below_thresh/n_per_grp*100, 3), final_lbl = paste0(perc_below_thresh, "% (", n_below_thresh, "/", n_per_grp, ")") ) # 绘图 ggplot(df, aes(x = x, y = y)) + geom_boxplot(fill = "lightblue", alpha = 0.7) + # 将注释放在每个分类的上方,y值设为全局最大值加偏移量(可根据数据调整) geom_text(data = label_df, aes(x = x, y = max(df$y) + 0.8, label = final_lbl), size = 4, fontface = "bold") + labs(title = "分类箱线图(含低于阈值比例注释)", x = "分类变量", y = "连续变量") + theme_minimal()
进阶调整(精准对齐箱线图顶端)
如果想让注释更精准地对齐箱线图的顶端,可以先计算每个组的箱线图上须位置,再把这个值作为y的参数:
# 计算每个组的上须位置 upper_whisker <- df %>% group_by(x) %>% summarise(upper = quantile(y, 0.75) + 1.5*IQR(y), .groups = "drop") # 合并标签和上须位置 label_df <- label_df %>% left_join(upper_whisker, by = "x") # 绘图时用upper作为y的基础,加小偏移 geom_text(data = label_df, aes(x = x, y = upper + 0.3, label = final_lbl), size = 4, fontface = "bold")
内容的提问来源于stack exchange,提问作者Ankit
相关产品推荐
相关产品推荐

