简体   繁体   中英

Plotting lmer() in ggplot2

I'm trying to adjust my graph to make it suitable for a scientific report. See example below (from here: http://glmm.wikidot.com/faq ).

How do I change the ggplot settings so the lines are displayed in greyscale?

library("lme4")
library("ggplot2") # Plotting
data("Orthodont",package="MEMSS")
fm1 <- lmer(
formula = distance ~ age*Sex + (age|Subject)
, data = Orthodont
)

newdat <- expand.grid(
age=c(8,10,12,14)
, Sex=c("Female","Male")
, distance = 0
)

mm <- model.matrix(terms(fm1),newdat)
newdat$distance <- predict(fm1,newdat,re.form=NA)

pvar1 <- diag(mm %*% tcrossprod(vcov(fm1),mm))
tvar1 <- pvar1+VarCorr(fm1)$Subject[1]  
cmult <- 2 ## could use 1.96
newdat <- data.frame(
    newdat
    , plo = newdat$distance-cmult*sqrt(pvar1)
    , phi = newdat$distance+cmult*sqrt(pvar1)
    , tlo = newdat$distance-cmult*sqrt(tvar1)
    , thi = newdat$distance+cmult*sqrt(tvar1)
)

g0 <- ggplot(newdat, aes(x=age, y=distance, colour=Sex))+geom_point()
g0 + geom_errorbar(aes(ymin = plo, ymax = phi))+
labs(title="CI based on fixed-effects uncertainty ONLY") + theme_bw()

I'm also unsure why sqrt() is used in this line of code:

plo = newdat$distance-cmult*sqrt(pvar1) 

Thanks

@aosmith is right - scale_color_grey is probably what you're looking for.

g0 <- ggplot(newdat, aes(x=age, y=distance, colour=Sex))+geom_point()
g0 + geom_errorbar(aes(ymin = plo, ymax = phi)) +
labs(title="CI based on fixed-effects uncertainty ONLY") + 
theme_bw() + scale_color_grey(start = 0.2, end = 0.5)

If you're able to (which you are here), it's generally best to use redundant encoding, ie, encoding sex with two variables (such as color and linetype). It makes it easier to perceive the difference between the two.

g0 <- ggplot(newdat, aes(x=age, y=distance, colour=Sex, linetype = Sex)) + geom_point()
g0 + geom_errorbar(aes(ymin = plo, ymax = phi)) +
labs(title="CI based on fixed-effects uncertainty ONLY") + 
theme_bw() + scale_color_grey(start = 0.2, end = 0.5) + scale_linetype()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM