## What is the tikzDevice

The tikzDevice is a R package that transforms R plots into \$\LaTeX\$ codes blocks. Those \$\LaTeX\$ codes can be complied by pdfLaTeX (or other \$\TeX\$ engines) with the help of TikZ — a graphics package for TeX and friends written by Till Tantau. On the website \$\TeX\$ample you may find many beautiful pictures created using TikZ/PGF (TikZ is a set of higher-level macros built on top of PGF).

There are many packages that extends or are built on top of TikZ and PGF. For example, Beamer- a \$\LaTeX\$ class for creating presentations and Pgfplots - a \$\LaTeX\$ package that creates high-quality function plots in normal or logarithmic scaling.

## Requirements to use tikzDevice with R

R, RStudio and some R plotting packages are necessary for using tikzDevice.

Since tikzDevice only transforms R plots into \$\LaTeX\$, to see the output in picture, one also needs a TeX system (such as TeXLive or TinyTeX) and the TikZ package.

For R users, TinyTeX may be a better choice (see Yihui’s blog on how to install TinyTeX).

## Examples on how to use tikzDevice

There are two way to use tikzDevice.

One way is to produce standalone a tex file and then produce the picture (compile the tex file within your favoriate TeX editor or convert using the R function texi2dvi).

Another way is using Yihui’s amazing knitr package to integrate a plot into a Rmd file.

### Standalone

To create a standalone TeX file that stores the transformation, one may follows the following the example:tikzDevice - TikZ output from R on \$\TeX\$ample.

### Integrated

knitr provides various plot options. To use tikzDevice, one may use dev=‘tikz’ in R code chunk. For example,

`````````{r plotcos, echo=TRUE, dev='tikz'}
plot(cos, -pi, 2*pi,
main="The graph of cosine generated by tikzDevice and TikZ"
)
```
``````

For more sophisticated plots, one may have to modify options for tikzDevice.

The better way to handle option may be to set globally. With knitr, this can be done by creating a R code chunk at the beginning of the Rmd file. Here is an example (see the blog “knitr documents with tikzDevice graphics” for detail).

`````````{r setup}
library(tikzDevice)

options(
tikzLatexPackages = c(
"\\usepackage{amsmath,amssymb,amsfonts}",
"\\usepackage{tikz}",
"\\usepackage{standalone}",
"\\usepackage[utf8]{inputenc}",
"\\usetikzlibrary{decorations.pathreplacing}",
"\\usetikzlibrary{positioning}",
"\\usetikzlibrary{shapes.arrows,shapes.symbols}",
"\\usetikzlibrary{shapes.callouts}"
)
)

options(tikzMetricsDictionary="../tikzMetrics") # speeds tikz up
```
``````

It was noticed that the plot option of knitr didn’t work well with the tikzAnnotate function of tikzDevice.

Edited on 2021/04/24