ggplot Fit Line and Lattice Fit Line in R

February 13, 2014

(This article was first published on Mollie's Research Blog, and kindly contributed to R-bloggers)

Let’s add a fit line to a scatterplot!

Fit Line in Base Graphics

Here’s how to do it in base graphics:

ols <- lm(Temp ~ Solar.R,
data = airquality)


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

Fit line in base graphics in R

Fit Line in ggplot

And here’s how to do it in ggplot:

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.


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

Fit Line in Lattice in R

The code is available in a gist.


To leave a comment for the author, please follow the link and comment on their blog: Mollie's Research Blog. offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...

If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.

Search R-bloggers


Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)