Fonts are tricky to work with in R. R and ggplot2 won’t recognize fonts outside of their default 3 fonts without a little work. Below are some one-time steps to have R recognize and register different fonts for bitmap and screen output (e.g. RStudio’s Plot Pane, .jpg, .png) and PDFs.

The instructions below are adapted from the ones in the extrafont vignette for a Windows machine. I’ve made some minor changes and omitted steps (e.g. GhostScript installation) in order for it to work on my computer.

Copy the following code snippets and paste/run in the console of your RStudio IDE.

Windows Bitmap and Screen Output

If you want to use fonts other than the basic ones R recognizes and want it to render in the RStudio Plot Pane and in an exported bitmap file like .jpg, .png:

  1. Install the extrafont package. This package helps identify the fonts on your machine and handles a lot of the details for you.
install.packages("extrafont")
  1. Load the extrafont library
library(extrafont)
  1. Run the font import function so that R can find and save information about fonts installed on your system. This step may take a while. Maybe now’s a good time to go on a coffee break.
font_import()
  1. Register the fonts for Windows.
loadfonts("win")

Test

Let’s test it! See if this code will produce a plot with the following font in your plot pane.

library(ggplot2)

my.plot <- 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"))

print(my.plot)

Now see if you can save it as a .jpg. Change the file path or file name to one that works for you.

ggsave("T:/2020November/christy/my_plot.jpg", plot = my.plot, width = 4, height = 4)

PDFs

After completing the steps in Windows Bitmap and Screen Output, you also have the option of exporting your plot with custom font to PDF but it will require a special argument device = cairo_pdf when you use ggsave().

ggsave("T:/2020November/christy/my_plot.pdf", plot = my.plot,  width=4, height=4, device = cairo_pdf)

Font choices

To find the fonts available for you to use after setup:

# Vector of font family names
fonts()

# Show entire table
font.df <- fonttable()
View(font.df)