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
相关产品推荐
相关产品推荐

