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)

FAQs

Using Fonts More Easily in R Graphs? ›

Now a new solution, the showtext package, is able to support more font formats and more graphics devices, and avoids using external software such as Ghostscript. showtext makes it even easier to use various types of fonts (TrueType, OpenType, Type 1, web fonts, etc.) in R graphs.

How do I get more fonts in R? ›

5 steps to import new fonts in R
  1. Download the new fonts online. ...
  2. Open the downloaded TTF (True Type font) file (in the zip folder) ...
  3. Open a new R session and install the extrafonts package. ...
  4. Import the new fonts into R. ...
  5. Load the fonts into plots. ...
  6. 4 Simple Steps to Fix Python-pip Not Recognized in cmd Issue.
Jan 9, 2021

Where does R look for fonts? ›

Default search paths will be assigned when package is loaded: For Windows, it is %windir%\Fonts , usually expanded into C:\Windows\Fonts. For Mac OS, default paths are /Library/Fonts and ~/Library/Fonts and their subdirectories. For Linux and other Unix-like OS, /usr/share/fonts , /usr/local/share/fonts , ~/.

What is the Font_add_google function? ›

This function will search the Google Fonts repository (https://fonts.google.com/) for a specified family name, download the proper font files, and then add them to sysfonts. This function requires the jsonlite and curl packages.

What is the best font for graphs? ›

When in doubt, use a sans-serif typeface for the text in your visualization. Roboto, Lato, Open Sans, Source Sans Pro, and Noto Sans are all good options and free to use. None of them will make your visualization stand out, but all of them will be readable and pleasant to look at.

What fonts can I use in R? ›

2023-12-08
R familyFont on WindowsFont on Unix
sansArialArial
serifTimes New RomanTimes
monoCourierCourier
symbolStandard Symbols LSymbol
Dec 8, 2023

How do I use different fonts in R? ›

In practice, you need to download and install the fonts in your system manually. This is usually done by opening the font file and clicking on the install button in the window that pops up. One of its advantages is that this procedure is required only once per font.

How do I increase the font size in R plot? ›

In order to change the font size of Base R plots, you can use the 'cex' argument in the plot function. This argument allows you to specify a numerical value which then scales the current font size by the specified amount.

What is the default font size in R? ›

For all of R's graphical devices, the default text size is 12 points but it can be reset by including a pointsize argument to the function that opens the graphical device.

What is the Windows fonts function in R? ›

The windowsFonts function can be used to list existing mappings and to define new mappings. The windowsFont function can be used to create a new mapping. Default mappings are provided for three device-independent font family names: "sans" for a sans-serif font, "serif" for a serif font and "mono" for a monospaced font.

What is the standard font for R markdown? ›

The RMarkdown output is based on LaTeX, and the default LaTeX font is Computer Modern.

What font is the Google logo? ›

Usage. The present Google logo is based on Product Sans. Slight modifications do exist in the logo compared to the typeface; the most noticeable is the slanted 'e'. The differences between the logo and Product Sans allows for distinction between the Google logotype and product name.

Which font is used in RStudio? ›

By default, RStudio on Windows uses the Courier New font.

What is the font size of R ggplot2 axis? ›

The base font size is 11 pts by default. You can change it with the base_size argument in the theme you're using. See the complete theme documentation for more high level options you can set. If you would like all plots within a session/document to use a particular base size, you can set it with theme_set() .

Top Articles
Latest Posts
Article information

Author: Merrill Bechtelar CPA

Last Updated:

Views: 6282

Rating: 5 / 5 (70 voted)

Reviews: 85% of readers found this page helpful

Author information

Name: Merrill Bechtelar CPA

Birthday: 1996-05-19

Address: Apt. 114 873 White Lodge, Libbyfurt, CA 93006

Phone: +5983010455207

Job: Legacy Representative

Hobby: Blacksmithing, Urban exploration, Sudoku, Slacklining, Creative writing, Community, Letterboxing

Introduction: My name is Merrill Bechtelar CPA, I am a clean, agreeable, glorious, magnificent, witty, enchanting, comfortable person who loves writing and wants to share my knowledge and understanding with you.