How can I add a label to an abline in r?

In R, you can add a label to an abline by using the “lty” argument in the abline() function and setting it to “b” for a labelled line. This will allow you to specify a text label to be placed at the end of the abline. You can also specify the font size, colour and position of the label using additional arguments.


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')

add label to horizontal abline in R

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:

Example 2: Add Label to Vertical abline in R

#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.

The following tutorials explain how to perform other common tasks in R:

x