How can I create smooth lines in ggplot2?

Creating smooth lines in ggplot2 involves utilizing the “geom_smooth” function, which allows for the creation of a smooth curve to represent the relationship between two variables in a plot. This function fits a statistical model to the data and produces a smoothed line, providing a clearer understanding of the overall trend in the data. The smoothness of the line can be adjusted by specifying the “method” argument, which allows for the use of different smoothing techniques such as “loess” or “gam”. Additionally, the “se” argument can be used to add confidence intervals to the curve, providing a measure of uncertainty in the smooth line. By incorporating these features, ggplot2 allows for the creation of visually appealing and informative plots with smooth lines.

Create Smooth Lines in ggplot2 (With Examples)


You can plot a smooth line in ggplot2 by using the geom_smooth() function, which uses the following basic syntax:

ggplot(df, aes(x=x, y=y)) +
  geom_smooth()

This tutorial shows several examples of how to use this function in practice.

Example: Create Smooth Lines in ggplot2

Suppose we have the following data frame:

df <- data.frame(x=c(1, 2, 4, 5, 7, 9, 13, 14, 15, 17, 18, 20),
                 y=c(34, 35, 36, 23, 37, 38, 49, 45, 48, 51, 53, 55))

We can use the following code to create a scatterplot of the values in the data frame and add a smooth line to capture the trend:

library(ggplot2)

ggplot(df, aes(x=x, y=y)) +
  geom_point() +
  geom_smooth()

Smooth line ggplot2

By default, the geom_smooth() function uses a loess method to fit the line to the dataset, but we can specify a different method such as lm to fit a straight line to the dataset instead:

ggplot(df, aes(x=x, y=y)) +
  geom_point() +
  geom_smooth(method='lm')

Smooth line in R

We can also hide the standard error bands by specifying se=FALSE:

ggplot(df, aes(x=x, y=y)) +
  geom_point() +
  geom_smooth(method='lm', se=FALSE)

Smooth line in ggplot2

You can also quickly change the size and color of the line by using the size and col arguments:

ggplot(df, aes(x=x, y=y)) +
  geom_point() +
  geom_smooth(method='lm', se=FALSE, col='red', size=2)

Custom smooth line in R with ggplot2

You can find the complete documentation for the geom_smooth() function here.

Additional Resources

How to Plot a Linear Regression Line in ggplot2
How to Add a Vertical Line to a Plot Using ggplot2
How to Create Side-by-Side Plots in ggplot2

x