Plot annotation in R-Markdown + tikzDevice

365 Views Asked by At

I'm preparing a presentation using R-Markdown + Beamer, and want every plot annotation to be typeset with a serif font.

Here's a minimal example (in order to run this, the code should be pasted in a .Rmd file and compiled with knitr):

---
title: An example
subtitle: which should work
output:
  beamer_presentation:
    theme: metropolis
header-includes:
  \usefonttheme[onlymath]{serif}
---

## A slide

```{r test, echo=FALSE, fig.height=3.2, fig.width=4, fig.align='center', dev='tikz', external=FALSE}
plot(2*pi*(0:19)/20, sin( 2*pi*(0:19)/20 ), xlab = '$x$', ylab='$\\sin(2\\pi x)$', pch=21, bg=rgb(0,.4,.7,.5), main='A plot using \\LaTeX', font.main=1)
```

In the generated plot, I expect the font annotations in the axes' numbering, plot title, etc, to be typeset with a serif font (the same fonts that appear in math annotations), but the actual output is typesetting with a sans-serif font. It is important that the rest of the document still typesets with sans-serif fonts.

1

There are 1 best solutions below

0
Martin Schmelzer On

That is because the plots are compiled in seperate tex files. To change anything about the plots you should change the tikzLatexPackages option. The default is

options(
tikzLatexPackages = c(
    "\\usepackage{tikz}",
    "\\usepackage[active,tightpage]{preview}",
    "\\PreviewEnvironment{pgfpicture}",
    "\\setlength\\PreviewBorder{0pt}")
),
tikzXelatexPackages = c(
    "\\usepackage{tikz}\n",
    "\\usepackage[active,tightpage,xetex]{preview}\n",
    "\\usepackage{fontspec,xunicode}\n",
    "\\PreviewEnvironment{pgfpicture}\n",
    "\\setlength\\PreviewBorder{0pt}\n"
),
tikzLualatexPackages = c(
    "\\usepackage{tikz}\n",
    "\\usepackage[active,tightpage,psfixbb]{preview}\n",
    "\\usepackage{fontspec,xunicode}\n",
    "\\PreviewEnvironment{pgfpicture}\n",
"\\setlength\\PreviewBorder{0pt}\n")
)

So adding \usefonttheme[onlymath]{serif} to that first option should do it.

You can find more info on this on page 6 of the tikzDevice manual.

Note that it is also possible to include the tex code rather then the precompiled code. Though I had some issues with this approach in the past.