Using Fonts More Easily in R Graphs (2024)

Yixuan Qiu

2024-03-02

  • Introduction
  • A QuickExample
  • The Usage
  • LoadingFonts
  • Working with R Markdown
  • CJK Fonts
  • Howshowtext Works
  • Compatibility with RStudio

Introduction

In many cases, using non-standard fonts in R graphs is not an easytask, especially for PDF devices. For example, creating PDF graphs withChinese characters may take a lot of extra work. Also, R users may haveinstalled various fonts in their systems, but for many graphics devicesthere is no direct and portable way to make use of those fonts.

The extrafont packagedeveloped by Winston Chang is onenice solution to this problem, which mainly focuses on using TrueTypefonts (.ttf) in PDF graphics device.

Now a new solution, the showtext package, is able tosupport more font formats and more graphics devices, and avoids usingexternal software such as Ghostscript. showtext makesit even easier to use various types of fonts (TrueType, OpenType, Type1, web fonts, etc.) in R graphs.

A Quick Example

Below is a quick example to show the functionality of theshowtext package.

library(showtext)## Loading Google fonts (https://fonts.google.com/)font_add_google("Gochi Hand", "gochi")font_add_google("Schoolbell", "bell")## Automatically use showtext to render textshowtext_auto()set.seed(123)hist(rnorm(1000), breaks = 30, col = "steelblue", border = "white", main = "", xlab = "", ylab = "")title("Histogram of Normal Random Numbers", family = "bell", cex.main = 2)title(ylab = "Frequency", family = "gochi", cex.lab = 2)text(2, 70, "N = 1000", family = "bell", cex = 2.5)

Using Fonts More Easily in R Graphs (1)

In this example we first load fonts that are available online throughGoogle Fonts, and then tell R torender text using showtext by calling theshowtext_auto() function. All the remaining part is exactlythe same as the usual plotting commands.

This example should work on most graphics devices, includingpdf(), png(), postscript(), andon-screen devices such as windows() on Windows andx11() on Linux.

The Usage

To create a graph using showtext, you simply do thefollowing:

  • (*) Load the font
  • Open the graphics device
  • (*) Claim that you want to use showtext to renderthe text
  • Plot
  • Close the device

Only the steps marked with (*) are new. If you want to useshowtext globally, you can call the functionshowtext_auto() once, and then all the devices after thatwill automatically use showtext to render text, as theexample in the beginning shows.

If you want to have finer control on which part of the code shoulduse showtext, functions showtext_begin()and showtext_end() will help. Only plotting functionsenclosed by this pair of calls will use showtext, andothers not. For example, to change the title font only, we can do:

library(showtext)font_add_google("Schoolbell", "bell")set.seed(123)hist(rnorm(1000), breaks = 30, col = "steelblue", border = "white", main = "Histogram of Normal Random Numbers", xlab = "", ylab = "Frequency")showtext_begin()text(2, 70, "N = 1000", family = "bell", cex = 2.5)showtext_end()

Using Fonts More Easily in R Graphs (2)

Loading Fonts

Loading font is actually done by packagesysfonts.

The easy way to load font into showtext is bycalling

font_add(family = "<family_name>", regular = "/path/to/font/file")

where family is the name that you assign to that font(so that later you can callpar(family = "<family_name>") to use this font inplotting), and regular is the path to the font file. Thatis to say, only knowing the “font name” is not sufficient to identifythe font, since the names are usually system dependent. On the contrary,font file is the entity that actually provides the character glyphs.

Usually the font files are located in some “standard” directories inthe system (for example on Windows it is typicallyC:\Windows\Fonts). You can use font_paths() tocheck the current search path or add a new one, and usefont_files() to list available font files in the searchpath.

Below is an example to load system fonts on Windows:

library(showtext)## HeiTi font for Chinese charactersfont_add("heiti", "simhei.ttf")## Constantia font with regular and italic font facesfont_add("constan", regular = "constan.ttf", italic = "constani.ttf")showtext_auto()library(ggplot2)p = ggplot(NULL, aes(x = 1, y = 1)) + ylim(0.8, 1.2) + theme(axis.title = element_blank(), axis.ticks = element_blank(), axis.text = element_blank()) + annotate("text", 1, 1.1, family = "heiti", size = 15, label = "\u4F60\u597D\uFF0C\u4E16\u754C") + annotate("text", 1, 0.9, label = 'Chinese for "Hello, world!"', family = "constan", fontface = "italic", size = 12)## On-screen devicex11()print(p)## PNG deviceggsave("load_fonts.png", width = 7, height = 4, dpi = 96)## turn off if no longer neededshowtext_auto(FALSE)

Using Fonts More Easily in R Graphs (3)

For other OS, you may not have the simhei.ttf font file,but there is no difficulty in using the alternatives. At presentfont_add() supports TrueType fonts(.ttf/.ttc) and OpenType fonts(.otf), and adding new font type is trivial as long asFreeType supports it.

Also, there are many free fonts available and accessible on the web,for instance the Google Fonts project (https://fonts.google.com/).sysfonts provides an interface to automaticallydownload and register those fonts through the functionfont_add_google(), as the example below shows.

Working with R Markdown

showtext can work with Rmarkdown/knitr nicely if youtake care of the following two points:

  1. Add a fig.showtext = TRUE option to the block where youuse showtext for graphs.
  2. Add a fig_retina = 1 option to the document header ifyou use HTML output. Without this option you may see figures with verysmall fonts.

Below is a minimal example of using showtext inRmarkdown:

---output: html_document: fig_retina: 1---```{r fig.showtext=TRUE}library(showtext)font_add_google("Lobster", "lobster")showtext_auto()plot(1, pch = 16, cex = 3)text(1, 1.1, "A fancy dot", family = "lobster", col = "steelblue", cex = 3)```

CJK Fonts

showtext includes an open source CJK (Chinese,Japanese, and Korean) font WenQuanYi MicroHei. If you just want to show CJK text in your graph, simply specifythe wqy-microhei family name in plotting functions.

Another option is to install the Source HanSans/Serif fontslocally using the following code:

library(showtext)font_install(source_han_serif())font_families()[1] "sans" "serif" "mono" "wqy-microhei" [5] "source-han-serif-cn"

See ?font_install and ?source_han for moredetails.

Using Fonts More Easily in R Graphs (4)

How showtext Works

showtext renders text by converting it intocolor-filled polygonal outlines (for vector graphics) or raster images(for bitmap and on-screen graphics). Therefore, the rendered text hasthe same appearance under all platforms. People who view the graph donot need to install the font that creates the graph. Of course as aprice, the actual text information is lost in this procedure.

The idea above can be better explained by the diagram below.

Using Fonts More Easily in R Graphs (5)

A more detailed introduction to the showtext packagecan be found in the R Journalarticle.

Compatibility with RStudio

Previously showtext did not work well with theRStudio graphics device (RStudioGD), but starting from version 0.9, thisissue has been fixed. Simply call showtext_auto() in theRStudio session and then the plots will be displayed correctly.

Using Fonts More Easily in R Graphs (2024)

References

Top Articles
Latest Posts
Article information

Author: Maia Crooks Jr

Last Updated:

Views: 6184

Rating: 4.2 / 5 (63 voted)

Reviews: 86% of readers found this page helpful

Author information

Name: Maia Crooks Jr

Birthday: 1997-09-21

Address: 93119 Joseph Street, Peggyfurt, NC 11582

Phone: +2983088926881

Job: Principal Design Liaison

Hobby: Web surfing, Skiing, role-playing games, Sketching, Polo, Sewing, Genealogy

Introduction: My name is Maia Crooks Jr, I am a homely, joyous, shiny, successful, hilarious, thoughtful, joyous person who loves writing and wants to share my knowledge and understanding with you.