R 中的多重回归线

Multiple Regression lines in R

我正在尝试用回归线输出 2 个不同的图表。我正在使用 mtcars 数据集,我相信您可以将其加载到 R 中。因此,我正在比较 2 对不同的信息以创建回归线。问题似乎是第二张图中的第二条回归线出于某种原因也在第一张图中。

我只想让它在每个图表中按应有的方式显示 1 条回归线。

mtcars
names(mtcars)
attach(mtcars)    

par(mfrow=c(1,2), bg="white")
with(mtcars,
{

regrline=(lm(gear~mpg))
abline(regrline)
plot(mpg,gear,abline(regrline, col="red"),main="MPG vs Gear")

# The black line in the first graph is the regression line(blue) from the second graph

regrline=(lm(cyl~disp))
abline(regrline)
plot(disp,cyl,abline(regrline, col="blue"),main="Displacement vs Number of Cylinder")

})

另外,当我运行单独绘制代码时,我没有看到黑线。只有当我 运行 它与: with() 时才会导致问题。

首先,你真的应该避免使用attach。对于具有 data= 参数的函数(如 plotlm),使用该参数通常比使用 with().

更明智

此外,abline() 是一个函数,应该在 plot() 之后调用。将其作为 plot() 的参数并没有任何意义。

这里是你的代码的一个更好的安排

par(mfrow=c(1,2), bg="white")

regrline=lm(gear~mpg, mtcars)
plot(gear~mpg,mtcars,main="MPG vs Gear")
abline(regrline, col="red")

regrline=lm(cyl~disp, mtcars)
plot(cyl~disp,mtcars,main="Displacement vs Number of Cylinder")
abline(regrline, col="blue")

你得到第二条回归线是因为你在 plot() 之前调用 abline() 进行第二次回归,在第一个图上画线。

这是您稍微清理过的代码。您正在对 abline 进行冗余调用,这会绘制额外的线条。

顺便说一句,你用with的时候不需要用attachwith 基本上是临时 attach.

par(mfrow=c(1,2), bg="white")
with(mtcars,
{
    regrline=(lm(gear~mpg))
    plot(mpg,gear,main="MPG vs Gear")
    abline(regrline, col="red")

    regrline=(lm(cyl~disp))
    plot(disp,cyl,main="Displacement vs Number of Cylinder")
    abline(regrline, col="blue")
}
)