The abline() function in R can be used to add a straight line to a plot in R.
To add a label to an abline, you can use the text() function with the following basic syntax:
text(x, y, ‘my label’)
where:
- x, y: The (x, y) coordinates where the label should be placed.
The following examples show how to use the text() function to add a label to a horizontal abline and vertical abline.
Example 1: Add Label to Horizontal abline in R
The following code shows how to create a scatterplot with a horizontal line at y=20 and a label:
#create data frame
df <- data.frame(x=c(1, 1, 2, 3, 4, 4, 7, 7, 8, 9),
y=c(13, 14, 17, 12, 23, 24, 25, 28, 32, 33))
#create scatterplot of x vs. y
plot(df$x, df$y, pch=19)
#add horizontal line at y=20
abline(h=20)
#add label to horizontal line
text(x=2, y=20.5, 'This is a label')
Notice that a label has been added just above the horizontal abline in the plot.
Also note that you can use the col and cex arguments in the text() function to modify the color and size of the label, respectively:
#create data frame
df <- data.frame(x=c(1, 1, 2, 3, 4, 4, 7, 7, 8, 9),
y=c(13, 14, 17, 12, 23, 24, 25, 28, 32, 33))
#create scatterplot of x vs. y
plot(df$x, df$y, pch=19)
#add horizontal line at y=20
abline(h=20)
#add label to horizontal line (with blue color and double the font size)
text(x=3, y=20.7, 'This is a label', col='blue', cex=2)
Notice that the label is now blue and the font size is twice as large as the previous example.
Related: How to Use cex to Change the Size of Plot Elements in R
Example 2: Add Label to Vertical abline in R
The following code shows how to create a scatterplot with a horizontal line at y=20 and a label:
#create data frame
df <- data.frame(x=c(1, 1, 2, 3, 4, 4, 7, 7, 8, 9),
y=c(13, 14, 17, 12, 23, 24, 25, 28, 32, 33))
#create scatterplot of x vs. y
plot(df$x, df$y, pch=19)
#add vertical line at x=6
abline(v=6)
#add label to vertical line
text(x=5.8, y=20, srt=90, 'This is a label')
Notice that a label has been added just to the left of the vertical abline in the plot.
Note: The argument srt=90 in the text() function rotates the label 90 degrees.
Additional Resources
The following tutorials explain how to perform other common tasks in R:
How to Create a Scatterplot with a Regression Line in R
How to Add a Horizontal Line to a Plot Using ggplot2
How to Add a Vertical Line to a Plot Using ggplot2