Including TikZ images in Rmarkdown

2022/07/27

Categories: TeX TikZ PGF Tags: TeX TikZ PGF

It is possible to draw TikZ graphics in Rmarkdown. Here is how.

  1. Install some tools on Debian/Ubuntu.
  1. Install pdftool and magick package in R.

  2. Open your rmarkdown file and include your TikZ pictures as follows:

```{r, echo=FALSE, engine='tikz', out.width='90%', fig.ext=if (knitr:::is_latex_output()) 'pdf' else 'png'}
\begin{tikzpicture}[scale=.7]
\draw [fill=gray!30,very thick] (0,-1) rectangle (5,1);
\draw [very thick] (5, 0) -- (13,0);
\node [below] at (2,-1) {\large Hello};
\node [below, align=center] at (0,-1) {\large Two\\ lines};
\end{tikzpicture}
```

This is the picture:

There may also be a way to include a latex preamble, but I have not figured that out yet.