Site icon R-bloggers

ggplot Fit Line and Lattice Fit Line in R

[This article was first published on Mollie's Research Blog, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Let’s add a fit line to a scatterplot!

Fit Line in Base Graphics

Here’s how to do it in base graphics:
< !-- HTML generated using hilite.me -->
ols <- lm(Temp ~ Solar.R,
  data = airquality)

summary(ols)

plot(Temp ~ Solar.R,
  data = airquality)
abline(ols)

Fit line in base graphics in R



Fit Line in ggplot

And here’s how to do it in ggplot:
< !-- HTML generated using hilite.me -->
library(ggplot2)
ggplot(data = airquality,
    aes(Solar.R, Temp)) + 
  geom_point(pch = 19) + 
  geom_abline(intercept = ols$coefficients[1],
    slope = ols$coefficients[2])

You can access the info from your regression results through ols$coefficients.
Fit line in ggplot in R

Fit Line in Lattice

In lattice, it’s even easier. You don’t even need to run a regression; you can just add to the type option.

< !-- HTML generated using hilite.me -->
library(lattice)

xyplot(Temp ~ Solar.R,
  data = airquality,
  type = c("p", "r"))

Fit Line in Lattice in R
The code is available in a gist.

References


To leave a comment for the author, please follow the link and comment on their blog: Mollie's Research Blog.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.