1

I'm trying to use sans serif fonts for the text in plots (ggplot2) made by R, within KOMA-book. Unfortunately I'm not very experienced in managing fonts and their families.

To keep things consistent, I want to use TikzDevice. The following example demonstrates the problem.

Where is the best place to define that the fonts should use sans? My attempt in the example doesn't work. I use XeLatex.

\documentclass{scrbook}
\begin{document}
<<settings, echo=FALSE>>=
library(knitr)
library(ggplot2)
opts_chunk$set(dev="tikz")
opts_chunk$set(fig.width=4.5)
opts_chunk$set(fig.height=3)
dev.args=list(family="sans")
@
\chapter{The first chapter}
This text should use the font defined in scrbook (serif).
<<, fig.cap="Here is the first figure", echo=FALSE>>=
p <- ggplot()
p <- p + geom_abline(intercept=(0), slope=1, linetype="dashed")
p <- p + xlim(0, 10)
p <- p + ylim(0, 10)
p <- p + xlab("This should be serif")
p <- p + ylab("Also serif")
print(p)
@
\chapter{The second chapter}
This text should also be serif. But the second plot should have text sans serif.
<<, fig.cap="Here is the second figure", echo=FALSE>>=
p <- ggplot()
p <- p + geom_abline(intercept=(0), slope=1, linetype="dashed")
p <- p + xlim(0, 10)
p <- p + ylim(0, 10)
p <- p + xlab("This should be sans")
p <- p + ylab("Also sans")
p <- p + theme(text=element_text(family="sans"))
print(p)
@
This text should be serif.
\end{document}
1

tikzDevice uses the default document font. So if your document is in sans serif, put in the preamble of your document

\renewcommand{\familydefault}{\sfdefault}

and both text and tikz labels will be in sans serif.

But what if you want the text in serifed font, but tikz labels in sans (not that I recommend it)? Well, you can fool tikzDevice by setting sans serif in preamble, and redefining it after \begin{document}:

\renewcommand{\familydefault}{\sfdefault}
\begin{document}
\renewcommand{\familydefault}{\rmdefault}\normalfont

Since tikzDevice reads only the preamble of the document, it will use sans serif, while the rest will use serif.

1

I suggest using the floatrow package, by which you can set font preferences both globally and locally.

In the preamble, add \usepackage{floatrow}, to which you may pass default options for the fonts you want to use throughout the document. Then if you want to change the options for figure fonts you can at anytime call \floatsetup{font={sf}} and it will adjust accordingly.

Do note, however, that if you place your figures outside a float these settings will not apply to them.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.