R 在图本身上打印线性回归方程

标签 r regression

我们如何在绘图上打印一条线的方程?

我有 2 个自变量,想要一个这样的方程:

y=mx1+bx2+c

where x1=cost, x2 =targeting

我可以绘制最佳拟合线,但如何在图中打印方程?

也许我不能在一个方程中打印 2 个自变量,但我该怎么做呢?y=mx1+c至少?

这是我的代码:
fit=lm(Signups ~ cost + targeting)
plot(cost, Signups, xlab="cost", ylab="Signups", main="Signups")
abline(lm(Signups ~ cost))

最佳答案

我试图使输出自动化一点:

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

希望能帮助到你,

亚历克斯

关于R 在图本身上打印线性回归方程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24173468/

相关文章:

R data.table 聚合数据

r - 制作 dplyr 过程的自定义函数

r - 省略列表中所有 data.frames 中不共享公共(public) ID 的行

python - pybrain NNregression工具参数

python - pytorch 如何计算简单线性回归模型的梯度?

r - corAR1 上 gls 的 r 错误 - 不是唯一的

r - 使用 dplyr 中的过滤条件改变每组的最小日期

regression - C\C++ 中的 LIBLINEAR

machine-learning - 为什么根据(或作为函数)鲑鱼的年龄和重量来预测鲑鱼的长度是一个回归问题?

R中的回归子集算法