本文介绍了绘制lm对象的95%置信区间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何为r中的回归计算和绘制置信区间?到目前为止,我有两个长度相等的数值向量(x,y)和一个回归对象(lm.out).给定x,我已经制作了y的散点图,并将回归线添加到该图中.我正在寻找一种将lm.out的95%预测置信带添加到绘图中的方法.我已经尝试过使用预测函数,但是我什至不知道从哪里开始:/.这是我目前的代码:

How can I calculate and plot a confidence interval for my regression in r? So far I have two numerical vectors of equal length (x,y) and a regression object(lm.out). I have made a scatterplot of y given x and added the regression line to this plot. I am looking for a way to add a 95% prediction confidence band for lm.out to the plot. I've tried using the predict function, but I don't even know where to start with that :/. Here is my code at the moment:

x=c(1,2,3,4,5,6,7,8,9,0)
y=c(13,28,43,35,96,84,101,110,108,13)

lm.out <- lm(y ~ x)

plot(x,y)

regression.data = summary(lm.out) #save regression summary as variable
names(regression.data) #get names so we can index this data
a= regression.data$coefficients["(Intercept)","Estimate"] #grab values
b= regression.data$coefficients["x","Estimate"]
abline(a,b) #add the regression line

谢谢!

我已经研究了建议的重复项,但不能完全了解其底部.

I've taken a look at the proposed duplicate and can't quite get to the bottom of it.

推荐答案

您可以使用预测来预测新的数据矢量,此处为newx.

You have yo use predict for a new vector of data, here newx.

x=c(1,2,3,4,5,6,7,8,9,0)

y=c(13,28,43,35,96,84,101,110,108,13)

lm.out <- lm(y ~ x)
newx = seq(min(x),max(x),by = 0.05)
conf_interval <- predict(lm.out, newdata=data.frame(x=newx), interval="confidence",
                         level = 0.95)
plot(x, y, xlab="x", ylab="y", main="Regression")
abline(lm.out, col="lightblue")
lines(newx, conf_interval[,2], col="blue", lty=2)
lines(newx, conf_interval[,3], col="blue", lty=2)

编辑

正如Ben在评论中提到的那样,可以使用matlines来完成此操作,如下所示:

EDIT

as it is mention in the coments by Ben this can be done with matlines as follow:

plot(x, y, xlab="x", ylab="y", main="Regression")
abline(lm.out, col="lightblue")
matlines(newx, conf_interval[,2:3], col = "blue", lty=2)

这篇关于绘制lm对象的95%置信区间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 23:52