Table of Contents
To label points on a scatterplot in R, you can use the “text” function which allows you to add text to a specific point on the plot. The syntax for this function is “text(x, y, labels)”, where x and y are the coordinates of the point and labels is the text you want to display. Additionally, you can use the “points” function to add markers to the points on the scatterplot, making them easier to identify. It is also possible to customize the size, color, and font of the labels and markers using the arguments in these functions. Overall, using the “text” and “points” functions in R allows for easy and effective labeling of points on a scatterplot.
Label Points on a Scatterplot in R (With Examples)
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 <- data.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 <- data.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)
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 <- data.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')
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 <- data.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))