Site icon R-bloggers

Using showtext in knitr

[This article was first published on Yixuan's Blog - R, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Thanks to the issue report by yufree and Yihui’s kind work, from version 1.6.10 (development version), knitr starts to support using showtext to change s 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 s to it. Details about loading are explained in the introduction document of showtext and also in the help topic ?syss::.add. While searching and adding s may be a tedious work, package syss (which showtext depends on) provides a convenient function .add.google() to automatically download and use s from the Google Fonts repository (http://www.google.coms). The first parameter is the name in Google Fonts and the second one is the family name that will be used in R plots.

```{r s, message=FALSE}
library(showtext)
.add.google("Lobster", "lobster")
```

After adding s, 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.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.