如何为ggplot中stat_sum的点组添加间距,避免点在同一垂直线重叠?
你可以直接为stat_sum和配套的stat_summary统一配置position_dodge参数,就能实现分组点整齐横向错开的效果,完全符合你的需求,不需要用geom_jitter。
完整可运行的修改后代码如下:
# 提前加载依赖包 library(tidyverse) dataset <- data.frame(drug = rep(c("drug 1", "drug 2", "drug 3", "drug 4", "drug 5"), 20), mouse =rep(paste0("test", 1:2), 50), color = rep(c("color1", "color2", "color3", "color4"), 25), amount_color = runif(100, 1, 2) ) # 定义统一的偏移规则,保证点和均值线完全对齐 pd <- position_dodge(width = 0.4) dataset %>% ggplot(aes(x = drug, y = amount_color, col = mouse, group = mouse)) + # 为stat_sum添加位置偏移 stat_sum(position = pd) + theme_light() + theme(axis.text.x = element_text(angle = 45, hjust=1)) + # 均值线也添加相同的偏移规则,同时缩短线段避免跨组重叠 stat_summary(fun="mean", geom="segment", mapping=aes(xend=..x.. - 0.2, yend=..y..), size = 1.5, position = pd) + stat_summary(fun="mean", geom="segment", mapping=aes(xend=..x.. + 0.2, yend=..y..), size = 1.5, position = pd)
调整说明
- 你可以自行修改
position_dodge的width参数调整不同分组的横向间距,数值越大间距越宽 - 如果需要更精细的分组对齐、边距控制,可以将
position_dodge替换为position_dodge2,额外配置padding参数调整组内边距 - 代码中缩短了均值线段的长度,避免不同组的线段重叠,你可以根据展示需求调整
xend的偏移数值
内容的提问来源于stack exchange,提问作者flavinsky
相关产品推荐
相关产品推荐

