0

我想知道如何使用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) 

在此处输入图像描述

我对使用broomand重现这个很感兴趣ggplot2,到目前为止我只实现了这个:

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

在此处输入图像描述

augment函数不计算conf.int。任何线索我可以添加一些smooth信心倒数?

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

2 回答 2

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=ygeom_point()是因为你不能对geom_ribbon.

在此处输入图像描述

于 2016-11-10T17:13:41.730 回答
0

只需执行此操作(使用您的原始数据集 dat):

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

在此处输入图像描述

于 2016-11-10T20:26:06.487 回答