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

如何调整ggplot2中箱线图与配对散点及geom_path至箱间区域?

解决方案

要把配对的散点和连线移到两个箱线图之间,核心是给散点/连线的x轴位置设置偏移,避开箱线图的区域。具体实现如下:

方法:自定义x轴偏移位置

  1. 原factor(name)对应的数值位置是1(Q)和2(A),我们可以把Q的散点移到1.2,A的移到1.8——这个位置刚好在两个箱线图之间(箱线图宽度0.12,Q的箱线范围是1±0.06,A是2±0.06)。

  2. 修改后的完整代码:

set.seed(123)
df <- data.frame(
  ID = 1:50,
  Q = rnorm(50),
  A = rnorm(50,1)
)

# 缩小抖动宽度,避免散点超出中间区域
pj <- position_jitter(seed = 1, width = .05, height = 0)

df %>%
  pivot_longer(-ID) %>%
  # 添加偏移后的x位置
  mutate(x_pos = case_when(
    name == "Q" ~ 1.2,
    name == "A" ~ 1.8
  )) %>%
  ggplot() +
  # 箱线图保留原x轴分组
  geom_boxplot(
    aes(x = factor(name), y = value, fill = factor(name)),
    width = 0.12,
    outlier.color = NA,
    alpha = 0.5
  ) +
  # 散点使用偏移后的x位置
  geom_point(
    aes(x = x_pos, y = value),
    alpha = 0.5, col = "blue",
    position = pj
  ) +
  # 连线使用偏移后的x位置,按ID分组
  geom_path(aes(x = x_pos, y = value, group = ID),
            alpha = 0.5,
            position = pj
  ) +
  # 还原x轴刻度和标签,保证可读性
  scale_x_continuous(breaks = c(1,2), labels = c("Q","A"))

关键说明

  • 调整position_jitter的width参数(从0.1改为0.05),防止散点超出中间区域
  • 通过mutate自定义散点/连线的x位置,精准落在箱线图之间
  • 用scale_x_continuous维持原x轴的标签显示,不破坏图表可读性

内容的提问来源于stack exchange,提问作者Chris Ruehlemann

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 01:12:18