绘制乘以k的拟合线性回归

时间:2020-09-11 06:07:24

标签: r

绘制简单的线性回归具有代码

plot(X,Y, pch=16)

其中Y_i = b_0 + b_1X_i且拟合线为

abline(lm(Y~X))

如果X乘以k,那么拟合值Y_hat的代码是什么? 会

abline(k*lm(Y~X))

因为k * Y_hat = k * b_0 + k * b_1 * X_i?

1 个答案:

答案 0 :(得分:0)

那样就不能直接工作,因为您不能将"lm"对象与某些对象相乘。但是,您可以使用stats:::plot.lm method,截距和斜率并绘制(有序的)拟合值,以不同的方式绘制回归线。

## baseline regression
(fit0 <- lm(y ~ x, d))$coe
# (Intercept)           x 
#    1.111633    3.427159 

op <- par(mfrow=c(1, 3))  ## set pars

plot(y ~ x, d, main="line.fit")
abline(fit0)  ## line by stats:::plot.lm method

plot(y ~ x, d, main="line.coef")
abline(a=fit0$coefficients[1], b=fit0$coefficients[2])  ## intercept and slope

plot(y ~ x, d, main="line.fitted")
lines(sort(d$x), fit0$fitted.values[order(d$x)])  ## (ordered) fitted values

enter image description here

现在,让我们将示例数据的x(见下文)乘以k得到xk

k <- 1e5
d <- transform(d, xk=x * k)
(fit.k <- lm(y ~ xk, d))$coe
#  (Intercept)           xk 
# 1.111633e+00 3.427159e-05 

我们只能看到与fit0相比的斜率变化,它被k 。截距保持不变。因此,我们将此见识应用于我们的绘图方法。

plot(y ~ xk, d, main="line.fit");abline(fit.k)

plot(y ~ xk, d, main="line.coef")
abline(a=fit.k$coefficients[1], b=fit.k$coefficients[2], col="black")
abline(a=fit0$coefficients[1], b=fit0$coefficients[2]/k, lty=2, col="red")

plot(y ~ xk, d, main="line.fitted");lines(sort(d$xk), fit0$fitted.values[order(d$x)])

par(op)  ## reset pars

enter image description here

中间的图表明fit.k的拟合线与我们将fit0的截距乘以k的线重合。


示例数据:

set.seed(42)
d <- data.frame(x=rnorm(1e2))
d <- transform(d, y=1.2 + 3.4*x + rnorm(1e2))