Search code examples
rfontsggplot2knitrcairo

knitr, cairo and ggplot2: font family 'Source Code Pro' not found in PostScript fontdatabase


Trying to fix the problem with otf-fonts I have (see How to use otf-font in ggplot2 graphics?) I found that I can use these fonts with ggplot2.

Using knitr with Rmd-files is okay:

---
title: "FontTest"
author: "me"
date: "22. April 2015"
output: html_document
---

```{r, echo=FALSE}
library(ggplot2)

ggplot(mtcars, aes(x=wt, y=mpg, color=factor(gear))) + geom_point() +
  ggtitle("Fuel Efficiency of 32 Cars") +
  xlab("Weight (x1000 lb)") + ylab("Miles per Gallon") +
  theme(text=element_text(size=16, family="Arial"))
```

But when I want to use LaTeX (Rnw-files) I get an error:

\documentclass{article}

\begin{document}
\SweaveOpts{concordance=TRUE}

<<>>=
Sys.setenv(LANG = "en")
library(ggplot2, quietly=TRUE)
@



<<>>=
ggplot(mtcars, aes(x=wt, y=mpg, color=factor(gear))) + geom_point() +
  ggtitle("Fuel Efficiency of 32 Cars") +
  xlab("Weight (x1000 lb)") + ylab("Miles per Gallon") +
  theme(text=element_text(size=16, family="Arial"))
@

\end{document}

Here's the error:

Writing to file test.tex
Processing code chunks with options ...
 1 : echo keep.source term verbatim (test.Rnw:6)
 2 : echo keep.source term verbatim (test.Rnw:13)
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

I'm using Mac OS X Mavericks.

Update

I found a work around using Cairo:

\documentclass{article}

\begin{document}



<<>>=
  Sys.setenv(LANG = "en")
library(ggplot2, quietly=TRUE)
library(Cairo)
@



<<dev='cairo_pdf'>>=

  ggplot(mtcars, aes(x=wt, y=mpg, color=factor(gear))) + geom_point() +
  ggtitle("Fuel Efficiency of 32 Cars") +
  xlab("Weight (x1000 lb)") + ylab("Miles per Gallon") +
  theme(text=element_text(size=16, family="Source Code Pro"))

@

\end{document}

But now I get lot's of warnings:

## Warning in grid.Call(LtextBounds, as.graphicsAnnot(x$label), x$x,x$y, :  font family 'Source Code Pro' not found in PostScript fontdatabase

I would like to avoid suppressing these warnings. So what do I have to do to get rid of these warnings?


Solution

  • I found the following solution:

    I use

    \usepackage{tikz}
    

    and

    <<plot, dev='tikz'>>
    

    in my .Rnw file. Doing it this way I get the fonts of my LaTeX project in my plots.