2017-09-05 114 views
0

我有一個看起來像這樣的數據:如何繪製R中lmer迴歸模型的估計值?

height <- c(1,2,3,4,2,4,6,8) 
weight <- c(12,13,14,15,22,23,24,25) 
type <- c("Wheat","Wheat","Wheat","Wheat","Rice","Rice","Rice","Rice") 
set <- c(1,1,1,1,2,2,2,2) 
dat <- data.frame(set,type,height,weight) 

我運行集11聚物模型作爲R中隨機效應:

mod <- lmer(weight~height + type + (1|set), data = dat) 

現在,我要繪製的模型的估計和在x軸和高度在y軸上繪製迴歸,具有重量,小刻面(〜型)

我使用預測函數如下

dat$pred <- predict(mod, type = "response") 

我想達到ggplot,將是這樣的:

ggplot(dat,aes(x = weight, y = height)) + 
geom_point() + geom_smooth(method="lm", fill=NA) + facet_grid(~ type, scales = "free") 

然而,我注意到,預測函數只具有單一的輸出。我如何繪製以實現與上述相同?或者我必須存儲兩個不同的預測響應,然後將其插入ggplot的x,y?

回答

1

我能適應你的情節,顯示原材料與預測這樣的價值觀:

ggplot(dat,aes(y = height)) + 
    geom_point(aes(x = weight)) + 
    geom_line(aes(x = pred)) + 
    facet_grid(~ type, scales = "free") 

在您的例子情節雖然你有weight,模型中的結果變量,在x軸,這是混亂。通常情況下,您將在y軸上獲得結果/預測變量,所以我會繪製您的模型預測:

ggplot(dat,aes(x = height)) + 
    geom_point(aes(y = weight)) + 
    geom_line(aes(y = pred)) + 
    facet_grid(~ type, scales = "free")