简体   繁体   中英

Multiple Regression lines in R

I am trying to have output 2 different graphs with a regression line. 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. 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.

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.

在此处输入图片说明

First of all, you really should avoid using attach . And for functions that have data= parameters (like plot and lm ), its usually wiser to use that parameter rather than with() .

Also, abline() is a function that should be called after plot() . Putting it is a parameter to plot() doesn't really make any sense.

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.

Here is your code cleaned up a little. You were making redundant calls to abline that was drawing the extra lines.

By the way, you don't need to use attach when you use with . with is basically a temporary 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")
}
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM