Expressions in R

expression() and related functions including bquote are powerful tools for annotating figures with mathematical notation in R. This functionality is not obvious from their respective help files. demo(plotmath) nicely shows the huge potential of expression(), but does not help that much with getting the code need for many real cases.

I tend to get my expressions to work by trial and lots of errors (although having put this together, I now understand them at least temporarily). I’ve just searched through my code library and extracted and annotated some examples of expression() being used. I hope someone finds it useful.

I’m going to use expression() with title(), but the same expressions can be used with any of the functions (text(), title(), mtext(), legend(), etc) used for putting text on plots.

x11(width = 4, height = 5, point = 14)
par(mar = rep(0, 4), cex.main = .8)
plot(1, type="n", axes = FALSE, ann = FALSE)

The simplest use of expression is take a character or string of characters and it will be added to the plot. If the string contains spaces, it must be enclosed in quotes (alternatively, the space can be replaced by a tilde ~, which probably gives better code – see comment from Gavin below).

title(line = -1, main = expression(fish))

This use of expression is entirely pointless, but is a useful starting point. Some strings have special meanings, for example infinity will draw the infinity symbol. If for some reason you want to have “infinity” written on your plot, it must be in quotes. Greek letters can be used by giving their name in lower-case or with the first letter capitalised to get the lower or upper case character respectively.

title(line = -2, main = expression(infinity))
title(line = -3, main = expression(pi))
title(line = -4, main = expression(Delta))

Subscript or superscript can be added to a string using ^ and [] notation respectively.

title(line = -5, main = expression(r^2))
title(line = -6, main = expression(beta[1]))

If the string we want to have as sub- or superscript contains a space, the string must be in quotes. Braces can be used to force multiple elements to all be superscript.

Strings can be separated by mathematical operators.

title(line = -7, main = expression(N[high]-N[low]))
title(line = -8, main = expression(N[2]==5))

To make more complicated expressions, build them up from separate parts by either using * or paste to join them together (if you want a multiplication symbol, use %*%). The * notation gives nicer code.

title(line = -9, main=expression(Delta*"R yr"))
title(line = -10, main=expression(paste(Delta,"R yr")))
title(line = -11, main=expression(paste("Two Year Minimum ",O[2])))
#title(line = -11, main=expression(Two~Year~Minimum~O[2]))
title(line = -12, main=expression(paste("Coefficient ", beta[1])))
#title(line = -12, main=expression(Coefficient~beta[1]))
title(line = -13, main=expression(paste("TP ", mu,"g l"^-1)))
#title(line = -13, main=expression(TP~mu*g~l^-1))
title(line = -14, main=expression(paste(delta^18,"O")))
#title(line = -14, main=expression(delta^18*O))
title(line = -15, main=expression(paste("Foram ", exp(H*minute[bc]))))
#title(line = -15, main=expression(Foram~exp(H*minute[bc])))

To start an expression() with a superscript (or subscript), I use an empty string (you can also use phantom()).

title(line = -16, main = expression(""^14*C*" years BP"))
#title(line = -16, main = expression(phantom()^14*C~years~BP))

So far so good. But sometimes, you want to use the value of an R-object in plot annotation.

For example, if we wanted to label a point with its x value, this will not work.

x <- 5
title(line = -17, main= expression(x==x))

Instead of using expression(), we have to use bquote(), with the object we want written out inside .()

title(line = -18, main = bquote(x==.(x)))
title(line = -19, main = bquote(x==.(x)~mu*g~l^-1))
Plot annotations with expression and bquote

Plot annotations with expression and bquote

If you understand these examples, you should be able to use the remainder of the functionality demonstrated by demo(plotmath) and at ?plotmath.

Advertisements

About richard telford

Ecologist with interests in quantitative methods and palaeoenvironments
This entry was posted in R and tagged , . Bookmark the permalink.

2 Responses to Expressions in R

  1. ucfagls says:

    Funny, I’d been meaning to write something on this for a while!

    I used to use paste() for this too, but it often resulted in messy code or difficult to follow combinations of vectors. I now find it much easier to just use ~ to space out words, * to juxtapose words, and use quoted strings to run several words together as a single quoted string to cut down on multiple ~.

    Another trick is to use phantom() to provide the anchor for other elements. Your 14C example could, combining both of these be written as:

    expression(phantom()^{14} * C ~ years ~ BP)
    ## or
    expression(phantom()^{14} * "C years BP")
    

    Or the TP units as

    expression(TP ~ mu * g ~ l^{-1})
    

    Once you forget about quoting strings (there are one or two places where you may need to quote; writing SO[4]^{2-} doesn’t work for example), these start to get much simpler.

    • Hei Gavin,

      Thanks for commenting. As I wrote this post, I began to realise that the * and ~ notation, which I have only used occasionally before, is much neater than paste() and quotes. I’ve now put the alternative style after each example.

      The SO[4]^{2-} problem can be solved with SO[4]^{2-phantom()} if you want to be a purist about not quoting.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s