Search code examples
rr-markdowntikzdevice

tikzDevice does not use LaTeX preamble when used in RMarkdown document


I want to use tikz as graphics device in RMarkdown and I want it to include the generated LaTeX preamble.

In the past, I already used tikzDevice within knitr documents. The tex file generated by tikzDevice usually included the whole preamble from my knitr/LaTeX document. When I use it with RMarkdown, I get the standard preamble (see below).

RMarkdown file:

---
title: "Title"
author: "Me"
fontsize: 12pt
documentclass: scrartcl
output:
  bookdown::pdf_document2:
    toc: true
    fig_caption: true
    keep_tex: true
---

# Introduction

```{r plot, dev="tikz"}
plot(rnorm(50))
``

Beginning of generated tex file (plot-1.tex):

% Created by tikzDevice version 0.12.3 on 2019-06-16 16:09:40
% !TEX encoding = UTF-8 Unicode
\documentclass[10pt]{article}

Desired/expected beginning of plot-1.tex:

% Created by tikzDevice version 0.12.3 on 2019-06-16 16:09:40
% !TEX encoding = UTF-8 Unicode
\documentclass[12pt]{scrartcl}

Solution

  • I think I figured it out:

    My problem was that while using RMarkdown the options tikzDocumentDeclaration, tikzLatexPackages ... (nearly all options for tikzDevice) were not set automatically. When you use knitr the options for tikzDevice get set up in the process of splitting up markup and code chunks from the source file. With RMarkdown there is no LaTeX code to extract and use with tikz because pandoc generates it after the graphic is rendered. So one can either define the tikz... options manually or use the chunk option external=FALSE like user2554330 suggested.

    Example minimal_knitr.Rnw:

    \documentclass[fontsize=12pt]{scrartcl}
    \usepackage[utf8]{inputenc}
    \usepackage[T1]{fontenc}
    \usepackage{lmodern}
    \begin{document}
    
    <<r plot, dev='tikz', echo=FALSE>>=
    plot(rnorm(50))
    @
    
    \end{document}