7.3 Math Expression in Figures

Main idea: to use expression or convert latex to expression;

Two options:

  1. expression(CO[2]) show math equation style as \(CO_2\).

    https://www.dataanalytics.org.uk/axis-labels-in-r-plots-using-expression/#expression_comm

    Basic syntax:

    • ^ for superscript

      Superscript is “started” by the caret ^ character. Anything after ^ is superscript. The superscript continues until you use a * or ~ character.

      If you want more text as superscript, then enclose it in quotes.

      expression(Super^script~text)  # superscript ends at the space

      renders as \(Super^{script} text\).

      expression(Super^"script text") # superscript continues until the closing quote

      renders as \(Super^{script text}\).

    • [] for subscript

      plot(1,1, main=expression('title'^2))   # superscript
      plot(1,1, main=expression('title'[2]))  # subscript
    • Use ~ for spacing in math mode.

      When you type an expression() any spaces you type are ignored.

    • Use * for tight concatenation (no space).

    • Combine text + math: expression("Mean of " * mu) → “Mean of μ”.

      • Quotes are optional. The usual letters and numbers are not “interpreted”.
      • Quotes are used to enclose items that would otherwise be treated as a special character (like ~, *, +, -).
    • Font face: plain(), bold(), italic(), underline(), bolditalic().

    Commonly used expressions:

    λ expression(lambda)
    y \(\le\) 5 expression("y"<= "5")
    y\(_i\) expression(y[i])
    x\(^2\) expression(x^2)
    x\(^2\) + 5 expression(x^2~"+ 5")) to add characters after a superscript, end the superscript with a * (no space) or ~ (space)
    P(Y < y | ɸ) expression(paste("P(Y", \<, "y | ", phi,")")) … expression(paste(“blah”, symbol, “blah”, symbol, “blah))

  2. latex2exp::TeX("$\\alpha^\\beta$") show as \(\alpha^{\beta}\);

    Basic syntax:

    • Escape special characters

      • Use \ before special characters, e.g., greek letters and latex commands that start with \;

      • Alternatively, use TeX(r"(\alpha)") to specify raw R string.

        r"( ... )" → everything inside is taken literally (no escaping). It means “take everything literally, don’t treat \ as escape characters.” ... can contain any character sequence, including \.

        See ?Quotes for raw string literal syntax.

      library(latex2exp)
      
      TeX(r"(\alpha)")       # raw string
      TeX("\\alpha")         # same, but escaped
      expression(alpha)      # equivalent

      All three produce the symbol α.

    • Put math needs to be rendered between $...$ and regular text outside $...$.

    Tricks:

    • Print whitespace in math mode $...$:
      • use \\, or \\; to show white space in math mode. \\; is a larger space than \\,.
      • ~ to print a normal space
      • \phantom{x} to print a space the width of the character x.
# There is an R package called latex2exp which may be helpful. It has function TeX which accepts some LaTeX expressions enclosed with dollar sign $ as in this example:

library(latex2exp)
library(ggplot2)

qplot(1, "A")+
     ylab(TeX("Formula: $\\frac{2hc^2}{\\lambda^\\beta}$"))+
     xlab(TeX("$\\alpha$"))

Tex

TeX only put the part that needs latex interpretation between $...$, and there are several escape characters that needs to be carefully treated.

Symbol TeX
\ \\
[ \[
] \]

Check out other escaping characters:

https://stat.ethz.ch/R-manual/R-devel/library/grDevices/html/plotmath.html

Ref:


TeX in legend scales, the use of unname() is necessary:

# have to use unname(TeX("$...$"))
labels=c("CRU", unname( TeX("$Burke \\times 10$") ) ) 

When using TeX inside geom_text(aes(x, y, label=TeX("", output = "character") ), parse=TRUE ),

  • specifying the output of TeX() as character, although “character” is not one of the values that the output argument can take, and

  • turning the parse argument in geom_text() to TRUE.


Using variables in aes

aes_string(x="TCS_reported", y=as.name(target_v))

  • target_v can be a variable which will be parsed in aes;

  • as.name() first coerces its argument internally to a character vector; then takes the first element and returns a symbol of that name.

    • A name (also known as a ‘symbol’) is a way to refer to R objects by name (rather than the value of the object, if any, bound to that name).

    • It will escape special characters that are otherwise reserved or illegal; equivalent to 'target_v'

target_v <- "#Obs"
aes_string(x="TCS_reported", y=as.name(target_v))

# or equivalently replace `as.name()` with backticks ``
target_v <- "`#Obs`"
aes_string(x="TCS_reported", y=target_v)

# or using get()
aes(x=TCS_reported, y=get(target_v))