Changing fonts in RMarkdown PDFs

Changing the font of RMarkdown PDF body text.

By Cecina Babich Morrow in R

January 2, 2020

Note: this post has been edited on 2 August 2020 - there was a typo in the indenting of the YAML. Thank you to Henry Hankins for catching this!

Inspiration for this post

After learning how to change the fonts within a graph in R, I wanted to be able to change the fonts in the body of an RMarkdown to match. I specifically wanted to be able to knit an RMarkdown to PDF using the Source Sans Pro Google font, but these instructions should work for any Google font.

Cairo

To embed custom fonts in PDFs, you can use the Cairo graphics library. This library is installed with R, but if you are using a Mac, you do need to install XQuartz. To check if you are able to run Cairo, you can run capabilities():

capabilities()
##        jpeg         png        tiff       tcltk         X11        aqua 
##        TRUE        TRUE        TRUE        TRUE        TRUE        TRUE 
##    http/ftp     sockets      libxml        fifo      cledit       iconv 
##        TRUE        TRUE       FALSE        TRUE       FALSE        TRUE 
##         NLS       Rprof     profmem       cairo         ICU long.double 
##        TRUE        TRUE        TRUE        TRUE        TRUE        TRUE 
##     libcurl 
##        TRUE

If cairo shows up as TRUE, you are good to go.

YAML header

To use Cairo to change the font of your RMarkdown pdf, you can modify the YAML heading:

---
title: "New fancy font!"
header-includes:
   - \usepackage[default]{sourcesanspro}
   - \usepackage[T1]{fontenc}
mainfont: SourceSansPro
output:
  pdf_document
---

The \usepackage components of the header load Latex packages for your font (I am using Source Sans Pro in this example).

Chunk options

The final step to use the font in your knitted pdf is to set the graphical device to Cairo in your code chunk option. At the beginning of your RMarkdown, the first chunk should include code that looks something like this:

knitr::opts_chunk$set(echo = TRUE)

Add dev="cairo_pdf" as one of the arguments:

knitr::opts_chunk$set(echo = TRUE, dev="cairo_pdf")

You can read more about other chunk options here.

Posted on:
January 2, 2020
Length:
2 minute read, 316 words
Categories:
R
Tags:
R
See Also:
Bias-variance decomposition
brat and it's the same but it's a blog post so it's not
Least squares regression: Part 2
comments powered by Disqus