Search code examples
rknitrr-markdownbeamertikzdevice

Beamer: use the document main font in plots when using tikzDevice


I am trying to create a Rmd document template that uses the tikz device for its plot outputs. Usually, when doing the same in a Rweave (sweave) document, the font in the tikz graphics is the same as in the document because tikz takes over the document preamble where the font is set.

In Rmarkdown I can only achieve this when I set the chunk option external = F. This way, the tikz grpahics are not pre-compiled.

But I want to use this externality and still have the same font in graphics in the final pdf output.

Heres is a simple beamer presentation that uses tikz. How can I make the plots have the same sans font?

---
title: "TikZ"
author: "Martin Schmelzer"
date: "10/9/2017"
output: beamer_presentation
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE, dev = "tikz")
```

## Slide with Plot

```{r pressure}
plot(pressure)
```

Solution

  • You need to tell tikzDevice that you are using the beamer class, otherwise it does not know and will assume a normal \documentclass{article}. If you take a look at the help page ?tikzDevice::tikz, you may see the document class can be declared through the option tikzDocumentDeclaration, e.g.,

    options(tikzDocumentDeclaration = '\\documentclass{beamer}')
    

    Full example (I decreased the plot size so you can see the font style more clearly in the plot):

    ---
    title: "TikZ"
    author: "Martin Schmelzer"
    date: "10/9/2017"
    output: beamer_presentation
    ---
    
    ```{r setup, include=FALSE}
    options(tikzDocumentDeclaration = '\\documentclass{beamer}')
    knitr::opts_chunk$set(echo = FALSE, dev = "tikz")
    ```
    
    ## Slide with Plot
    
    ```{r pressure, fig.width=5, fig.height=4}
    plot(pressure)
    ```
    

    a plot in beamer and R Markdown