Erdogan CEVHER Erdogan CEVHER - 17 days ago 6
R Question

Incorrect abline line for a regression model with intercept in R

(reproducible example given) In the following, I get an abline line with y-intercept is about 30, but the regression says y-intercept should be 37.2851 Where am I wrong?

mtcars$mpg # 21.0 21.0 22.8 ... 21.4 (32 obs)
mtcars$wt # 2.620 2.875 2.320 ... 2.780 (32 obs)
regression1 <- lm(mtcars$mpg ~ mtcars$wt)
coef(regression1) # mpg ~ 37.2851 - 5.3445wt
plot(mtcars$mpg ~ mtcars$wt, pch=19, col='gray50') # pch: shape of points
abline(h=mean(mtcars$mpg), lwd=2, col ='darkorange') # The y-coordinate of hor'l line: 20,09062
abline(lm(mtcars$mpg ~ mtcars$wt), lwd=2, col ='sienna')


enter image description here

I looked at all the similar abline problems in SOF. Still, I could not figure out what is wrong in the course.

Answer

Use

plot(mtcars$mpg ~ mtcars$wt, pch=19, col='gray50', xlim = c(0, 6), ylim = c(0, 40))

Note, your current code produces a plot with xlim not starting from 0. While to see the intercept, you need x = 0. Don't forget to set ylim as well to see a complete line.

enter image description here