0
0
R-programmingHow-ToBeginner ยท 3 min read

How to Use geom_smooth in ggplot2 for Trend Lines

Use geom_smooth() in ggplot2 to add a smooth trend line or curve to your plot. It fits a model like LOESS or linear regression by default and shows confidence intervals. Simply add geom_smooth() to your ggplot object with optional parameters to customize the smoothing method and appearance.
๐Ÿ“

Syntax

The basic syntax of geom_smooth() is:

  • mapping: aesthetic mappings like aes(x, y).
  • method: smoothing method, e.g., "loess" (default for small data) or "lm" for linear model.
  • se: logical, whether to display confidence interval (default TRUE).
  • formula: formula for the model, e.g., y ~ x.
  • color, fill: colors for line and confidence band.

Example syntax:

geom_smooth(mapping = aes(x, y), method = "loess", se = TRUE)
r
geom_smooth(mapping = aes(x, y), method = "loess", se = TRUE)
๐Ÿ’ป

Example

This example shows how to add a smooth trend line to a scatter plot of mpg dataset with geom_smooth(). It uses the default LOESS method and shows the confidence interval.

r
library(ggplot2)

# Scatter plot with smooth trend line
p <- ggplot(mpg, aes(x = displ, y = hwy)) +
  geom_point() +
  geom_smooth() +
  labs(title = "Engine Displacement vs Highway MPG with Smooth Line")

print(p)
Output
[A scatter plot with points and a smooth curve with shaded confidence band]
โš ๏ธ

Common Pitfalls

Common mistakes when using geom_smooth() include:

  • Not specifying method when data is large, causing slow LOESS computation.
  • Forgetting to set se = FALSE if you don't want the confidence band.
  • Using geom_smooth() without aes() mappings, which can cause errors.
  • Passing incorrect formula syntax for custom models.

Example of wrong and right usage:

r
# Wrong: No aes mapping
# geom_smooth() # may cause error if no x and y defined

# Right: Proper aes mapping and method
geom_smooth(aes(x = displ, y = hwy), method = "lm", se = FALSE)
๐Ÿ“Š

Quick Reference

ParameterDescriptionDefault
mappingAesthetic mappings like x and yRequired
methodSmoothing method: "loess", "lm", etc."loess" for small data
seShow confidence interval bandTRUE
formulaModel formula, e.g. y ~ xDepends on method
colorLine colorggplot default
fillConfidence band fill colorggplot default
โœ…

Key Takeaways

Add smooth trend lines easily with geom_smooth() in ggplot2.
Specify method like "lm" for linear or "loess" for local smoothing.
Use se = FALSE to hide confidence intervals if not needed.
Always map x and y aesthetics inside aes() for geom_smooth().
Large datasets may require method = "lm" for faster smoothing.