22

R Markdown is a good tool for document authoring. It can use LaTeX statement in R Markdown directory. But when I try to insert a TikZ picture, I am lost about how to add preamble \usepackage{tikz} in it, so compile will fail.

Example code:

---
title: "R Markdown with tikz picture"
author: "Me"
date: "January 10, 2015"
output: beamer_presentation
---

## TikZ picture
- Here is a TikZ picutre

\begin{tikzpicture}
\draw (0,0) circle (2cm);
\end{tikzpicture}

Since actually it will generate a LaTeX document, so it's fine to just add it in LaTeX and then compile it to PDF but I wish I can just do it in R Markdown, then click the "Knit to PDF" button to generate PDF document directly.

kkuilla
  • 2,226
  • 3
  • 34
  • 37

2 Answers2

21

This is a example about how to use tikz graph in R Markdown within R Studio

---
title: "Hello World"
author: "Me"
date: "February 17, 2015"
output:
  pdf_document: default
header-includes: 
  - \usepackage{tikz}
  - \usepackage{pgfplots}
---

## TikZ picture
- Here is a TikZ picutre

\begin{tikzpicture}
\draw (0,0) circle (2cm);
\end{tikzpicture}

- Here is another TikZ picutre

\begin{tikzpicture}
\begin{axis}[xmax=9,ymax=9, samples=50]
  \addplot[blue, ultra thick] (x,x*x);
  \addplot[red,  ultra thick] (x*x,x);
\end{axis}
\end{tikzpicture}

Output:

enter image description here

  • 2
    Why when we knit to html, this tikz figures are not compiled?? – David Jul 31 '18 at 18:20
  • @David This is an old question, but are you compiling your file as a PDF file? If you are, then there should not be any issue. You seem to be trying to compile your file as an HTML file. – SavedByJESUS Aug 31 '19 at 08:41
  • @SavedByJESUS Yeah..Thats a mistake. I didnt realize that knit html does not use latex but tikz needs latex to compile – David Sep 08 '19 at 13:25
12

In this post it is described how to use LaTeX packages in R Markdown. Not sure if the tikz-package works with R Markdown though.

Community
  • 1
  • 1
jmjr
  • 2,090
  • 2
  • 21
  • 31
  • Great,it's what I want.Need to add section in YAML: header-includes: - \usepackage{tikz} –  Jan 19 '15 at 17:51
  • @Beatlej: Did it work to use the tikz package with RMarkdown? – histelheim Jul 31 '15 at 00:48
  • @histelheim Sure, check a simple example from my answer below. –  Aug 01 '15 at 10:35
  • 4
    I am now using `tikzDevice` (via `knitr::chunk_options$set(dev = "tikz")`) in an `rmarkdown` document that builds as a PDF. It *just works*, the above line was enough, everything else seems to happen magically behind the scenes. – krlmlr Jan 22 '16 at 08:26