ggplot2 将 geom_smooth() 应用于跨因子级别的每个参与者

问题描述 投票:0回答:1

我有数据,其中 n 参与者在 2 个“条件”内进行了 3 个“回合”的测量。我想生成一个图表,其中对于每个

geom_smooth()
级别的每个单独参与者,在
bout
上有一个
condition
。应该有 n * 2 条单独的线条,并且线条应根据条件着色(无需在条件之间识别参与者)。

我有这个 R 代码,可以将参与者集中在

condition
:

ggplot(data, aes(bout, y, colour = condition)) +
geom_point() +
geom_smooth(method = "lm", se = F)

enter image description here

这个 R 代码将

condition
汇集到每个参与者中:

ggplot(data, aes(bout, y, colour = condition)) +
geom_point() +
geom_smooth(aes(group = participant), method = "lm", se = F)

enter image description here

本质上,我想将它们组合起来,用 n 粉色线表示控制条件,n 绿色线表示实验条件。

r ggplot2
1个回答
0
投票

在您的问题中包含一些带有

dput
的示例数据或使用常见的玩具数据集会很有帮助。这里的数据很容易重新创建,因此这里是一个使用
interaction
的示例,它从粘贴在一起的一组变量中生成一个因子。

library(ggplot2)
data <- data.frame(
  y = c(
    sort(rnorm(120, 150, 20)),
    sort(rnorm(120, 120, 15))
  ),
  bout = c(
    rep(1:3, each = 40),
    rep(1:3, each = 40)
  ),
  condition = rep(c("ctrl", "exp"), each = 120),
  participant = c(
    rep(1:40, times = 3),
    rep(1:40, times = 3)
  )
)
ggplot(data, aes(bout, y, colour = condition)) +
  geom_point() +
  geom_smooth(aes(group = interaction(condition, participant)),
     method = "lm", se = F, linewidth = 0.5)

© www.soinside.com 2019 - 2024. All rights reserved.