2017-09-05 99 views
1

我正在努力如何將個人和組趨勢線添加到我的圖中。 (R和使用ggplot2)。R:將組和單個多項式趨勢線添加到GMM圖中

這裏是我使用的代碼:

MensHG.fm2=lmer(HGNewtons~Temperature+QuadTemp+Run+(1|Subject),MenstrualData) #model 

plot.hg<-data.frame([email protected],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 

現在我希望把趨勢線的數據的G1部分(即整體趨勢)到我的每一個個別地塊的 - 什麼是最好的方法來做到這一點?我可以看到的趨勢,如果我使用的代碼:只要我做的小麪包裝

g5=g1+geom_smooth(method="glm", formula=y~poly(x,2), se=FALSE) 

​​

但是這個趨勢線disspears(我得到的輸出G3相同)

它不會出現通過使用來解決這個問題:G4 < -g3 + geom_smooth(數據= MensHG.fm2)

+0

的[如何放置在GGPLOT2對象的每個方面相同的流暢?(HTTPS可能重複: //stackoverflow.com/questions/6673074/how-do-i-place-an-identical-smooth-on-each-face-of-a-ggplot2-object) – aosmith

+0

代替'geom_smooth',使用'geom_line(aes (Temperature,fitted.re))'來生成連接所有擬合值的線。 – Brian

回答

1

沒有你的數據的最小工作示例中,我使用的內置虹膜數據。在這裏,我假裝物種爲了示範的目的是不同的主題。

library(lme4) 
library(ggplot2) 

fit.iris <- lmer(Sepal.Width ~ Sepal.Length + I(Sepal.Length^2) + (1|Species), data = iris) 

爲簡單起見,我還使用了兩個額外的軟件包,broomdplyraugment from broom做的和上面做的..., fitted.re=fitted(MensHG.fm2)一樣,但是有一些額外的花裏胡哨。我也使用dplyr::select,但這並非嚴格需要,取決於您所需的輸出(圖2與圖3之間的差異)。

library(broom) 
library(dplyr) 
augment(fit.iris) 
# output here truncated for simplicity 
Sepal.Width Sepal.Length I.Sepal.Length.2. Species .fitted  .resid .fixed ... 
1   3.5   5.1    26.01 setosa 3.501175 -0.001175181 2.756738 
2   3.0   4.9    24.01 setosa 3.371194 -0.371193601 2.626757 
3   3.2   4.7    22.09 setosa 3.230650 -0.030649983 2.486213 
4   3.1   4.6    21.16 setosa 3.156417 -0.056417409 2.411981 
5   3.6   5.0    25 setosa 3.437505 0.162495354 2.693068 
6   3.9   5.4    29.16 setosa 3.676344 0.223656271 2.931907 
ggplot(augment(fit.iris), 
     aes(Sepal.Length, Sepal.Width)) + 
    geom_line(#data = augment(fit.iris) %>% select(-Species), 
      aes(y = .fixed, color = "population"), size = 2) + 
    geom_line(aes(y = .fitted, color = "subject", group = Species), size = 2) + 
    geom_point() + 
    #facet_wrap(~Species, ncol = 2) + 
    theme(legend.position = c(0.75,0.25)) 

注意,我# -commented兩個語句:data = ...facet_wrap(...)。有了這些行註釋掉,你會得到一個輸出這樣的:

enter image description here

你必須在整個範圍內的人口光滑(.fixed爲固定效應),然後你有一羣平滑,顯示擬合模型值(.fitted),考慮到學科級別的攔截。

然後你就可以通過取出第二# -comment標記的代碼片段在顯示方面是:

enter image description here

這是相同的,但由於擬合值只的範圍內,存在每個主題級別面板的原始數據,總體平滑度被截斷到該範圍。

要解決這個問題,我們可以刪除第一# -comment標記:

enter image description here