rguides

How to Add Trend Lines to Scatter Plots in R

Add trend lines to scatter plots to reveal the direction and strength of relationships between variables. ggplot2::geom_smooth() handles this cleanly — it fits a model behind the scenes and draws the line over your points, with an optional confidence band that shows the uncertainty around the fit. A linear trend line works when the relationship between x and y is roughly proportional; a loess smooth fits a flexible local curve when the relationship bends across the range of x. The default confidence interval shade makes it immediately obvious whether the trend is real or driven by a few outliers.

library(ggplot2)

ggplot(mtcars, aes(x = wt, y = mpg)) +
  geom_point() +
  geom_smooth(method = "lm", se = TRUE)

Use method = "loess" for smoothed curves or se = FALSE to hide confidence intervals. For polynomial trends, specify a formula directly:

ggplot(mtcars, aes(x = wt, y = mpg)) +
  geom_point() +
  geom_smooth(method = "lm", formula = y ~ poly(x, 2))

With base R, use abline(lm(y ~ x), col = "red") after plot(). Loess is slow on large datasets — switch to method = "gam" from the mgcv package for faster smooth fitting in those cases.

See also