Home Â» How to Add a Vertical Line to a Plot Using ggplot2

# How to Add a Vertical Line to a Plot Using ggplot2

You can quickly add vertical lines to ggplot2 plots using the geom_vline() function, which uses the following syntax:

geom_vline(xintercept, linetype, color, size)

where:

• xintercept: Location to add line on the x-intercept. This can be one value or multiple values.
• linetype: Line style. Default is â€˜solidâ€™ but you can specify â€˜twodashâ€™, â€˜longdashâ€™, â€˜dottedâ€™, â€˜dotdashâ€™, â€˜dashedâ€™, or â€˜blank.â€™
• color: Color of the line.
• size: Width of the line.

The following examples show how to use this function in practice.

## Add a Single Vertical Line to a Plot

The following code shows how to add a single vertical line to a plot:

```library(ggplot2)

#create data frame
df #create scatterplot with vertical line at x=10
ggplot(df, aes(x=x, y=y)) +
geom_point() +
geom_vline(xintercept=10)
```

## Add Multiple Vertical Lines to Plots

The following code shows how to add multiple vertical lines to a plot:

```library(ggplot2)

#create data frame
df #create scatterplot with vertical line at x=6, 10, and 11
ggplot(df, aes(x=x, y=y)) +
geom_point() +
geom_vline(xintercept=c(6, 10, 11))```

## Customize Vertical Lines

The following code shows how to customize vertical lines on a plot:

```library(ggplot2)

#create data frame
df #create scatterplot with customized vertical line
ggplot(df, aes(x=x, y=y)) +
geom_point() +
geom_vline(xintercept=5, linetype='dashed', color='blue', size=2)```

If you have multiple vertical lines on one chart, you can specify a unique color for each line:

```library(ggplot2)

#create data frame
df #create scatterplot with customized vertical lines
ggplot(df, aes(x=x, y=y)) +
geom_point() +
geom_vline(xintercept=c(5, 7), linetype='dashed', color=c('blue', 'red'))```