tikzDevice does not use LaTeX preamble when used in RMarkdown document

358 views Asked by At

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}
2

There are 2 answers

2
julianre On BEST ANSWER

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}
2
user2554330 On

I'm not sure you really want what you're asking for. The figure will be produced as a separate document containing nothing except the figure, which will be rendered as a PDF. The differences between scrartcl and article shouldn't matter for the figure, they matter for the document as a whole.

But if you really do need that document class, you get it by specifying options(tikzDocumentDeclaration = "\\documentclass[12pt]{scrartcl}") in an R chunk early in your document. When I do that I can see in the source that it worked, but the output looks pretty much the same as it did with the default class. It's also possible to specify this using chunk options, but there's unlikely to be any advantage to doing that.