Using showtext in knitr

July 20, 2014

(This article was first published on Yixuan's Blog - R, and kindly contributed to R-bloggers)

Thanks to the issue report by
yufree and Yihui’s
kind work,
from version 1.6.10 (development version), knitr starts to support using
to change fonts in R plots. To demonstrate its usage, this document
itself serves as an example. (Rmd source code)

We first do some setup work, mainly about setting options that control
the appearance of the plots. Notice that if you create plots in PNG
format (the default format for HTML output), it is strongly recommended
to use the CairoPNG device rather than the default png, since
the latter one could produce quite ugly plots when using showtext.

```{r setup}
knitr::opts_chunk$set(dev="CairoPNG", fig.width=7, fig.height=7, dpi = 72)
options(digits = 4)

Then we can load showtext package and add fonts to it. Details about
font loading are explained in the
introduction document
of showtext and also in the help topic ?sysfonts::font.add.
While searching and adding fonts may be a tedious work,
package sysfonts (which showtext depends on)
provides a convenient function to automatically download
and use fonts from the Google Fonts repository
The first parameter is the font name in Google Fonts and the second one is
the family name that will be used in R plots.

```{r fonts, message=FALSE}
library(showtext)"Lobster", "lobster")

After adding fonts, simply set the fig.showtext option in the code block
where you want to use showtext, and then specify the family name you
just added.

```{r fig.showtext=TRUE, fig.align='center'}
plot(1, pch = 16, cex = 3)
text(1, 1.1, "A fancy dot", family = "lobster", col = "steelblue", cex = 3)

To leave a comment for the author, please follow the link and comment on their blog: Yixuan's Blog - R. offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...

If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.


Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)