Chun-Jie Liu

Plot TeX in R

Chun-Jie Liu · 2022-08-03

Using latex2exp package to plot TeX in R.

The Tex function taks a LaTeX string and return sthe plotmath expression suitable for using graphics. Refer to the latex2exp package for more details. Refer to the markdown syntax for more details here.

Basic LaTeX equations

In line eqaution: $\int_{-\infty}^{\infty} e^{-x^2} dx$

In block eqaution: $$\begin{align} \int_{-\infty}^{\infty} e^{-x^2} dx \end{align}$$


- $x+y$
- $x-y$
- $x \times y$
- $x \div y$
- $\dfrac{x}{y}$
- $\sqrt{x}$

- $\pi \approx 3.14159$
- $\pm \, 0.2$
- $\dfrac{0}{1} \neq \infty$
- $0 < x < 1$
- $0 \leq x \leq 1$
- $x \geq 10$
- $\forall \, x \in (1,2)$
- $\exists \, x \notin [0,1]$
- $A \subset B$
- $A \subseteq B$
- $A \cup B$
- $A \cap B$
- $X \implies Y$
- $X \impliedby Y$
- $a \to b$
- $a \longrightarrow b$
- $a \Rightarrow b$
- $a \Longrightarrow b$
- $a \propto b$
- $\bar a$
- $\tilde a$
- $\breve a$
- $\hat a$
- $a^ \prime$
- $a^ \dagger$
- $a^ \ast$
- $a^ \star$
- $\mathcal A$
- $\mathrm a$
- $\cdots$
- $\vdots$
- $\#$
- $\$$
- $\%$
- $\&$
- $\{ \}$
- $\_$

latex2exp

plot(TeX(r'(A $\LaTeX$ formula: $\frac{2hc^2}{\lambda^5}\frac{1}{e^{\frac{hc}{\lambda k_B T}} - 1}$)'), cex=2, main="")
x <- seq(0, 4, length.out=100)
alpha <- 1:5
data <- map_df(alpha, ~ tibble(v=.*x^., x=x, alpha=.))

p <- ggplot(data, aes(x=x, y=v, color=as.factor(alpha))) +
    geom_line() +
    ylab(TeX(r'($\alpha  x^\alpha$, where $\alpha \in 1\ldots 5$)')) +
    ggtitle(TeX(r'(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(r'($\alpha = %d$)', alpha), TeX))
    # Note that ggplot2 legend labels must be lists of expressions, not vectors of expressions

print(p)
latex2exp_examples(cex=0.9)