Understanding R: Mathematical Expressions
Basic Mathematical Expressions
expr1 = expression(c^2 == a[1]^2 + b[1]^2)
expr2 = expression(paste(pi^{
x[i]
}, (1 - pi)^(n - x[i])))
expr3 = expression(paste("Sample mean: ", italic(n)^{
-1
}, sum(italic(x)[italic(i)], italic(i) == 1, italic(n)) == frac(italic(x)[1] + ... +
italic(x)[italic(n)], italic(n))))
expr4 = expression(paste("f(x", "|", alpha, ",", beta, ")" == frac(x^{
alpha - 1
} ~ (1 - x)^{
beta - 1
}, B(alpha, beta))))
plot(1, 1, type = "n", xlim = c(-1, 1), ylim = c(0.5, 4.5), xaxt = "n", yaxt = "n",
ann = FALSE)
text(0, 4:1, labels = c(expr1, expr2, expr3, expr4), cex = 1.35)
title(main = "Math", cex.main = 2)
Using Greek Letters in Plot Title
R allows users great flexibility in creating and formatting plots. Greek letters can be included in titles and labels using the expression command.
Example 1
set.seed(1) # for reproducible, pseudo-random numbers
betas <- rnorm(1000)
hist(betas, main = expression(beta), col = "light blue")
If we want Greek letters embedded in the text of a title or label, we can use expression with paste:
Equations inside Plot
Add equations directly inside plot areas.
Example 1
curve(dnorm, from = -3, to = 3, n = 1000, main = "Normal Probability Density Function")
text(-2, 0.3, expression(f(x) == paste(frac(1, sqrt(2 * pi * sigma^2)), " ", e^{
frac(-(x - mu)^2, 2 * sigma^2)
})), cex = 1.2)
Example 2
Combining Expressions and Text
If you want to combine multiple mathematical expressions with text, use paste() inside expression(), as in the following.
plot(rnorm(100), rnorm(100), xlab = expression(hat(mu)[0]), ylab = expression(alpha^beta),
main = expression(paste("Plot of ", alpha^beta, " versus ", hat(mu)[0])))
latex2exp
latex2exp is an R package that parses and converts LaTeX math formulas to R’s plotmath expressions. Plotmath expressions are used to enter mathematical formulas and symbols to be rendered as text, axis labels, etc. throughout R’s plotting system. I find plotmath expressions to be quite opaque, while LaTeX is a de-facto standard for mathematical expressions, so this package might be useful to others as well.
The TeX function takes a LaTeX string and returns a plotmath expression suitable for use in plotting, e.g.,
expression(`$\alpha^\beta$` = paste("", "", alpha, , , , phantom()^{
paste(beta, , , , "")
}))
# (note it is always necessary to escape the backslash within a string, hence the
# double backslash).
# The return value of TeX() can be used anywhere a plotmath expression is
# accepted, including plot labels, legends, and text.
# The following example shows plotting in base graphics:
x <- seq(0, 4, length.out = 100)
alpha <- 1:5
plot(x, xlim = c(0, 4), ylim = c(0, 10), xlab = "x", ylab = TeX("$\\alpha x^\\alpha$, where $\\alpha \\in 1\\ldots 5$"),
type = "n", main = TeX("Using $\\LaTeX$ for plotting in base graphics!"))
invisible(sapply(alpha, function(a) lines(x, a * x^a, col = a)))
legend("topleft", legend = TeX(sprintf("$\\alpha = %d$", alpha)), lwd = 1, col = alpha)
library(plyr)
library(ggplot2)
x <- seq(0, 4, length.out = 100)
alpha <- 1:5
data <- mdply(alpha, function(a, x) data.frame(v = a * x^a, x = x), x)
p <- ggplot(data, aes(x = x, y = v, color = X1)) + geom_line() + ylab(TeX("$\\alpha x^\\alpha$, where $\\alpha \\in 1\\ldots 5$")) +
ggtitle(TeX("Using $\\LaTeX$ for plotting in ggplot2. I $\\heartsuit$ ggplot!")) +
coord_cartesian(ylim = c(-1, 10)) + guides(color = guide_legend(title = NULL)) +
scale_color_discrete(labels = lapply(sprintf("$\\alpha = %d$", alpha), TeX))
# Note that ggplot2 legend labels must be lists of expressions, not vectors of
# expressions
print(p)
Quickly test out what a translated LaTeX string would look like by using plot:
plot(TeX("A $\\LaTeX$ formula: $\\frac{2hc^2}{\\lambda^5} \\,
\\frac{1}{e^{\\frac{hc}{\\lambda k_B T}} - 1}$"),
cex = 2)
[1] "\\%" "\\," "\\;" "\\aleph"
[5] "\\approx" "\\ast" "\\bar" "\\bigcap"
[9] "\\bigcup" "\\bullet" "\\cdot" "\\cdots"
[13] "\\clubsuit" "\\cong" "\\degree" "\\diamondsuit"
[17] "\\div" "\\dot" "\\equiv" "\\exists"
[21] "\\forall" "\\frac" "\\geq" "\\hat"
[25] "\\heartsuit" "\\Im" "\\in" "\\infty"
[29] "\\int" "\\LaTeX" "\\lbrack" "\\ldots"
[33] "\\leftarrow" "\\Leftarrow" "\\leq" "\\lim"
[37] "\\mathbf" "\\mathit" "\\mathrm" "\\neg"
[41] "\\neq" "\\normalsize" "\\notin" "\\nsubset"
[45] "\\oplus" "\\oslash" "\\otimes" "\\overset"
[49] "\\partial" "\\perp" "\\pm" "\\prime"
[53] "\\prod" "\\propto" "\\rbrack" "\\Re"
[57] "\\rightarrow" "\\Rightarrow" "\\sim" "\\small"
[61] "\\spadesuit" "\\sqrt" "\\subset" "\\subseteq"
[65] "\\sum" "\\supset" "\\supseteq" "\\surd"
[69] "\\TeX" "\\textbf" "\\textit" "\\tilde"
[73] "\\times" "\\tiny" "\\underline"
[ reached getOption("max.print") -- omitted 5 entries ]
[1] TRUE