Yihui Xie
(xie@yihui.name / GitHub
/ Twitter) Department of Statistics, Iowa State University; interested in statistical computing and graphics; author of knitr, animation and a few other R packages.
Fonts play an important role in graphics. This article was motivated from a StackOverflow
post, and shows how to draw xkcd
style graphs in R using the Cairo package. Before
get started, you need to install the Humor Sans font (please Google it yourself).
Set up fonts for R
After the font has been installed, we can tell Cairo to use it:
Draw it
Now we use the CairoPNG() device to save a plot. Because I’m using knitr, I only need to
specify the chunk option dev='CairoPNG' instead of really opening the device in the code below.
There are other ways to use additional fonts in R graphics, such as the tikzDevice and
extrafonts package; the former requires knowledge of LaTeX, and the latter is easier to use.
Acknowledgments
I thank Mark Bulling for the answer under the SO post. I used base R graphics instead of
ggplot2 as Mark did because I think the pen-and-paper model of base R is more natural for
drawing such a plot (the grammar of graphics seems to be overkill).
Session info
Since I’m not entirely sure about how Cairo performs under Windows; here is my R session info: