ggplot2:如何在分组翻转条形图左侧添加样本量文本
解决方案
要把样本量n放在每个条形的左侧(因coord_flip翻转了坐标轴,对应原条形图的底部),需要做两个关键调整:
- 给显示
n的geom_text指定固定的y轴位置为0,让文本对齐到条形的起始端; - 保持
position = position_dodge(width = 0.9),和geom_col的默认dodge宽度一致,确保每个分组的文本和条形一一对应。
修改后的完整代码如下:
library(tidyverse) # Some sample data n <- 100 df <- data.frame(grp = sample(c("A", "B", "C", "Total"), size = n, replace = TRUE), value = runif(n = n, min = 1, max = 5), item = sample(c("Item1", "Item2", "Item3"), size = n, replace = TRUE)) # Barplot df %>% group_by(item, grp) %>% summarise(n = n(), mean = mean(value)) %>% ungroup() %>% ggplot(aes(x = item, group = grp, y = mean, fill = grp)) + geom_col(position = 'dodge') + coord_flip() + geom_text(aes(label = round(mean, 2)), position = position_dodge(width=0.9), size = 4) + # 调整后的geom_text:指定y=0,position与geom_col匹配,hjust避免重叠 geom_text(aes(label = n, y = 0), position = position_dodge(width=0.9), size = 4, hjust = 1)
额外补充:添加hjust = 1可以让文本紧贴条形左侧边缘,避免和条形主体重叠,优化视觉效果。
内容的提问来源于stack exchange,提问作者D. Studer
相关产品推荐
相关产品推荐

