• Stars
    star
    304
  • Rank 137,274 (Top 3 %)
  • Language
    R
  • Created over 12 years ago
  • Updated almost 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Tools for using fonts in R graphics

extrafont

The extrafont package makes it easier to use fonts other than the basic PostScript fonts that R uses. Fonts that are imported into extrafont can be used with PDF or PostScript output files. On Windows, extrafont will also make system fonts available for bitmap output.

There are two hurdles for using fonts in PDF (or Postscript) output files:

  • Making R aware of the font and the dimensions of the characters.
  • Embedding the fonts in the PDF file so that the PDF can be displayed properly on a device that doesn't have the font. This is usually needed if you want to print the PDF file or share it with others.

The extrafont package makes both of these things easier.

Presently it allows the use of TrueType fonts with R, and installation of special font packages. Support for other kinds of fonts will be added in the future. It has been tested on Mac OS X 10.7 and Ubuntu Linux 12.04 and Windows XP.

The instructions below are written for PDF files, although the information also applies to PostScript files.

If you want to use the TeX Computer Modern fonts in PDF files, also see the fontcm package.

Using extrafont

Requirements

You must have Ghostscript installed on your system for embedding fonts into PDF files.

Extrafont requires the extrafontdb package to be installed. extrafontdb contains the font database, while this package contains the code to install fonts and register them in the database.

It also requires the Rttf2pt1 package to be installed. Rttf2pt1 contains the ttf2pt1 program which is used to read and manipulate TrueType fonts. It is in a separate package for licensing reasons.

Install extrafont from CRAN will automatically install extrafontdb and Rttf2pt1:

install.packages('extrafont')
library(extrafont)

To use extrafont in making graphs, you'll need to do the following:

  • Import fonts into the extrafont database. (Needs to be done once)
  • Register the fonts from the extrafont database with R's PDF (or PostScript) output device. (Needs to be done once per R session)
  • Create the graphics that use the fonts.
  • Embed the fonts into the PDF file. (Needs to be done for each file)

Import fonts into the extrafont database

First, import the fonts installed on the system. (This only works with TrueType fonts right now.)

font_import()
# This tries to autodetect the directory containing the TrueType fonts.
# If it fails on your system, please let me know.

This does the following:

  • Finds the fonts on your system.
  • Extracts the FontName (like ArialNarrow-BoldItalic).
  • Extracts/converts a PostScript .afm file for each font. This file contains the font metrics, which are the rectangular dimensions of each character that are needed for placement of the characters. These are not the glyphs, which the curves defining the visual shape of each character. The glyphs are only in the .ttf file.
  • Scan all the resulting .afm files, and save a table with information about them. This table will be used when making plots with R.
  • Creates a file Fontmap, which contains the mapping from FontName to the .ttf file. This is required by Ghostscript for embedding fonts.

You can view the resulting table of font information with:

# Vector of font family names
fonts()

# Show entire table
fonttable()

If you install new fonts on your computer, you'll have to run font_import() again.

Register the fonts with the PDF output device

The next step is to register the fonts in the afm table with R's PDF (or PostScript) output device. This is needed to create PDF files with the fonts. As of extrafont version 0.13, this must be run only in the first session when you import your fonts. In sessions started after the fonts have been imported, simply loading the package with library(extrafont) this step isn't necessary, since it will automatically register the fonts with R.

# Only necessary in session where you ran font_import()
loadfonts()
# For PostScript output, use loadfonts(device="postscript")
# Suppress output with loadfonts(quiet=TRUE)

Create figures with the fonts

Here's an example of PDFs made with base graphics and with ggplot2. These examples use the font Impact, which should be available on Windows and Mac. (Use fonts() to see what fonts are available on your system)

pdf("font_plot.pdf", family="Impact", width=4, height=4)
plot(mtcars$mpg, mtcars$wt, 
     main = "Fuel Efficiency of 32 Cars",
     xlab = "Weight (x1000 lb)",
     ylab = "Miles per Gallon")
dev.off()


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(text=element_text(size=16, family="Impact"))

ggsave("font_ggplot.pdf", plot=p,  width=4, height=4)

The first time you use a font, it may throw some warnings about unknown characters. This should be harmless, but if it causes any problems, please report them.

Embed the fonts

After you create a PDF output file, you should embed the fonts into the file. There are 14 PostScript base fonts never need to be embedded, because they are included with every PDF/PostScript renderer. All other fonts should be embedded into the PDF files.

First, if you are running Windows, you may need to tell it where the Ghostscript program is, for embedding fonts. (See Windows installation notes below.)

# Needed only on Windows - run once per R session
# Adjust the path to match your installation of Ghostscript
Sys.setenv(R_GSCMD = "C:/Program Files/gs/gs9.05/bin/gswin32c.exe")

As the name suggests, embed_fonts() will embed the fonts:

embed_fonts("font_plot.pdf", outfile="font_plot_embed.pdf")
embed_fonts("font_ggplot.pdf", outfile="font_ggplot_embed.pdf")
# If outfile is not specified, it will overwrite the original file

To check if the fonts have been properly embedded, open each of the PDF files with Adobe Reader, and go to File->Properties->Fonts. If a font is embedded, it will say "Embedded Subset" by the font's name; otherwise it will say nothing next to the name.

With Adobe Reader, if a font is not embedded, it will be substituted by another font. This provides a way to see what your PDF will look like on printer or computer that doesn't have the font installed. Other PDF viewers may behave differently. For example, the Preview application on Mac OS X will automatically use system fonts to display non-embedded fonts -- this makes it impossible to tell whether the font is embedded in the PDF.

On Linux you can also use evince (the default PDF viewer) to view embedded fonts. Open the file and go to File->Properties->Fonts. If a font is embedded, it will say "Embedded subset"; otherwise it will say "Not embedded".

If you are putting multiple PDF figures into a single document, it is more space-efficient to not embed fonts in each figure, but instead embed the font in the final PDF document.

Windows bitmap output

extrafont also makes it easier to use fonts in Windows for on-screen or bitmap output.

# Register fonts for Windows bitmap output
loadfonts(device="win")

ggplot(mtcars, aes(x=wt, y=mpg)) + geom_point() +
  ggtitle("Title text goes here") +
  theme(plot.title = element_text(size = 16, family="Georgia", face="italic"))

ggsave("fonttest-win.png")

Since the output is a bitmap file, there's no need to embed the fonts.

Font packages

Extrafont supports font packages, which contain fonts that are packaged in a particular way so that they can be imported into extrafont. These fonts are installed as R packages; they are not installed for the computer operating system. Fonts that are installed this way will be available only for PDF or PostScript output. They will not be available for on-screen or bitmap output, which requires that the font be installed for operating system, not just with R and extrafont.

Presently extrafont supports only font packages with PostScript Type 1 fonts.

See the fontcm package containing Computer Modern fonts for an example.


Installation notes

Rttf2pt1

The source code for the utility program ttf2pt1 is in the package Rttf2pt1. CRAN has pre-compiled Windows and Mac OS X binaries. For other platforms, and when installing from source, it will be compiled on installation, so you need a build environment on your system.

Windows installation notes

In Windows, you need to make sure that Ghostscript is installed.

In each R session where you embed fonts, you will need to tell R where Ghostscript is installed. For example, when Ghostscript 9.05 is installed to the default location, running this command will do it (adjust the path for your installation):

Sys.setenv(R_GSCMD="C:/Program Files/gs/gs9.05/bin/gswin32c.exe")

Resetting the font database

To reset the extrafont database, reinstall the extrafontdb package:

install.packages("extrafontdb")

More Repositories

1

r-source

Read-only mirror of R source code from https://svn.r-project.org/R/, updated hourly. See the build instructions on the wiki page.
R
1,053
star
2

rgcookbook

R Graphics Cookbook
R
280
star
3

webshot

Take screenshots of web pages from R
JavaScript
227
star
4

latexsheet

LaTeX cheat sheet
TeX
156
star
5

harbor

An R package for controlling docker containers on local and remote hosts
R
100
star
6

r-debug

Dockerfile with several builds of R for memory/thread debugging
Dockerfile
88
star
7

chatstream

Example Shiny for Python app which talks to the OpenAI API
Python
75
star
8

SendText

A Sublime Text plugin to send text to a terminal or other program
JavaScript
70
star
9

shiny-jsdemo

Demo of Shiny integration with third-party Javascript libraries
R
54
star
10

staticimports

Statically import R functions into packages and projects
R
54
star
11

shiny-wordle

Wordle in Shiny
R
48
star
12

downloader

R package for downloading files with https
R
32
star
13

shiny-gridster

Add-on package for using the Gridster library with Shiny
R
25
star
14

retirement-simulation-dashboard

Retirement Simulation Dashboard, built with Quarto and Shiny for Python
25
star
15

fontcm

Computer Modern font package for R
R
22
star
16

testapp

Shiny apps for testing
R
20
star
17

bisectr

Bisect tools for R
R
16
star
18

vtest

Visual test system for R packages
R
13
star
19

Rttf2pt1

R package for ttf2pt1- to be used with extrafont package
C
12
star
20

2020-01-later

Materials for talk about later and async at 2020 RStudio Conf
R
11
star
21

shinylive-example

Example of Shinylive application deployed on GitHub Pages
Python
11
star
22

qstack

Fast basic data structures for R
R
11
star
23

rspeed

R speed tests
C
10
star
24

gcookbook

Data sets for R Graphics Cookbook
R
10
star
25

movies

Movie explorer Shiny app
R
10
star
26

vagrant-ec2-r

Vagrant config for Ubuntu VM with R, under EC2
Ruby
10
star
27

shinycomponent

Example Shiny component
TypeScript
9
star
28

s3ops

S3 dispatch on operators
R
9
star
29

extrafontdb

Package that holds the database for the fonts package for R
R
9
star
30

dockr

Docker files related to R
R
9
star
31

shiny-reactlog-examples

Example data from Shiny reactlog
R
5
star
32

shiny-quarto

Quarto extension for building Shiny apps
5
star
33

string_builder

Performance tests of various ways of building strings in R
R
5
star
34

sassy

A new Sass package for R
JavaScript
5
star
35

shiny_demo

Shiny app for looking at crandb data
R
4
star
36

send-custom-message

Custom server-to-client message example app for R shiny
R
4
star
37

shiny-handsontable

Handsontable bindings for Shiny
JavaScript
3
star
38

image-output

Image output example for R Shiny
R
3
star
39

shiny-disconnect

Shinyapps.io disconnection test app
R
2
star
40

r-devel-nix

R-devel for Nix
Nix
2
star
41

shiny_express_doc

Introduction to Shiny Express
Lua
2
star
42

badadd

Example of operator overloading problem in R
2
star
43

flang-webr

Nix flake for flang-webr
Nix
2
star
44

custom-input-binding

Custom input binding demo app for R Shiny
JavaScript
2
star
45

shiny-slickgrid

Package for using Slickgrid with Shiny
JavaScript
2
star
46

python-wasm-demo

Python wasm demo
Python
2
star
47

s3methodtest

Package for showing S3 method warning
R
1
star
48

envtest

Environment test package for R
R
1
star
49

gtable-vtest

Visual test results for gtable
1
star
50

rcpptest

Experimenting with rcpp
C++
1
star
51

pyshiny-bootswatch-example

Example Shiny for Python application using a Bootswatch theme
Python
1
star
52

2020-vote-count

Plots of 2020 vote count
HTML
1
star
53

ggplot2-vtest

Visual test results for ggplot2
1
star
54

ranked-choice-vote

Ranked-choice vote calculation script
R
1
star
55

namespace-cpp-test

Attempt to create a C++ namespace clash
C++
1
star
56

pkgClosure

Tests of closures that span packages in R
R
1
star
57

movie_import

Scripts for importing and converting movie files from digital cameras
Python
1
star
58

animated-terminal

Animated Terminal JS component
JavaScript
1
star
59

focuswatch

Program for monitoring which application has focus on macOS
Objective-C
1
star
60

examplepackage

An example R package
R
1
star