R print equation of linear regression on the plot itself

前端 未结 2 808
难免孤独
难免孤独 2020-12-03 08:20

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         


        
2条回答
  •  没有蜡笔的小新
    2020-12-03 08:59

    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)
    

    enter image description here

    Hope it helps,

    alex

提交回复
热议问题