Search code examples
rggplot2facetlmer

plot lmer result in faceted ggplot


I'm analysing some repeated measures drug trials data and I'm not sure how to plot the lmer results when using faceted ggplots. I have made an initial plot of the individual slopes from the master dataset, but I'm doing the lmer analyses separately by sex.

Using publicly available data, which has only 2 treatment groups compared to the four I have, this is the replicable example below. It uses the reshape2, lme4, and ggplot2 packages.

CatAnx <- read.fwf(file=("http://www.stat.ufl.edu/~winner/data/cats_anxiety1.dat"),
               widths=c(-6,2,-5,3,-5,3,-7,1,-7,1,-7,1,-7,1,-7,1,-6,2,-6,2,-6,2,-6,2,-6,2))
colnames(CatAnx) <- c('ID','Weight','Age_Months','Gender','Environment','Origin','Treatment','Result','EmoTime1','EmoTime2',
                  'EmoTime3','EmoTime4','EmoTime5')
library("reshape2")
CatAnxRM <- melt(CatAnx, id.vars=c("ID", "Gender", "Treatment"), measure.vars=c("EmoTime1", "EmoTime2", "EmoTime3",
                                                                            "EmoTime4", "EmoTime5"))
CatAnxRM$Sex <- with(CatAnxRM, ifelse(Gender==1, "Neut Female", ifelse(Gender==2, "Neut Male", "Whole Female")))
CatAnxRM$Time <- with(CatAnxRM, ifelse(variable=="EmoTime1", 1, ifelse(variable=="EmoTime2", 2, ifelse(variable=="EmoTime3", 3,
                                  ifelse(variable=="EmoTime4", 4,5)))))
CatAnxRM.Male <- subset(CatAnxRM, Gender=="2")
library("lme4")
Male.lmer <- lmer(value ~ Treatment * Time + (Time + 1|ID), data=CatAnxRM.Male)
library("ggplot2")
AnxScores<-ggplot(CatAnxRM, aes(Time, value, colour=Sex))+
geom_line(aes(group = ID))+
labs(x="Time Anxiety Measured", y="Anxiety Score", title="Effect of Zylkene on Anxiety")+ 
facet_grid(. ~ Treatment)
AnxScores

Information about the dataset is here.

How do I plot the correct summary line from lmer in both facets, which differ on the basis of Treatment?

In my real life example, I'll also be analysing the females so there will be two sets of lines to plot per facet.


Solution

  • Create a data frame (e.g. lines.df) with intercept (e.g. int) and slope (slo) variables where each line of the df corresponds to one facet, then plot over the top:

    + geom_abline(aes(intercept = int, slope = slo), data = lines.df)