R Tips

Home

Contact

Steven Holland

Special characters and typography

21 March 2013, 26 February 2015

It is easy in R to include special characters (like Greek letters), typography (like subscripts, superscripts, bars), or mathematical formulas in axis labels or other text. First, build your text string (see below), then wrap it in the paste() function, which will combine the various elements in your string, and then wrap it in the expression() function, which will convey to R that this is a string of text.

To build your text string, see the help page for plotmath, which shows the available symbols. To see a table of formulas for various mathematical expressions, type demo(plotmath). For most symbols, the syntax is simple. Adding a subscript is done by placing the subscript text in brackets: SO[4] will make SO4. Adding a superscript is done by preceding the superscript text with a caret (^) symbol: O^18 will make O18. Some symbols require functions, such as placing a bar over text: bar(X).

These can be chained together with commas to build up more complicated formulas. For example, Si[2],O[6] will make Si2O6.

Greek letters can be inserted with their name: delta, theta, sigma, etc.

Here's a simple example showing how to use these for two custom axis labels:

plot(x, y, ylab=expression(paste(theta[2007])), xlab=expression(paste(bar(m))[2007]))

You can also used this approach to add text to a plot that displays a calculated value, such as R2. To embed a calculated value in a text string, you need to use bquote(). For example, here is how you might add a label with R2 on a plot.

rsquared <- round(cor(x, y)^2, 2) text(5, 30, bquote(R^2 == .(rsquared)))

The double equals sign (==) is necessary so that bquote reads this as the symbol "=" and not as the assignment operator.