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

R语言ggplot分组条形图geom_text标签错位问题求助

ggplot条形图n标签错位问题解决

你遇到的问题是右侧蓝色条形的n标签未随条形偏移,出现错位,即便使用了position_dodge(0.9)和group参数也未解决。

问题原因

geom_text未正确识别分组信息,导致position_dodge偏移规则未生效。尽管全局aes设置了group=affected,但geom_text的aes中未明确关联分组映射,ggplot无法为标签应用正确的偏移逻辑。

修正后的代码

factor <- c("Included", "Included", "Excluded", "Excluded")
affected <- c("Affected", "Not Affected", "Affected", "Not Affected")
mean_rating <- c(76.00000, 39.55556, 49.00000, 41.62069)
n <- c(23, 2, 17, 19)

df1 <- data.frame(factor, affected, mean_rating, n)

ggplot(df1, aes(x = factor, y = mean_rating)) + 
  geom_bar(aes(fill = affected, group = affected), stat = "identity", position = position_dodge(0.9)) +
  # 在geom_text的aes中明确指定group,确保偏移生效
  geom_text(aes(label = paste("n =", n), group = affected), 
            hjust = 1, vjust = -0.35, position = position_dodge(0.9)) +
  guides(fill = FALSE, color = FALSE)

调整标签对齐方式(左侧对齐)

如果需要让标签和条形左侧对齐,只需将hjust设置为0(原代码hjust=1是右对齐):

ggplot(df1, aes(x = factor, y = mean_rating)) + 
  geom_bar(aes(fill = affected, group = affected), stat = "identity", position = position_dodge(0.9)) +
  geom_text(aes(label = paste("n =", n), group = affected), 
            hjust = 0, vjust = -0.35, position = position_dodge(0.9)) +
  guides(fill = FALSE, color = FALSE)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 12:23:26