Search code examples
rplotggplot2statsmoothing

Create group smooth plot in ggplot2


I am currently plotting a graph with 100 individuals over 10 years, where each line in the graph is for one individual. The 100 individuals are also grouped into 4 different stratification groups. I am trying to use the stat_smooth function to create a smooth plot for each group. However, it is currently plotting a smooth plot for each individual. Is there a way for ggplot2 to plot this smooth function?

Also, for the smooth function, I wish to use the gam function ans specify weights and correlation type. Is there a way to do that in the stat_smooth function?

Here is an example of the issue:

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") 

I wish to create four smooth functions for group A, B, C and D respectively. Is there a way to do this in ggplot?


Solution

  • If you simply drop the group = id it will use the color as the id instead, giving you want you want:

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

    enter image description here