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

在R的ggplot分组误差棒图中为每组内数据点添加连线

实现分组内数据点连线的解决方案

只需在你的ggplot代码中添加geom_line(),并设置与点、误差棒一致的position_dodge参数,就能让线和对应分组的点对齐,实现目标效果。

修改后的完整代码:

dat_a = structure(list(exposure = c("HDL", "HDL", "HDL", "HDL", "HDL", 
"HDL", "HDL", "HDL", "HDL"), event = c("mRS", "mRS", "mRS", "mRS", 
"mRS", "mRS", "mRS", "mRS", "mRS"), model = structure(c(1L, 1L, 
1L, 2L, 2L, 2L, 3L, 3L, 3L), levels = c("low", "middle", "high"
), class = "factor"), group = c("middle", "low", "high", "middle", 
"low", "high", "middle", "low", "high"), margin = c(0.292, 0.372, 
0.349, 0.25, 0.336, 0.281, 0.252, 0.35, 0.278), LL = c(0.273, 
0.327, 0.308, 0.23, 0.287, 0.235, 0.226, 0.285, 0.22), UL = c(0.311, 
0.417, 0.391, 0.27, 0.385, 0.326, 0.278, 0.415, 0.336)), row.names = c(NA, 
-9L), class = c("tbl_df", "tbl", "data.frame"))

pd = position_dodge(.7)

ggplot(dat_a, aes(colour=group, y=margin, x=model, group=group))+
  geom_line(position = pd, size = 1) +  # 新增连线层,与点使用相同的位置调整
  geom_point(position=pd, shape=16, size=4)+
  geom_errorbar(aes(ymax = UL, ymin=LL), position=pd, width=0.2, size=1.1)+
  labs(title = "", x="", y="Marginal probability of poor prognosis") +
  guides(color=guide_legend(title="HDL cholesterol level"))+
  scale_color_jama()+
  theme_classic()+
  theme(axis.title = element_text(size=14),
        axis.text = element_text(size = 12),
        legend.text = element_text(size=12),
        legend.title = element_text(size=12),
        legend.position = 'right')+ 
  ylim(0.2, 0.5)

核心要点:

  • 必须给geom_line()设置position = pd,因为你的点和误差棒都用了position_dodge(.7)偏移位置,线只有同步偏移才能和点对齐。
  • 原代码的aes中已经指定group=group,这会让geom_line自动按group列的分组连接对应的数据点,实现跨x轴分组的连线效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 09:05:28