Search code examples
rggplot2fontssweavebeamer

Custom ggplot font with sweave and beamer


I wanted to use a custom font within my .Rnw beamer presentation. A minimal working example that reproduces the error is:

\documentclass{beamer}
\begin{document}
\begin{frame}[plain]
<<echo=FALSE>>= 
library(ggplot2)
library(extrafont)
@
\begin{figure}
\centering
<<label = test, fig=TRUE, include=FALSE, echo=FALSE, message=FALSE>>=
ggplot(mtcars, aes(x=wt, y=mpg)) + geom_point() +
  ggtitle("Fuel Efficiency of 32 Cars") +
  xlab("Weight (x1000 lb)") + ylab("Miles per Gallon") +
  theme_bw() +
  theme(text=element_text(family="Garamond", size=14))
@
\includegraphics[width=\textwidth]{test}
\end{figure}
\end{frame}
\end{document}

and the error message looks like this:

Writing to file test.tex
Processing code chunks with options ...
 1 : keep.source term verbatim (test.Rnw:6)
Registering fonts with R
 2 : keep.source term verbatim pdf  (label = test, test.Rnw:12)
Error in grid.Call.graphics(L_text, as.graphicsAnnot(x$label), x$x, x$y,  : 
  invalid font type
Calls: <Anonymous> ... drawDetails -> drawDetails.text -> grid.Call.graphics
In addition: There were 50 or more warnings (use warnings() to see the first 50)
Execution halted

But when I use the ggplot command in the console, everything looks fine.

Any help would be greatly appreciated.


Solution

  • Alright, I the problem was indeed that the font was not installed. But since I only used Garamond as an example and really wanted to use the otf font Fira Sans, I made use of the showtext package.

    Here's the code that works:

    \documentclass{beamer}
    \begin{document}
    \begin{frame}[plain]
    <<test, fig=TRUE, echo=FALSE, width=6, height=4>>=
    library(ggplot2)
    library(showtext)
    font.add.google("Fira Sans", "fira")
    showtext.auto()
    ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point() +
      ggtitle("Fuel Efficiency of 32 Cars") +
      xlab("Weight (x1000 lb)") + ylab("Miles per Gallon") +
      theme_bw() +
      theme(text = element_text(family = "fira"))
    @
    \end{frame}
    \end{document}