Incorrect abline line for a regression model with intercept in R

China☆狼群 提交于 2019-12-02 12:11:19

问题


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

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


回答1:


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.



来源:https://stackoverflow.com/questions/40704492/incorrect-abline-line-for-a-regression-model-with-intercept-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!