How to 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

Leave a Reply

Your email address will not be published.