Search code examples
rplottextfigureplotmath

Functions to format text for base R plotting


Specifying text in a base R plot() with formatting such as italics / bold font / newline usually involves one or more of the following functions:

paste()
expression()
atop()
substitute()
italic()

Is there an intuitive explanation for the differences between these functions and when best to apply them?


Solution

  • What you're referring to is the plotmath syntax.

    To start off, let's make it clear that for a plotmath expression to be interpreted as such, you tell R it's an "expression" and that is why you need expression().

    So any time you want to use special symbols or formatting, like italic() and atop(), it's actually a part of plotmath and so you need to wrap it in an expression. eg:

    plot(0, main = expression(atop(over,italic(under))))
    

    plot1

    If you've tried out ?italic or ?atop, you've probably noticed it takes you straight to the plotmath manual page, where a bunch of other functions are listed.

    What about substitute() ? Well in my previous example, you'll notice I used strings directly to write 'over' and 'under', without putting them within quotes. This is because of the special expression() environment. So if you need to put whatever is inside a variable in your text (rather than the variable name) then you put your expression inside a substitute() and give it the arguments. eg:

    plot(0, main = substitute(atop(oo,italic(under))), list(oo='over2')))
    

    plot2

    Note that we don't put substitute around the expression block but replace it entirely.

    Finally, where does paste() come in all this ? Well, paste is the glue (pun intended) with any text not dealt with by plotmath.

    So if you need text before or after math symbols (or formatted text), you paste() things together within the expression (or substitute) environment. eg :

    plot(0, main = substitute(paste("b4", atop(oo,italic(under)), aft),
                              list(oo='over', aft = 'after3')))
    

    enter image description here

    As before, if you want to paste the content of a variable, you need substitute.


    And Voilà that's most of the plotmath you'll ever need!

    For any other symbols, or functions, have look at ?plotmath