Table of Contents
To add straight lines to a ggplot2 plot, the geom_abline() function can be used. This function takes in several parameters such as the intercept, slope, and color of the desired line to be added. It is also possible to add multiple lines to the plot by simply repeating the geom_abline() function with different parameters.
You can use the geom_abline() function and other similar geom functions to add straight lines to plots in ggplot2.
Here are the most common ways to use these functions:
Method 1: Use geom_abline() to Add Line with Slope and Intercept
ggplot(df, aes(x, y)) +
geom_point() +
geom_abline(slope=3, intercept=15)
Method 2: Use geom_vline() to Add Vertical Line
ggplot(df, aes(x=xvar, y=yvar)) +
geom_point() +
geom_vline(xintercept=5)
Method 3: Use geom_hline() to Add Horizontal Line
ggplot(df, aes(x=xvar, y=yvar)) +
geom_point() +
geom_hline(yintercept=25)
Method 4: Use geom_smooth() to Add Regression Line
ggplot(df, aes(x=xvar, y=yvar)) +
geom_point() +
geom_smooth(method='lm')
The following examples show how to use each of these methods in practice with the following data frame in R:
#create data frame df <- data.frame(x=c(1, 2, 3, 3, 5, 7, 9), y=c(8, 14, 18, 25, 29, 33, 25)) #view data frame df x y 1 1 8 2 2 14 3 3 18 4 3 25 5 5 29 6 7 33 7 9 25
Example 1: Use geom_abline() to Add Line with Slope and Intercept
The following code shows how to use geom_abline() to add a straight line to a scatterplot with a slope of 3 and an intercept of 15:
library(ggplot2) #create scatterplot and add straight line with specific slope and intercept ggplot(df, aes(x=x, y=y)) + geom_point() + geom_abline(slope=3, intercept=15)
Example 2: Use geom_vline() to Add Vertical Line
library(ggplot2) #create scatterplot and add vertical line at x=5 ggplot(df, aes(x=x, y=y)) + geom_point() + geom_vline(xintercept=5)
Example 3: Use geom_hline() to Add Horizontal Line
The following code shows how to use geom_hline() to add a horizontal line to a scatterplot at y=25:
library(ggplot2) #create scatterplot and add horizontal line at y=25 ggplot(df, aes(x=x, y=y)) + geom_point() + geom_hline(yintercept=25)
Example 4: Use geom_smooth() to Add Regression Line
The following code shows how to use geom_smooth() to add a fitted regression line to a scatterplot:
library(ggplot2) #create scatterplot and add fitted regression line ggplot(df, aes(x=x, y=y)) + geom_point() + geom_smooth(method='lm', se=FALSE)
Note: The argument se=FALSE tells ggplot2 not to display shaded lines for standard error estimates.
The following tutorials explain how to perform other commonly used operations in ggplot2: