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

如何用ggplot2创建无重叠的边际均值效应图(附数据集)

解决方案:用tidyverse+ggh4x绘制无重叠的边际均值图

步骤1:加载工具包并导入数据

library(tidyverse)
library(ggh4x)

# 导入示例数据集
df <- structure(list(SecondFactor = structure(c(NA, NA, NA, NA, 1L, 
2L, 1L, 2L, 1L, 2L, 1L, 2L, 3L, 4L, 3L, 4L), levels = c("D_AMPER = 1", 
"D_AMPER = 2", "E_DPT = 1", "E_DPT = 2"), class = "factor"), 
    FirstFactor = structure(c(1L, 2L, 7L, 8L, 1L, 1L, 2L, 2L, 
    3L, 3L, 4L, 4L, 5L, 5L, 6L, 6L), levels = c("A_CONC = 1", 
    "A_CONC = 2", "B_TEMP = 1", "B_TEMP = 2", "C_PT = 1", "C_PT = 2", 
    "D_AMPER = 1", "D_AMPER = 2"), class = "factor"), y = c(31.7083333333333, 
    29.4583333333333, 29.2083333333334, 31.9583333333333, 29.5, 
    28.9166666666667, 33.9166666666667, 30, 22.0833333333334, 
    36.3333333333333, 39.5833333333333, 24.3333333333333, 29.4166666666667, 
    31.5833333333333, 31.75, 29.5833333333333), section = structure(c(1L, 
    1L, 2L, 2L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 5L, 5L, 5L, 5L
    ), levels = c("1", "2", "3", "4", "5"), class = "factor")), class = "data.frame", row.names = c(NA, 
-16L))

步骤2:优化因子标签(可选)

简化因子名称,让图表显示更清爽:

df <- df %>%
  mutate(
    FirstFactor = fct_recode(FirstFactor,
      "A=1" = "A_CONC = 1",
      "A=2" = "A_CONC = 2",
      "B=1" = "B_TEMP = 1",
      "B=2" = "B_TEMP = 2",
      "C=1" = "C_PT = 1",
      "C=2" = "C_PT = 2",
      "D=1" = "D_AMPER = 1",
      "D=2" = "D_AMPER = 2"
    ),
    SecondFactor = fct_recode(SecondFactor,
      "D=1" = "D_AMPER = 1",
      "D=2" = "D_AMPER = 2",
      "E=1" = "E_DPT = 1",
      "E=2" = "E_DPT = 2"
    )
  )

步骤3:绘制无重叠图表

通过position_dodge错开重叠点,结合ggh4x的分面功能模拟Excel的分组布局:

ggplot(df, aes(x = FirstFactor, y = y, color = SecondFactor)) +
  # 用position_dodge横向错开同一主因子下的次级因子点
  geom_point(size = 3, position = position_dodge(width = 0.5)) +
  # 按section横向分面,还原Excel的分组拼接效果
  facet_wrap2(vars(section), nrow = 1, strip.position = "bottom") +
  # 设置标签与标题
  labs(
    y = "估计边际均值",
    color = "次级因子",
    title = "各分组边际均值对比"
  ) +
  # 优化主题样式
  theme_minimal() +
  theme(
    strip.placement = "outside",
    strip.background = element_rect(fill = "#f0f0f0", color = "black"),
    axis.text.x = element_text(angle = 45, hjust = 1)
  )

核心逻辑说明

  • position_dodge(width = 0.5):解决同一主因子下不同次级因子的点重叠问题,让点横向分散;
  • facet_wrap2():ggh4x的增强分面函数,支持更灵活的布局设置,这里实现分组横向排列的效果;
  • 如果不需要分面,也可以将x轴设为interaction(section, FirstFactor),再配合position_dodge使用,同样能避免重叠。

内容的提问来源于stack exchange,提问作者Steven Ouellette

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 05:44:51