2

Perhaps this will be quick for some of you but I would like to represent the standard error of the regression using plot().

So, if I have a data like this:

x1 <- 1:500
b0 <- 17 
b1 <- 0.5 
sigma <- 7 
er <- rnorm(x1,0,sigma)
y <- b0 + b1*x1 + er 

model1 <- lm(y~x1)
plot(x1,y)
abline(model1,col="red",lwd=5)

afadassaf

How could I represent the standard error, in lines, for that regression?

Thanks in advance!

1
  • 4
    I suggest you plot the confidence band: lines(x1[order(x1)], predict(model1, interval = "confidence")[, "lwr"][order(x1)]); lines(x1[order(x1)], predict(model1, interval = "confidence")[, "upr"][order(x1)]) Commented Jan 23, 2020 at 14:27

2 Answers 2

1

You may want to use ggplot() instead of plot(). You have a slightly more modern layout and much more possibilities.

Add the following code after your example code. For better visibility I have changed the original data a bit (See line: y <- b0 + b1*x1 + er*5.)

# ------ test case ggplot ----------------
library (ggplot2)
# --- change some data fields ------------
y <- b0 + b1*x1 + er*5

df <- data.frame(y,x1)

ggplot(data = df, aes(x1,y)) +
geom_point() +
geom_smooth(method="lm", color="red", fill = "blue")

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

0

You can do it manually calculating the regression without the error and from that put the general lines of the sd() of all the residual errors:

x1 <- 1:500
b0 <- 17 
b1 <- 0.5 
sigma <- 7 
er <- rnorm(x1,0,sigma)
y <- b0 + b1*x1 + er 


GeneralStandardDev<-sd(model1$residuals)
UpperLine<- model1$coefficients[1]+model1$coefficients[2]*x1 + GeneralStandardDev
LowerLine<- model1$coefficients[1]+model1$coefficients[2]*x1 - GeneralStandardDev


model1 <- lm(y~x1)
plot(x1,y)
abline(model1,col="red",lwd=5)
lines(x1, UpperLine, col = "blue")
lines(x1, LowerLine, col = "blue")

enter image description here

3 Comments

I'm sorry but your calculation is not calculating "the standard error of the regression" (whatever the OP means by that).
What is then for you the standard error of the regression ? Then I might be wrong about the meaning of "the standard error of the regression".
I don't know what OP means by that. But you are not calculating a standard error. Use predict(model1, se.fit = TRUE) if you want to calculate the standard error of predictions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.