I am struggling with how to add both individual and a group trend line to my plots. (R and using ggplot2).
Here is the code that I am using:
MensHG.fm2=lmer(HGNewtons~Temperature+QuadTemp+Run+(1|Subject),MenstrualData) #model
plot.hg<-data.frame(MensHG.fm2@frame,fitted.re=fitted(MensHG.fm2))
g1<-ggplot(plot.hg,aes(x=Temperature,y=HGNewtons))+geom_point()
g2<-g1+facet_wrap(~Subject, nrow=6)+ylab(bquote('HG MVF (N)'))+xlab(bquote('Hand ' ~T[sk] ~(degree*C)))
g3<-g2+geom_smooth(method="glm", formula=y~ploy(x,2), se=FALSE) #This gives me my individual trendlines
Now I want to put on the trendline for the g1 part of the data (ie overall trend) onto each of my individual plots - what is the best way to do this? I can see the trend if I use the code:
g5=g1+geom_smooth(method="glm", formula=y~poly(x,2), se=FALSE)
BUT this trendline disspears as soon as I do the facet-wrap (I get the same output as g3)
It does not appear to solve the problem by using: g4<-g3+geom_smooth(data=MensHG.fm2)
Without a minimal working example of your data, I used the builtin iris data. Here I pretended that the Species were different subjects for the sake of demonstration.
I also use two extra packages for simplicity,
broom
anddplyr
.augment
frombroom
does the same thing as you did above with..., fitted.re=fitted(MensHG.fm2)
, but with some extra bells and whistles. I also usedplyr::select
, but that's not strictly needed, depending on the output you desire (the difference between Fig 2 vs Fig 3).Note that I
#
-commented two statements:data = ...
andfacet_wrap(...)
. With those lines commented out, you get an output like this:You have your population smooth (
.fixed
for fixed-effects) across the whole range, and then you have group smooths that show the fitted model values (.fitted
), taking into account the subject-level intercepts.Then you can show this in facets by taking out the second
#
-comment mark in the code snippet:This is the same, but since the fitted values only exist within the range of the original data for each subject-level panel, the population smooth is truncated to just that range.
To get around that, we can remove the first
#
-comment mark: