Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Embedding fonts in ggplot2 charts in rmarkdown documents

I would like to use non-standard fonts in a ggplot2 chart which I then embed in an rmarkdown document, which get knitted into a PDF. My current workflow is to specify the font in the chart, then knit, then run extrafonts::embed_fonts on the created PDF. My question is: can I specify directly in the rmarkdown document that fonts should be embedded in the outputted PDF?

Minimal example:

---
title: "Untitled"
output: beamer_presentation
---

```{r}
library(extrafont)
library(ggplot2)
loadfonts()
qplot(iris$Sepal.Length) + theme_light(base_family = "CM Roman")
```

knitr::knit2pdf("test.rmd")
embed_fonts("test.pdf")
like image 700
user2987808 Avatar asked Apr 06 '16 13:04

user2987808


1 Answers

If you set the graphics device to "cairo_pdf" the fonts will be embedded. You can do this for individual chunks or for the whole document using knitr::opts_chunk$set

I used a really obviously different font below so that it was clear the fonts were really being set.

The package is called "extrafont" not "extrafonts"

---
title: "Untitled"
output: beamer_presentation
---

```{r, echo=FALSE, message = FALSE}
knitr::opts_chunk$set(warning=FALSE, message=FALSE, echo = FALSE, dev = "cairo_pdf")
```

```{r}
library(extrafont)
library(ggplot2)
loadfonts()
```


##

```{r, fig.width = 5}
qplot(iris$Sepal.Length) + theme_light(base_family = "Vladimir Script")
```
like image 87
Andrew Avatar answered Sep 18 '22 01:09

Andrew