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 likeaes(x, y).method: smoothing method, e.g.,"loess"(default for small data) or"lm"for linear model.se: logical, whether to display confidence interval (defaultTRUE).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
methodwhen data is large, causing slow LOESS computation. - Forgetting to set
se = FALSEif you don't want the confidence band. - Using
geom_smooth()withoutaes()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
| Parameter | Description | Default |
|---|---|---|
| mapping | Aesthetic mappings like x and y | Required |
| method | Smoothing method: "loess", "lm", etc. | "loess" for small data |
| se | Show confidence interval band | TRUE |
| formula | Model formula, e.g. y ~ x | Depends on method |
| color | Line color | ggplot default |
| fill | Confidence band fill color | ggplot 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.