//
you're reading...

# Latex symbols in R plots

Recently I’ve been making a lot of plots using R and I’ve reached the “I need some fancy math here” point. If you google around you’ll find the way to do this (for example or ) but I’ll post here a quick snippet anyway.

One way of adding math symbols to your plots is using the expression function. However if you are planning to use your plots as part of an article or report written in Latex, then in my opinion it is actually better to use the tikz graphical device. This may be a bit more complicated at first but with tikz you can use the same syntax both in the report text and on the plots so in the long run it is worth the effort.

So here’s the code:

require(tikzDevice)

# Start the tikz device
tikz('phi_plot.tex',
standAlone = TRUE, # We want a tex file that can be directly compiled to a dvi
width = 6, height = 6,
packages=c(options()$tikzLatexPackages, "\\usepackage{amsfonts}")) # Prepare your wonderful plot x &lt;- seq(-2,2,length=100) plot(x, x^2+rnorm(100,sd=0.1), asp=1, xlab=&quot;x&quot;,ylab=&quot;$\\phi(x)$&quot;, main = &quot;Plot of the$\\phi : \\mathbb R \\rightarrow \\mathbb R$function defined as$\\phi(x) = x^2 + \\varepsilon$&quot;) # Turn the device off dev.off(); # Convert the latex file to a pdf tools::texi2pdf('phi_plot.tex',quiet=FALSE)  If all goes well then phi_plot.pdf should look like this : There are however some possible pitfalls. • Notice how the amsfonts package is included – if we would simply try to do this : tikz('phi_plot.tex', standAlone = TRUE, # We want a tex file that can be directly compiled to a dvi width = 6, height = 6, packages=c("\\usepackage{amsfonts}"))  then the result would most probably be ! ==&gt; Fatal error occurred, no output PDF file produced! Błąd w getMetricsFromLatex(TeXMetrics) : TeX was unable to calculate metrics for the following string or character: m Common reasons for failure include: * The string contains a character which is special to LaTeX unless escaped properly, such as % or$.
* The string makes use of LaTeX commands provided by a package and
the tikzDevice was not told to load the package.


this is because the included package actually overrides the packages set in tikz options so the original option value also needs to be included.

• If something bad happens and the tikz device doesn’t get switched off then the next attempt to convert the tex file to a pdf
may end complaining that the texi2dvi returned error code 1. In such case try to turn the tikz device off (dev.off())
and just in case put the entire clause in a tryCatch and the dev.off() in the finally clause.