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)?
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.tikzcan be achieved like this: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 withgetOption("tikzLatexPackages"). Also note that you have to escape\in the R strings.The second important part is to set
standAlone = TRUEif 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
optionsto set fonts in a different way.