Brett Klamer

Better Fonts in LaTeX and R Graphics

Using TikZ and PGF

Default R PDF graphics look bad in LaTeX documents. You can change the fonts within R, but you are limited to a subset of fonts that R can import. To solve this, try using the tikzDevice R package. It will help create publisher quality output with all T1 embedded fonts based on the font choice within LaTeX. Make sure the pgf and preview packages are installed in LaTeX and the tikzDevice package is installed in R. Then simply add the following to your .Rnw document processed with knitr:

<<setup, include=FALSE, cache=FALSE>>=
library(knitr)
library(tikzDevice)
opts_chunk$set(dev = 'tikz') # automatically call the tikz graphics device
opts_chunk$set(dev.args = list(pointsize = 10)) # smaller graphics font
@

One downside is the extra layer of abstraction in LaTeX can create error messages that are even harder to decipher than usual.

I've created an example .Rnw file with lmodern fonts here. The PDF output should look like this (check the properties to see all T1 embedded lmodern fonts), and the graph should look like the image below.

R graph example using tikzDevice

Using Cairo

Cairo also produces better default graphics and is a good alternative if you have trouble with tikz. Unfortunately Cairo is limited to specific system fonts and I don't know of a good way to see a list of all supported fonts and their keywords. To use the Cairo graphics device you will need to install cairo, install the Cairo package in R, and add the following to your .Rnw document processed with knitr:

<<setup, include=FALSE, cache=FALSE>>=
library(knitr)
library(Cairo)
myfont <- "Garamond"
CairoFonts(regular = paste(myfont, "style = Regular", sep = ":"),
           bold = paste(myfont, "style = Bold", sep = ":"),
           italic = paste(myfont, "style = Italic", sep = ":"),
           bolditalic = paste(myfont, "style = Bold Italic, BoldItalic", sep = ":"))
pdf <- CairoPDF
opts_chunk$set(dev = 'CairoPDF')
@