0

I want to plot the overall trend for longitudinal data. I am using the sleepstudy data in lme4 package to demonstrate my problem.

 library("lme4")
 library("ggplot2")
    p1 <- ggplot(data = sleepstudy, aes(x = Days, y = Reaction, group = Subject))
    p1 + geom_line() + geom_point(aes(col = Subject) ,size=2)

When i plot the longitudinal trajectories for each individual, I got this plot enter image description here

Here I am interested in finding the overall trend based on all subjects. For an example based on the above plot we can see an upward trend in general. In general this trend can be anything like linear, quadratic etc. Is this any way to plot this overall trend ?

I tried this . But i got smoothed curves for each subject instead of getting the overall trend

p1  + geom_point() +  geom_smooth(method = "lm") 

enter image description here

Can anyone help me figure this out ?

Thank you

student_R123
  • 702
  • 6
  • 20

1 Answers1

1

Don't know if I understand correctly:

library("lme4")
library("ggplot2")
ggplot(data = sleepstudy, aes(x = Days, y = Reaction))+
  geom_point(aes(colour = Subject), alpha = .3)+
  geom_smooth()+
  theme(legend.position = "none")

enter image description here

As you can see you'll have loess function:

> geom_smooth()` using method = 'loess' and formula 'y ~ x'

If you need lm just specify the argument method into geom_smooth.

library("lme4")
library("ggplot2")
ggplot(data = sleepstudy, aes(x = Days, y = Reaction))+
  geom_point(aes(colour = Subject), alpha = .3)+
  geom_smooth(method = "lm")+
  labs(title = "Linear Model (LM)")+
  theme(legend.position = "none")

The result:

enter image description here

Borexino
  • 584
  • 4
  • 19
  • Hi thank you for the answer. Although the data has a linear trend in this situation, sometimes it can be quadratic. In that case what type of smoothing method can we use ? – student_R123 May 03 '20 at 17:57
  • It depends on what you would like to show. However, if you need quadratic take a look [here](https://stackoverflow.com/q/42764028/3519756) – Borexino May 03 '20 at 18:01
  • Thank you . One more thing i have in mind. In the plot that i showed you , there are smoothed curves for each individual. So is there any way to get the average of those smoothed curves and plot that as the overall trend ? I may want to try this because these are longitudinal data – student_R123 May 03 '20 at 18:11
  • Probably what you need is a regression model. Look at `glm` or `gam` – Borexino May 03 '20 at 18:18