2016-11-10 108 views
0

我在想如何使用broom包來計算置信區間。R - 整齊增強置信區間

我所試圖做的是簡單的標準:

set.seed(1) 
x <- runif(50) 
y <- 2.5 + (3 * x) + rnorm(50, mean = 2.5, sd = 2) 
dat <- data.frame(x = x, y = y) 
mod <- lm(y ~ x, data = dat) 

使用visreg我可以積迴歸模型CI很簡單地:

library(visreg) 
visreg(mod, 'x', overlay=TRUE) 

enter image description here

我有意思在使用broomggplot2再現這一點,到目前爲止,我只能實現編輯本:

library(broom) 

dt = lm(y ~ x, data = dat) %>% augment(conf.int = TRUE) 
ggplot(data = dt, aes(x, y, colour = y)) + 
    geom_point() + geom_line(data = dt, aes(x, .fitted, colour = .fitted)) 

enter image description here

augment功能可按不計算conf.int。任何線索我如何可以添加一些smooth信心invervals?

geom_smooth(data=dt, aes(x, y, ymin=lcl, ymax=ucl), size = 1.5, 
     colour = "red", se = TRUE, stat = "smooth") 
+1

爲什麼你不使用'geom_smooth(方法= 「LM」)'用原來的數據框添加CI的迴歸線? –

+0

原因是我需要添加許多不同的線條和做更復雜的東西,所以我想知道是否有一個簡單的方法來繪製'掃帚'。 'geom_smooth(method =「lm」)'當你有很多變量並且你想控制哪一行被繪製時,它會變得複雜嗎? – giacomo

回答

6

使用broom輸出,你可以做這樣的事情:

ggplot(data = dt, aes(x, y)) + 
    geom_ribbon(aes(ymin=.fitted-1.96*.se.fit, ymax=.fitted+1.96*.se.fit), alpha=0.2) + 
    geom_point(aes(colour = y)) + 
    geom_line(aes(x, .fitted, colour = .fitted)) + 
    theme_bw() 

我感動colour=ygeom_point(),因爲你不能在彩色審美適用於geom_ribbon

enter image description here

0

只是這樣做(與你的原始數據集DAT):

ggplot(data = dat, aes(x, y, colour = y)) + 
    geom_point(size=2) + geom_smooth(method='lm', se = TRUE) + theme_bw() 

enter image description here

+0

如果您正在運行多變量回歸併且只想顯示一個變量,該怎麼辦? – giacomo

+0

@giacomoV不知道我是否得到了你,我想你是在談論多元迴歸(而不是多元迴歸的權利),其中你有多個預測因子,例如,另一個預測變量x1,s.t. y〜x + x1,但在這種情況下,可視化應該是一個平面而不是一條直線,您需要三維可視化來顯示迴歸平面和飛機周圍的密度區間體積,對嗎? –

+0

二維我想我們只會有興趣只顯示響應和單個預測變量之間的關係,保持其他變量不變。 –