14.7 Using Fonts in Windows Bitmap or Screen Output

14.7.1 Problem

You are using Windows and want to use fonts other than the basic ones provided by R for bitmap or screen output.

14.7.2 Solution

The extrafont package can be used to create bitmap or screen output. The procedure is similar to using extrafont with PDF files (Recipe 14.6). The one-time setup is almost the same, except that Ghostscript is not required:

install.packages("extrafont")
library(extrafont)

# Find and save information about fonts installed on your system
font_import()

# List the fonts
fonts()

After the one-time setup is done, there are tasks you need to do in each R session:

library(extrafont)

# Register the fonts for Windows
loadfonts("win")

Finally, you can create each output file or display graphs on screen, as in Figure 14.5:

library(ggplot2)

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

ggsave("myplot.png", width = 4, height = 4, dpi = 300)
PNG output with font Georgia Italic

Figure 14.5: PNG output with font Georgia Italic

14.7.3 Discussion

Fonts are handled in a completely different way for bitmaps than they are for PDF files.

On Windows, for bitmap output it is necessary to register each font manually with R (extrafont makes this much easier). On Mac OS X and Linux, the fonts should already be available for bitmap output; it isn’t necessary to register them manually.