Adding linear model lines

In this recipe we will learn how to fit a linear model and plot the linear regression line on a scatter plot.

Getting ready

All you need for the next recipe is to type it at the R prompt as we will only use some base functions. You may also save the recipe code as a script so that you can use it again later on.

How to do it...

Once again, let's use the mtcars dataset and draw a linear fit line for mpg versus disp:

plot(mtcars$mpg~mtcars$disp)
lmfit<-lm(mtcars$mpg~mtcars$disp)
abline(lmfit)
How to do it...

How it works...

We first draw the basic scatter plot of mpg versus disp. Then we fit a linear model to the data using the lm() function, which takes a formula in the form y~x as its argument. Finally, we pass the linear fit to the abline() function, which reads the intercept and slope saved in the lmfit object to draw a line.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset