Home » How to Label Points on a Scatterplot in R (With Examples)

How to Label Points on a Scatterplot in R (With Examples)

by Erma Khan

This tutorial provides an example of how to label the points on a scatterplot in both base R and ggplot2.

Example 1: Label Scatterplot Points in Base R

To add labels to scatterplot points in base R you can use the text() function, which uses the following syntax:

text(x, y, labels, …)

  • x: The x-coordinate of the labels
  • y: The y-coordinate of the labels
  • labels: The text to use for the labels

The following code shows how to label a single point on a scatterplot in base R:

#create data
df frame(x=c(1, 2, 3, 4, 5, 6),
                 y=c(7, 9, 14, 19, 12, 15),
                 z=c('A', 'B', 'C', 'D', 'E', 'F'))

#create scatterplot
plot(df$x, df$y)

#add label to third point in dataset
text(df$x[3], df$y[3]-1, labels=df$z[3])

The following code shows how to label every point on a scatterplot in base R:

#create data
df frame(x=c(1, 2, 3, 4, 5, 6),
                 y=c(7, 9, 14, 19, 12, 15),
                 z=c('A', 'B', 'C', 'D', 'E', 'F'))

#create scatterplot
plot(df$x, df$y)

#add labels to every point
text(df$x, df$y-1, labels=df$z)

Label scatterplot points in R

Example 2: Label Scatterplot Points in ggplot2

The following code shows how to label a single point on a scatterplot in ggplot2:

#load ggplot2
library(ggplot2)

#create data
df frame(x=c(1, 2, 3, 4, 5, 6),
                 y=c(7, 9, 14, 19, 12, 15),
                 z=c('A', 'B', 'C', 'D', 'E', 'F'))

#create scatterplot with a label on the third point in dataset
ggplot(df, aes(x,y)) +
  geom_point() +
  annotate('text', x = 3, y = 13.5, label = 'C')

Ggplot2 add labels to scatterplot

The following code shows how to label every point on a scatterplot in ggplot2:

#load ggplot2 & ggrepel for easy annotations
library(ggplot2)
library(ggrepel)

#create data
df frame(x=c(1, 2, 3, 4, 5, 6),
                 y=c(7, 9, 14, 19, 12, 15),
                 z=c('A', 'B', 'C', 'D', 'E', 'F'))

#create scatterplot with a label on every point
ggplot(df, aes(x,y)) +
  geom_point() +
  geom_text_repel(aes(label = z))

labels on scatterplot in ggplot2

Additional Resources

How to Create a Scatterplot with a Regression Line in R
How to Use the Jitter Function in R for Scatterplots

Related Posts