R tikzdevice: How to use sans serif font

613 views Asked by At

I'm using ggplot in R to create plots, tikzdevice to save them and then latex to compile them in a larger document.

when I create a very simple plot, e.g.

require(ggplot2)
require(tikzDevice)

tikz("test.tikz", height = 4, width = 4)
ggplot(data = data.frame(x = c(1:3), y = c(1:3)), aes(x=x, y=y)) +
geom_point() +
theme(text = element_text(family = "sans", face = "bold"))
dev.off()

While I can change the size and the font face using the element_text options in theme, changing the font family doesn't work. I.e. the exported tikz does not contain the sans-serif command.

How can I export the graphic using sans-serif font for text (and particularly the axis labels)?

1

There are 1 answers

0
fry On

tikz() will output latex code. The fonts will be the ones specified in this latex document (which is great because that results in a consistent look).

Creating a standalone figure with sans-serif font that you can then render via pdflatex test.tikz can be achieved like this:

require(ggplot2)
require(tikzDevice)
options(tikzLatexPackages = 
      c(getOption("tikzLatexPackages"), 
        "\\renewcommand{\\familydefault}{\\sfdefault}\n")
      )

tikz("test.tikz", height = 4, width = 4, standAlone = TRUE)
   ggplot(data = data.frame(x = c(1:3), y = c(1:3)), aes(x=x, y=y)) +
   geom_point()
dev.off()

We pass in additional text that is written to the preamble via options. We need to add new options to the default options and not overwrite them, which is why we concatenate with getOption("tikzLatexPackages"). Also note that you have to escape \in the R strings.

The second important part is to set standAlone = TRUE if we want to render the figure on its own and not make it part of a larger document.

How to set fonts in a latex document I still find somewhat mysterious. My solution builds on this question. But you could pass in other latex commands via options to set fonts in a different way.