2016-07-27 111 views
0

我正在嘗試調整我的圖形,使其適用於科學報告。看下面的例子(從這裏:http://glmm.wikidot.com/faq)。在ggplot2中繪製lmer()

如何更改ggplot設置,使行以灰度顯示?

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() 

我也不清楚爲什麼開方()在這行代碼被用於:

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

感謝

+1

請參閱'scale_color_grey'作爲一個選項。您也可以考慮使用標準誤差(方差的平方根)計算映射到「線型」和/或「形狀」而不是「顏色」。 – aosmith

回答

1

@aosmith是正確的 - scale_color_grey可能是你在找什麼。

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) 

如果你能(你在這裏),它通常最好使用冗餘編碼,即用兩個變量(如顏色和線型)編碼性。它更容易察覺兩者之間的差異。

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() 
+0

謝謝,這個工作!我花了一段時間纔得到了scale_linetype()的工作,但它做出了很大的改變! –