There are several options for integrating your R workspace with LaTeX. One of these is the R package tikzDevice
that allows you to export images created in R as tikz code in a .tex file, for immediate use in a LaTeX document via the line \include{diagrams}
.
A simpler way, the one we all start out with, is to export an image from R as a .pdf, then include it using the line \includegraphics{diagrams.pdf}
. This is a pretty easy and straightforward workflow – so, why would I want to use tikzDevice
?
There several advantages to converting your images into TikZ code directly from R:
- TikZ diagrams consist of vectors coded directly into your LaTeX document: there’s no loss of image resolution.
- The labels on TikZ diagrams match the font of your LaTeX document.
- Wonderful LaTeX equations can be effortlessly used as labels in your diagrams.
- You can harness the power of the loop in R to create a single .tex file containing many images.
- You can harness the power of the loop in R to add
\caption{}
and\label{}
lines to all your images for immediate reference within LaTeX. - You can include all these features and output via one line in LaTeX:
\include{diagrams}
.
A Simple Example
That being said, let’s export a TikZ scatterplot using the tikzDevice
package. We will use data posted on Dr. Walter Enders web site.
Clik here to view.

Notice the fancy latex equations as labels on the plot.
R:
# gdata helps read .xls files require(gdata) df = read.xls("http://cba.ua.edu/assets/docs/wenders/arch.xls", sheet = 1) # tikzDevice will export the plots as a .tex file require(tikzDevice) # choose a name and path for the .tex file # folder should be the same as where your latex document resides tikz( '/Users/kevingoulding/latex_documents/thesis/plot_with_line.tex' ) plot(df, xlab = "$\\alpha_t + \\hat{\\beta}X_t$", ylab = "$Y_t$", main = "$Y_t = \\alpha_t + \\hat{\\beta}X_t$") abline(h = mean(df[,2]), col = "red", lwd = 2) dev.off() # must turn device off to complete .tex file
To include this diagram in your LaTeX document, simply add the line \include{plot_with_line}
and compile. Don’t forget to include \usepackage{tikz}
in the preamble. If you zoom in, you can see that we’ve labeled the plot and axes using LaTeX math language (amsmath).
Image may be NSFW.
Clik here to view.
A few things to be careful with as you try to code LaTeX equations from within R:
- All backslashes need to be doubled.
\
–>\\
. - All equations still need to be bordered by
$
on each side.
To be continued…