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

重复测量数据可视化:双分组因子下的ggplot绘图问题

解决重复测量设计均值响应图为空的问题

问题背景

研究采用2×2×3重复测量设计,被试在pre/post两个时间点提供数值响应tcons,同时被分为两个组间因子:

  • pretest_leaning:含pro、anti两个水平
  • condition:含both、counter、favour三个水平

希望绘制两个时间点的均值响应折线图,按上述两个因子的6种组合分组。已计算好的均值数据如下:

structure(list(condition = c("both", "both", "both", "both", 
"counter", "counter", "counter", "counter", "favour", "favour", 
"favour", "favour"), pretest_leaning = c("anti", "anti", "pro", 
"pro", "anti", "anti", "pro", "pro", "anti", "anti", "pro", "pro"
), test = structure(c(1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 
1L, 2L), levels = c("pre", "post"), class = "factor"), tcons_mean = c(-0.407142857142857, 
-0.289285714285714, 0.357142857142857, 0.398809523809524, -0.357142857142857, 
-0.0676691729323308, 0.272727272727273, 0.155844155844156, -0.43984962406015, 
-0.488721804511278, 0.357142857142857, 0.279220779220779)), class = c("grouped_df", 
"tbl_df", "tbl", "data.frame"), row.names = c(NA, -12L), groups = structure(list(
    condition = c("both", "both", "counter", "counter", "favour", 
    "favour"), pretest_leaning = c("anti", "pro", "anti", "pro", 
    "anti", "pro"), .rows = structure(list(1:2, 3:4, 5:6, 7:8, 
        9:10, 11:12), ptype = integer(0), class = c("vctrs_list_of", 
    "vctrs_vctr", "list"))), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -6L), .drop = TRUE))

尝试以下代码后无报错,但图形为空:

ggplot(tcons_long, aes(x = test, y = tcons_mean, colour = pretest_leaning, linetype = condition)) + geom_path()

解决方法

图形为空的核心原因:

  1. 原数据是分组数据框(grouped_df),ggplot默认分组逻辑与数据自带分组冲突
  2. geom_path需要明确的分组规则来连接折线,仅靠colour和linetype无法自动识别双因子的6种组合分组

步骤1:取消数据分组

先将分组数据框转为普通数据框,避免自带分组干扰绘图:

library(dplyr)
tcons_long <- ungroup(tcons_long)

步骤2:明确绘图分组

在aes中添加group = interaction(pretest_leaning, condition),指定按两个因子的交互项分组,确保geom_path正确连接同一分组下的pre和post点。同时可添加geom_point让数据点更清晰:

library(ggplot2)
ggplot(tcons_long, aes(x = test, y = tcons_mean, 
                       colour = pretest_leaning, 
                       linetype = condition,
                       group = interaction(pretest_leaning, condition))) +
  geom_path(linewidth = 1) +  # 调整线宽提升折线辨识度
  geom_point(size = 2) +      # 添加数据点明确数值位置
  labs(x = "测试时间点", y = "tcons均值", 
       colour = "预测试倾向", linetype = "实验条件") +
  theme_minimal()

效果说明

上述代码将生成6条折线,分别对应pretest_leaning和condition的6种组合,每条折线连接同一组的pre和post均值点,颜色区分pro/anti,线型区分both/counter/favour。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 03:46:02