我正在尝试使用回归线输出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()运行它时才会出现问题。
答案 0 :(得分:2)
首先,你真的应该避免使用attach
。对于具有data=
参数的函数(例如plot
和lm
),使用该参数而不是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")
你得到了第二个回归线,因为你在abline()
之前为第二次回归调用了plot()
,这条线是在第一个图上绘制的。
答案 1 :(得分:0)
这是你的代码清理了一下。您正在对abline
进行冗余调用,这些调用正在绘制额外的行。
顺便说一句,使用attach
时无需使用with
。 with
基本上是一个临时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")
}
)