简体   繁体   English

R-整洁地增加置信区间

[英]R - tidy augment confidence interval

I am wondering how I can compute confidence interval using the broom package. 我想知道如何使用broom包计算置信区间。

What I am trying to do is simple and standard : 我正在尝试做的是简单和标准的:

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)

Using visreg I can plot regression models with CI very simply with : 使用visreg我可以使用CI非常简单地绘制回归模型:

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

在此处输入图片说明

I am interesting in reproducing this using broom and ggplot2 , so far I only achieved this : 在使用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)) 

在此处输入图片说明

The augment funciton doesn't compute conf.int . augment函数不计算conf.int Any clue how I can add some smooth confidence invervals ? 有什么线索可以添加smooth置信区间吗?

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

Using the broom output, you can do something like this: 使用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()

I moved colour=y into geom_point() because you can't apply a colour aesthetic to geom_ribbon . 我将colour=y移至geom_point()因为您无法将颜色美学应用于geom_ribbon

在此处输入图片说明

Just do this (with your original dataset dat): 只需执行此操作(使用原始数据集dat):

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

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM