Search code examples
rlatexlatex2exp

Using Latex math fonts in R plots


I am frequently using Latex to use custom math expressions in titles and axis labels of R plots. As described here, this can be achieved using the latex2exp package. Is it somehow possible to include Latex special fonts for mathmode? Specifically, I am looking for a way to include \mathcal and \mathbb symbols in R plots. Of these, \mathbb might be harder, because it requires a Latex package (usually amsfonts). According to this post, \mathcal does not require any Latex packages, but it still does not seem to work.

Here is an example:

library(ggplot2)
library(latex2exp)

# this works:
ggplot() + ggtitle(TeX('$\\alpha + \\sum_{n = 1}^\\infty \\frac{1}{n^2}$'))

# this does not:
ggplot() + ggtitle(TeX('$\\mathcal{A} + \\mathbf{C}$'))

Created on 2023-08-04 with reprex v2.0.2

The same issue occurs in base R plotting, so it's not a ggplot issue.

According to the answer in this post, at least \mathbf should work as used above, but it doesn't for me. When I copy-paste the example from the reply and run it, the graphics device writes out "mathbf", as in my example above.


Solution

  • To answer part of this, I'm quoting from ?text and ?par , describing some of the possible arguments. As you can see, access to arbitrary fonts from your machine's OS is not generally possible when creating the graphs inside R. However, per Stephane Laurent's comment, I think the tikzDevice package allows you to define a graph which will not actually come into existence, so to speak, until the output from R is rendered with a TeX application. This allows you to specify any font inside LaTeX commands.

    family
    The name of a font family for drawing text. The maximum allowed length is 200 bytes. This name gets mapped by each graphics device to a device-specific font description. The default value is "" which means that the default device fonts will be used (and what those are should be listed on the help page for the device). Standard values are "serif", "sans" and "mono", and the Hershey font families are also available. (Devices may define others, and some devices will ignore this setting completely. Names starting with "Hershey" are treated specially and should only be used for the built-in Hershey font families.) This can be specified inline for text.

    font
    An integer which specifies which font to use for text. If possible, device drivers arrange so that 1 corresponds to plain text (the default), 2 to bold face, 3 to italic and 4 to bold italic. Also, font 5 is expected to be the symbol font, in Adobe symbol encoding. On some devices font families can be selected by family to choose different sets of 5 fonts.