Getting LaTeX into R Plots

The CRAN package latex2exp contains a TeX function that translate LaTeX formulas to R’s plotmath expressions. You can use it anywhere you could enter mathematical annotations, such as axis labels, legend labels, and general text.

For example:

x <- seq(0, 4, length.out=100)
alpha <- 1:5

plot(x, xlim=c(0, 4), ylim=c(0, 10), 
     xlab='x', ylab=TeX(r'($\alpha  x^\alpha$, where $\alpha \in \{1 \ldots 5\}$)'), 
     type="n", main=TeX(r'(Using $\LaTeX$ for plotting in base graphics!)', bold=TRUE))

for (a in alpha) {
  lines(x, a*x^a, col=a)
}

legend('topleft', 
       legend=TeX(sprintf(r'($\alpha = %d$)', alpha)), 
       lwd=1, 
       col=alpha)

produces this plot.

Leave a Comment