[英]Multiple Regression lines in R
I am trying to have output 2 different graphs with a regression line. 我正在尝试使用回归线输出2个不同的图形。 I am using the mtcars data set which I believe you can load into R. So, I am comparing 2 different pairs of information to create a regression line.
我正在使用mtcars数据集,我相信您可以将其加载到R中。因此,我正在比较2对不同的信息对以创建回归线。 And the problem seems to be that the 2nd regression line from the 2nd graph is for some reason in the first graph as well.
问题似乎是由于某种原因,第二张图的第二条回归线也在第一张图中。
I just want it to show 1 regression line in each graph the way it should be. 我只希望它在每张图中以应有的方式显示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")
})
Also when I run the code separately for plotting, I don't see the black line. 另外,当我分别运行代码进行绘图时,看不到黑线。 Its only when I run it with the: with() it causes a problem.
只有当我使用:with()运行它时,它才会引起问题。
First of all, you really should avoid using attach
. 首先,您确实应该避免使用
attach
。 And for functions that have data=
parameters (like plot
and lm
), its usually wiser to use that parameter rather than with()
. 对于具有
data=
参数的函数(例如plot
和lm
),通常明智的做法是使用该参数而不是with()
。
Also, abline()
is a function that should be called after plot()
. 另外,
abline()
是应在plot()
之后调用的函数。 Putting it is a parameter to plot()
doesn't really make any sense. 将它作为
plot()
的参数并没有任何意义。
Here's a better arrangement of your code 这是您的代码的更好安排
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")
You got that second regression line because you were calling abline()
before plot()
for the second regression, do the line drew on the first plot. 你明白我的第二回归线,因为你调用
abline()
之前plot()
的第二个回归,做行吸取了第一条曲线。
Here is your code cleaned up a little. 这是您的代码整理了一下。 You were making redundant calls to
abline
that was drawing the extra lines. 您对多余的
abline
进行了多余的调用, abline
绘制了多余的线条。
By the way, you don't need to use attach
when you use with
. 顺便说一句,当
with
一起使用时,您不需要使用attach
。 with
is basically a temporary attach
. 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")
}
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.