# 31 LaTeX rendering

LaTeX rendering via MathJax is possible via the TeX() function which flags a character vector as LaTeX. To load MathJaX externally (meaning an internet connection is needed for TeX rendering), set the new mathjax argument in config() to "cdn". Figure 31.1 demonstrates how to render LaTeX in the plot and axis titles.

library(plotly)
data(co2, package = "datasets")

plot_ly() %>%
add_lines(x = zoo::index(co2), y = co2) %>%
layout(
title = TeX("CO_2 \\text{measured in } \\frac{parts}{million}"),
xaxis = list(title = "Time"),
yaxis = list(title = TeX("\\text{Atmospheric concentraion of CO}_2"))
) %>%
config(mathjax = "cdn")

Figure 31.2 demonstrates how to render LaTeX with on-graph text. There are two ways to draw on-graph text: add_text() which is a scatter trace with a mode of text and add_annotations() which is part of the graph’s layout. The main difference is that add_text() is able to display tooltips and add_annotations() is able to display arrows.

plotly_empty(showlegend = FALSE, hoverinfo = "x+y") %>%
add_annotations(x = 1, y = 2, text = TeX("\\text{The sample mean:} \\sum_{i=1}^n x_i \\text{ where}"), showarrow = FALSE) %>%
add_text(x = 1, y = 1, text = TeX("x_i \\sim N(\\mu, \\sigma)"), size = I(100)) %>%
add_annotations(x = 1, y = 0, text = TeX("E[x_i]")) %>%
add_text(x = 1, y = 0, text = TeX("\\mu"), textposition = "bottom") %>%
config(mathjax = "cdn")

To use a local version of MathJax (so that your graphs will render without an internet connection), you need to inform plotly where it’s located. If you don’t already have MathJax locally, I recommend downloading the official MathJax git repo. Here’s how to do that using terminal commands:

$git clone https://github.com/mathjax/MathJax.git$ cd MathJax

Now set the PLOTLY_MATHJAX_PATH environment variable so that plotly knows where that MathJax folder lives. I recommend setting this variable in you .Rprofile so you don’t have to reset it everytime you restart R:

$export PLOTLY_MATHJAX_PATH=pwd$ echo "Sys.setenv('PLOTLY_MATHJAX_PATH' = '\$PLOTLY_MATHJAX_PATH')" >> ~/.Rprofile

Finally, once PLOTLY_MATHJAX_PATH is set, specify mathjax="local" in config():

config(last_plot(), mathjax="local")

## 31.1 MathJax caveats

1. MathJax rendering in tooltips currently isn’t supported.

2. At least currently, plotly.js requires SVG-based rendering which doesn’t play nicely with HTML-based rendering (e.g. rmarkdown documents and shiny apps) . If you need both the SVG and HTML rendering, consider <iframe>-ing your plotly graph(s) into the larger document (see here for an example).

3. Due to the size and nature of MathJax, using htmlwidget::saveWidget() with selfcontained = TRUE won’t work. At least for now, when you need to save a plotly graph (p) with local MathJax, do htmlwidget::saveWidget(p, selfcontained = FALSE)