R print equation of linear regression on the plot itself

与世无争的帅哥 提交于 2019-11-27 16:28:02

问题


How do we print the equation of a line on a plot?

I have 2 independent variables and would like an equation like this:

y=mx1+bx2+c

where x1=cost, x2 =targeting

I can plot the best fit line but how do i print the equation on the plot?

Maybe i cant print the 2 independent variables in one equation but how do i do it for say y=mx1+c at least?

Here is my code:

fit=lm(Signups ~ cost + targeting)
plot(cost, Signups, xlab="cost", ylab="Signups", main="Signups")
abline(lm(Signups ~ cost))

回答1:


I tried to automate the output a bit:

fit <- lm(mpg ~ cyl + hp, data = mtcars)
summary(fit)
##Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept) 36.90833    2.19080  16.847  < 2e-16 ***
## cyl         -2.26469    0.57589  -3.933  0.00048 ***
## hp          -0.01912    0.01500  -1.275  0.21253 


plot(mpg ~ cyl, data = mtcars, xlab = "Cylinders", ylab = "Miles per gallon")
abline(coef(fit)[1:2])

## rounded coefficients for better output
cf <- round(coef(fit), 2) 

## sign check to avoid having plus followed by minus for negative coefficients
eq <- paste0("mpg = ", cf[1],
             ifelse(sign(cf[2])==1, " + ", " - "), abs(cf[2]), " cyl ",
             ifelse(sign(cf[3])==1, " + ", " - "), abs(cf[3]), " hp")

## printing of the equation
mtext(eq, 3, line=-2)

Hope it helps,

alex




回答2:


You use ?text. In addition, you should not use abline(lm(Signups ~ cost)), as this is a different model (see my answer on CV here: Is there a difference between 'controling for' and 'ignoring' other variables in multiple regression). At any rate, consider:

set.seed(1)
Signups   <- rnorm(20)
cost      <- rnorm(20)
targeting <- rnorm(20)
fit       <- lm(Signups ~ cost + targeting)

summary(fit)
# ...
# Coefficients:
#             Estimate Std. Error t value Pr(>|t|)
# (Intercept)   0.1494     0.2072   0.721    0.481
# cost         -0.1516     0.2504  -0.605    0.553
# targeting     0.2894     0.2695   1.074    0.298
# ...

windows();{
  plot(cost, Signups, xlab="cost", ylab="Signups", main="Signups")
  abline(coef(fit)[1:2])
  text(-2, -2, adj=c(0,0), labels="Signups = .15 -.15cost + .29targeting")
}



来源:https://stackoverflow.com/questions/24173468/r-print-equation-of-linear-regression-on-the-plot-itself

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