I am looking to create a graph of longitudinal data by age and sex, similar to the graph in this image , from this paper https://www.thelancet.com/journals/lanpub/article/PIIS2468-2667(20)30258-9/fulltext.
To graph model results in the past, I have used both ggplot2 and ggpredict. I prefer ggpredict because it graphs the results accounting for covariates, but I am OK with graphing in ggplot2 if it can't be done in ggpredict.
I am providing a minimal reproducible example below, with id, wave (2 waves, separated by 6 years), age, sex, tst (total sleep time), and bmi for a covariate.
id<-rep(1:50, 2) wave<-c(rep(1, 50),rep(2, 50)) tst<-c(sample(7:9,50, replace = T),sample(4:7,50, replace = T)) mydf<-data.frame(id,wave,tst) mydf$age[mydf$wave==1]<-sample(40:90,50, replace = T) mydf$age[mydf$wave==2]<-mydf$age[mydf$wave==1]+6 mydf$bmi<-sample(20:30,50, replace = T) mydf$sex<-sample(1:2,50, replace = T) mydf$age.cat<-cut(mydf$age[mydf$wave==1], breaks = 3,labels = c(1,2,3)) ##Overall model## (model <- lmer( tst ~ wave + age + sex + bmi +(1|id), data = mydf))
I tried to graph it with ggplot2 using the following syntax, however I'm not sure that the graph is exactly what I'm looking for. I would like to graph change in tst between waves 1 and 2, by age group and sex. TST would be on the y axis, age would be on the x axis, with separate lines for age group and sex, with standard errors. The lines will correspond to within-person change in TST between waves 1 and 2.
I think that the graph right now is showing the between subjects effects of age on tst, and not taking into account the fact that the data is nested within-person. Any help would be greatly appreciated.
ggplot(mydf,aes(x=age, y=tst, color=as.factor(sex), group=as.factor(age.cat), linetype=as.factor(age.cat)))+ geom_smooth(data=mydf[mydf$sex==1,], method = lm, formula = y~x)+ geom_smooth(data=mydf[mydf$sex==2,], method = lm, formula = y~x)+ geom_point() + theme_bw()