R - 整理增强置信区间

时间:2016-11-10 17:02:35

标签: r ggplot2 broom

我想知道如何使用broom包计算置信区间。

我想做的是简单和标准:

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

2 个答案:

答案 0 :(得分:7)

使用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=y移至geom_point(),因为您无法将颜色美学应用于geom_ribbon

enter image description here

答案 1 :(得分: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