You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在ggplot2中如何单独调整箱线图样本量文本标签的位置?

解决方案

1. 整体统一偏移所有标签

如果所有组的标签都可以向同一个方向挪动避开均值线,直接修改你自定义的give.n函数中的y轴返回值即可,不需要额外调用position类参数:

# 调整函数里的偏移数值即可,正数向上偏移,负数向下,根据你的DSI数值范围调整
give.n <- function(x){ 
  return(c(y = mean(x) + 2, label = length(x))) 
}
# 原有ggplot绘图代码保持不变

2. 单独调整每个组的标签位置

如果需要给不同的县设置不同的偏移量,提前汇总每个组的统计值后自定义偏移即可,自由度最高:

library(dplyr)
# 先汇总每个县的均值、样本量,自定义每个标签的y轴位置
label_df <- ratings_county_2019_DI %>%
  group_by(county) %>%
  summarise(
    di_mean = mean(di, na.rm = TRUE),
    n = n()
  ) %>%
  mutate(
    # 按你的需求给不同县设置不同偏移,这里仅为示例
    label_y = case_when(
      county == "县A" ~ di_mean + 3,
      county == "县B" ~ di_mean - 1.5,
      TRUE ~ di_mean + 2
    )
  )

# 绘图时替换原来的stat_summary为geom_text加载自定义标签数据
ggplot(ratings_county_2019_DI, aes(x=county, y=di))+ 
  geom_boxplot(aes(fill = county), fatten = 1.25)+ 
  scale_fill_manual(values = col19, aesthetics = c("colour", "fill"))+ 
  labs(x = "County", y = " DSI (%)")+ 
  theme_minimal()+ 
  theme(legend.position = "top")+ 
  geom_text(data = label_df, aes(y = label_y, label = n)) +
  ggtitle("Disease Serverity Index 2019 Survey")+ 
  theme(plot.title = element_text(hjust = 0.5))

如果还是有重叠问题,可以给geom_text加size = 3调小字号,或者加check_overlap = TRUE自动隐藏重叠的标签。


内容的提问来源于stack exchange,提问作者Clark

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 16:15:02