You can use the text() function to add text to a plot in base R.
This function uses the following basic syntax:
text(x, y, “my text”)
where:
- x, y: The (x, y) coordinates where the text should be placed.
The following examples show how to use this function in practice.
Example 1: Add One Text Element to Plot
The following code shows how to use text() to add one text element to a plot at (x, y) coordinates of (5, 18):
#create data frame with values to plot df <- data.frame(x=c(1, 4, 7, 8, 8, 10), y=c(4, 9, 16, 14, 12, 20)) #create scatterplot plot(df$x, df$y) #add text element at (5, 18) text(x=5, y=18, "this is my text")
Notice that our text element has been added to the (x, y) coordinates of (5, 18) in the plot.
Example 2: Add Multiple Text Elements to Plot
To add multiple text elements to a plot, we can simply use multiple text() functions:
#create data frame with values to plot df <- data.frame(x=c(1, 4, 7, 8, 8, 10), y=c(4, 9, 16, 14, 12, 20)) #create scatterplot plot(df$x, df$y) #add text elements text(x=5, y=18, "first text") text(x=5, y=10, "second text") text(x=5, y=5, "third text")
Notice that three text elements have been added to the plot, each at the (x, y) coordinates that we specified.
Example 3: Customize Text Elements in Plot
We can use the cex, col, and font arguments to customize the size, color, and font style of the text elements in the plot, respectively:
#create data frame with values to plot df <- data.frame(x=c(1, 4, 7, 8, 8, 10), y=c(4, 9, 16, 14, 12, 20)) #create scatterplot plot(df$x, df$y) #add text elements with custom appearance text(x=5, y=18, "first text", col='red') text(x=5, y=10, "second text", col='blue', cex=3) text(x=5, y=5, "third text", col='green', cex=5, font=3)
Notice that each of the three text elements have a custom appearance.
Also note that the font argument takes four possible values:
- 1: plain
- 2: bold
- 3: italic
- 4: bold-italic
Since we specified font=3 for our third text element, the font is italic.
Example 4: Add Text Labels to Each Point in Plot
We can use the labels arguments to add a text label to each point in the plot:
#create data frame with values to plot df <- data.frame(teams=c('A', 'B', 'C', 'D', 'E', 'F'), x=c(1, 4, 7, 8, 8, 10), y=c(4, 9, 16, 14, 12, 20)) #create scatterplot plot(df$x, df$y) #add text label to each point in plot text(df$x, df$y, labels=df$teams, pos=4)
Notice that each of the points in the plot now have a text label.
Also note that the pos argument controls where the text label is placed relative to the point and takes four possible values:
- 1: below text
- 2: left of text
- 3: above text
- 4: right of text
Since we specified pos=4 each text label is placed to the right of the points in the plot.
Additional Resources
The following tutorials explain how to use other common functions in R:
How to Use paste & paste0 Functions in R
How to Use the replace() Function in R
How to Use the View() Function in R