Introduction


There are occassions when you want to display additional information in a plot. This is usually achieved by adding text either inside the plot or on the margins. For example, you might want to label a line/bar or add formulas to better communicate what is shown in the plot. The idea is to use the available space within/outside the plot to provide additional information that can be useful to the end users. We will learn to add text inside as well as on the margins of the plot. This is accomplished using the following two functions:

  • text() : add text inside the plot
  • mtext() : add text on the margins of the plot

Syntax


Let us take a quick look at the syntax of both the functions:

text(x, y = NULL, labels = seq_along(x$x), adj = NULL,
     pos = NULL, offset = 0.5, vfont = NULL,
     cex = 1, col = NULL, font = NULL, ...)
mtext(text, side = 3, line = 0, outer = FALSE, at = NA,
      adj = NA, padj = NA, cex = NA, col = NA, font = NA, ...)

Text Inside the Plot


To add text inside a plot, the following arguments must be supplied to the text() function:

  • labels : the text to be displayed
  • x : x axis coordinate
  • y : y axis coordinate

Text Inside the Plot


plot(mtcars$disp, mtcars$mpg)
text(x = 340, y = 30, labels = 'Sample Text')

Text Color


plot(mtcars$disp, mtcars$mpg)
text(x = 340, y = 30, labels = 'Sample Text', col = 'red')

Text Color


Font


plot(mtcars$disp, mtcars$mpg)
text(x = 340, y = 30, labels = 'Sample Text', col = 'red', font = 2)

Font


Font Family


plot(mtcars$disp, mtcars$mpg)
text(x = 340, y = 30, labels = 'Sample Text', col = 'red', family = 'mono')

Font Family


## Warning in text.default(x = 340, y = 30, labels = "Sample Text", col =
## "red", : font family not found in Windows font database

Font Size


plot(mtcars$disp, mtcars$mpg)
text(x = 340, y = 30, labels = 'Sample Text', col = 'red', cex = 2)

Font Size


Text on the Margins


The mtext() function allows the user to place the text on the margins of the plot. It allows the user to modify the location of the text in multiple ways using the following options:

  • side
  • line
  • adj

Text on the Margins


plot(mtcars$disp, mtcars$mpg)
mtext('Sample Text')

Specify Margin


plot(mtcars$disp, mtcars$mpg)
mtext('Sample Text', side = 1)

Specify Margin


Line


plot(mtcars$disp, mtcars$mpg)
mtext('Sample Text', line = 1)

Line


plot(mtcars$disp, mtcars$mpg)
mtext('Sample Text', line = -1)

Line


Alignment


plot(mtcars$disp, mtcars$mpg)
mtext('Sample Text', adj = 0)

Alignment


plot(mtcars$disp, mtcars$mpg)
mtext('Sample Text', adj = 1)

Alignment