Site icon R-bloggers

How to use your favorite fonts in R charts

[This article was first published on Revolutions, 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.

Today's guest post comes from Winston Chang, a software developer at RStudio  ed.

When it comes to making figures in R, you can use any you like, as long as it's Helvetica, Times, or Courier. Using other s that are installed on your computer can seem an impossible task, especially if you want to save the output to PDF.

Fortunately, the extra package makes this process much easier. With it, you can create beautiful, professional-looking results like this:

When using s in PDF files, there are two challenges: First you must tell R that the is available to use. Next, you must embed the into the PDF file to make it render properly on another computer or printer that doesn't already have the .

Here's an example of what a PDF using Garamond might look like when it's not embedded, and printed or viewed on a device that lacks the . It will substitute some other in the place of Garamond:

Using extra in three easy steps

The first step is to install extra, and then import the s from your system into the extra database:

Installation

install.packages("extra")

library(extra)
_import()

You may see some warnings, but you should be able to ignore them. After the s are imported, you can view the available s by running s() or table():

s()
##  [1] "Andale Mono"                  "AppleMyungjo"                
##  [3] "Arial Black"                  "Arial"                       
##  [5] "Arial Narrow"                 "Arial Rounded MT Bold"       
##  [7] "Arial Unicode MS"             "Bangla Sangam MN"            
##  [9] "Brush Script MT"              "Comic Sans MS"               
## [11] "Courier New"                  "Georgia"                     
## [13] "Gujarati Sangam MN"           "Impact"        
##  ...

# This will show more detailed information about s
table()

Creating PDF files with s

Once you've imported the s from your system to the extra database, they must be registered with R as being available for the PDF output device. This must be run once in each R session where you want to use the s:

library(extra)
loads()
# If you want to output to .ps files instead of .pdf, use:
# loads(device="postscript")

After the s are registered with R's PDF device, you can create figures with them. Here's an example using base graphics:

pdf("plot_garamond.pdf", family="Garamond", width=4, height=4.5)

plot(mtcars$mpg, mtcars$wt, 
     main = "Fuel Efficiency of 32 Cars",
     xlab = "Weight (x1000 lb)",
     ylab = "Miles per Gallon")

dev.off()

Again, you may see some warnings, but they shouldn't cause any problems.

And with ggplot2:

library(ggplot2)
p <- ggplot(mtcars, aes(x=wt, y=mpg)) + geom_point() +
  ggtitle("Fuel Efficiency of 32 Cars") +
  xlab("Weight (x1000 lb)") + ylab("Miles per Gallon") +
  theme_bw() +
  theme(text=element_text(family="Garamond", size=14))

ggsave("ggplot_garamond.pdf", p, width=3.5, height=3.5)

Embedding s

Extra uses GhostScript, a free PostScript interpreter, to embed the s. You'll need to make sure it's installed on your computer (note that GhostScript is not an R package). If you're using Windows, you'll also need to tell R where the Ghostscript executable is:

# For Windows - in each session
# Adjust the path to match your installation of Ghostscript
Sys.setenv(R_GSCMD = "C:/Program Files/gs/gs9.05/bin/gswin32c.exe")

To embed the s, use embed_s():

#  If you don't specify 'outfile', it will overwrite the original file
embed_s("plot_garamond.pdf", outfile="plot_garamond_embed.pdf")

embed_s("ggplot_garamond.pdf", outfile="ggplot_garamond_embed.pdf")


If you have many PDF figures that are being put into a single PDF document, it can be more space-efficient to embed the s in the final document, instead of in each figure. That way, there will be a single copy of the in the document instead of one for each figure.

Using Computer Modern (with math symbols)

If you are creating a document with TeX, there's a good chance that your document uses the default , Computer Modern. Some R users use TikZ (with the tikzDevice package) to create figures that use Computer Modern, to match the appearance of the document text.

With extra, you can use Computer Modern in a PDF figure without using TikZ. This is done by installing the package called cm. (Extra supports special packages that contain a PostScript type 1 stored in a particular way.)

_install("cm")

It will ask you to download the cm package from CRAN, and then it will import the into the extra database. Once that's done, run loads() to register the s with R's PDF device. If you run s(), they will be listed as “CM Roman”, “CM Sans”, and “CM Typewriter”.

Now you can create PDF figures with these s:

# Base graphics
pdf("plot_cm.pdf", family="CM Roman", width=5.5, height=5)

curve(dnorm, from=-3, to=3, main="Normal Distribution")
text(x=0, y=0.1, cex=1.5, expression(italic(y == frac(1, sqrt(2 * pi)) *
                                     e ^ {-frac(x^2, 2)} )))

dev.off()
embed_s("plot_cm.pdf", outfile="plot_cm_embed.pdf")

And with ggplot2:

# ggplot2
exp_text <- "italic(y == frac(1, sqrt(2 * pi)) * e ^ {-frac(x^2, 2)} )"

p <- ggplot(data.frame(x=c(-3,3)), aes(x=x)) + ggtitle("Normal Distribution") +
  stat_function(fun=dnorm, geom="line") +
  theme_bw() +
  theme(text=element_text(family="CM Roman")) +
  annotate("text", x=0, y=0.1, label=exp_text, parse=TRUE, family="CM Roman")

ggsave("ggplot_cm.pdf", p, width=4, height=3.5)
embed_s("ggplot_cm.pdf", outfile="ggplot_cm_embed.pdf")

Note that packages installed this way can only be used for PDF and PostScript figures generated with R. They aren't available for on-screen output, nor are they available for use for other programs.

Output to bitmap files (PNG, TIFF)

If you output graphics using Linux or Mac, you are probably using the Cairo device or Quartz output devices. With these output devices, system s are generally available without having to jump through any of these hoops.

On Windows, however, the default output device, “windows”, requires registering s to work with it. Usually this is a bit of a chore, but extra makes it easy. After the s have been imported:

loads(device = "win")

This registers the s with R's windows output device. Then you can make bitmap figures with system s on screen, or saved to a file.

Experimental support for OTF and TTC files

The released version of extra can only import TTF (TrueType) s. It doesn't work with with OTF (OpenType) and TTC (TrueType collection) files, which are increasingly common. There is an in-development version supports these file formats. It can be installed from GitHub, using the devtools package. This requires that you have a C compiler installed on your system, and the proper R development environment set up:

library(devtools)
install_github("Rttf2pt1", "wch")
install_github("extra", "wch")

Once it's installed, import the s as before:

library(extra)
_import()

Support for these file types is experimental. If you find any issues, please report them on the issues page for extra:

https://github.com/wch/extra/issues

Learning more

For more information, see:

  • extra project page
  • cm project page
  • A writeup by Paul Murrell about using symbol s with R. (The cm package should take care of the issues.)

The current version of extra is 0.11. Previous version had problems with character spacing when you use hyphens and minus signs, but it should be fixed in the latest version.

Winston Chang graduated in 2012 from Northwestern University with a PhD in Psychology. He is now a software developer for RStudio, working primarily on developing the ggplot2 package for data visualization. He created and maintains the "Cookbook for R" website, and is the author of the forthcoming book "R Graphics Cookbook", to be published by O'Reilly Media.

To leave a comment for the author, please follow the link and comment on their blog: Revolutions.

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.