在 ggplot2 中创建组平滑图

Create group smooth plot in ggplot2

我目前正在绘制一个包含 100 个人超过 10 年的图表,其中图表中的每条线代表一个人。这 100 个人也被分为 4 个不同的分层组。我正在尝试使用 stat_smooth 函数为每个组创建平滑图。然而,它目前正在为每个人绘制一个平滑的图。 ggplot2 有没有办法绘制这个平滑函数?

此外,对于平滑函数,我希望使用 gam 函数并指定权重和相关类型。有没有办法在 stat_smooth 函数中做到这一点?

这是问题的一个例子:

set.seed(1)
D = data.table(id = rep((1:100),10), value = rnorm(1000), stratification = rep(c("A","B","C","D"), 25))
setkey(D, id)
D = D[, time := 1:10, by = id]

plot = ggplot(data = D, aes(x = time, y = value, group = id, color = stratification) )+
  geom_line()+ 
  theme_classic()  +
  xlab("Time from index (years)") +
  ylab("value") 

我想分别为A、B、C、D组创建四个平滑函数。有没有办法在 ggplot 中做到这一点?

如果您简单地放下 group = id,它将使用 id 的颜色来代替,给您想要的颜色:

ggplot(data = D, aes(x = time, y = value, color = stratification) )+
  geom_smooth()+ 
  theme_classic()  +
  xlab("Time from index (years)") +
  ylab("value")