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 plotmtext()
: add text on the margins of the plotLet 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, ...)
To add text inside a plot, the following arguments must be supplied to the text()
function:
labels
: the text to be displayedx
: x axis coordinatey
: y axis coordinateplot(mtcars$disp, mtcars$mpg)
text(x = 340, y = 30, labels = 'Sample Text')
plot(mtcars$disp, mtcars$mpg)
text(x = 340, y = 30, labels = 'Sample Text', col = 'red')
plot(mtcars$disp, mtcars$mpg)
text(x = 340, y = 30, labels = 'Sample Text', col = 'red', font = 2)
plot(mtcars$disp, mtcars$mpg)
text(x = 340, y = 30, labels = 'Sample Text', col = 'red', family = 'mono')
## Warning in text.default(x = 340, y = 30, labels = "Sample Text", col =
## "red", : font family not found in Windows font database
plot(mtcars$disp, mtcars$mpg)
text(x = 340, y = 30, labels = 'Sample Text', col = 'red', cex = 2)
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
plot(mtcars$disp, mtcars$mpg)
mtext('Sample Text')
plot(mtcars$disp, mtcars$mpg)
mtext('Sample Text', side = 1)
plot(mtcars$disp, mtcars$mpg)
mtext('Sample Text', line = 1)
plot(mtcars$disp, mtcars$mpg)
mtext('Sample Text', line = -1)
plot(mtcars$disp, mtcars$mpg)
mtext('Sample Text', adj = 0)
plot(mtcars$disp, mtcars$mpg)
mtext('Sample Text', adj = 1)