R print equation of linear regression on the plot itself

前端 未结 2 802
难免孤独
难免孤独 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:57

    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")
    }
    

    enter image description here

提交回复
热议问题