[r] Changing fonts in ggplot2

Once upon a time, I changed my ggplot2 font using using windowsFonts(Times=windowsFont("TT Times New Roman")) to change it. Now I can't get it off of this.

In trying to set family="" in ggplot2 theme() I can't seem to generate a change in fonts as I compile the MWE below with different font families.

library(ggplot2)
library(extrafont)
loadfonts(device = "win")

a <- 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="Comic Sans MS"))
#       family="CM Roman"))
#       family="TT Times New Roman"))
#       family="Sans"))
        family="Serif"))


print(a)
print("Graph should have refreshed")

R is returning a warning font family not found in Windows font database, but there was a tutorial I was following (if I can find it again I will update the link here) that said this was normal and not a problem. Also, somehow this worked at one point because my graph once used some arial or helvitica type font. I think this has always been a present warning even during the initial times migration.

UPDATE

when I run windowsFonts() my output is

$serif [1] "TT Times New Roman"

$sans [1] "TT Arial"

$mono [1] "TT Courier New"

But, this is after I ran font_import() so I can only conclude that my fonts are not being saved in the right place. The code that ran the font_import() request actually loads the libraries with:

LocalLibraryLocation <- paste0("C:\\Users\\",Sys.getenv("USERNAME"),"\\Documents","\\R\\win-library\\3.2");
    .libPaths(c(LocalLibraryLocation, .libPaths()))

This question is related to r ggplot2 fonts extrafont showtext

The answer is


To change the font globally for ggplot2 plots.

theme_set(theme_gray(base_size = 20, base_family = 'Font Name' ))

Another option is to use showtext package which supports more types of fonts (TrueType, OpenType, Type 1, web fonts, etc.) and more graphics devices, and avoids using external software such as Ghostscript.

# install.packages('showtext', dependencies = TRUE)
library(showtext)

Import some Google Fonts

# https://fonts.google.com/featured/Superfamilies
font_add_google("Montserrat", "Montserrat")
font_add_google("Roboto", "Roboto")

Load font from the current search path into showtext

# Check the current search path for fonts
font_paths()    
#> [1] "C:\\Windows\\Fonts"

# List available font files in the search path
font_files()    
#>   [1] "AcadEref.ttf"                                
#>   [2] "AGENCYB.TTF"                           
#> [428] "pala.ttf"                                    
#> [429] "palab.ttf"                                   
#> [430] "palabi.ttf"                                  
#> [431] "palai.ttf"

# syntax: font_add(family = "<family_name>", regular = "/path/to/font/file")
font_add("Palatino", "pala.ttf")

font_families()
#> [1] "sans"         "serif"        "mono"         "wqy-microhei"
#> [5] "Montserrat"   "Roboto"       "Palatino"

## automatically use showtext for new devices
showtext_auto() 

Plot: need to open Windows graphics device as showtext does not work well with RStudio built-in graphics device

# https://github.com/yixuan/showtext/issues/7
# https://journal.r-project.org/archive/2015-1/qiu.pdf
# `x11()` on Linux, or `quartz()` on Mac OS
windows()

myFont1 <- "Montserrat"
myFont2 <- "Roboto"
myFont3 <- "Palatino"

library(ggplot2)

a <- 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 = myFont1)) +
  annotate("text", 4, 30, label = 'Palatino Linotype',
           family = myFont3, size = 10) +
  annotate("text", 1, 11, label = 'Roboto', hjust = 0,
           family = myFont2, size = 10) 

## On-screen device
print(a) 

## Save to PNG 
ggsave("plot_showtext.png", plot = a, 
       type = 'cairo',
       width = 6, height = 6, dpi = 150)  

## Save to PDF
ggsave("plot_showtext.pdf", plot = a, 
       device = cairo_pdf,
       width = 6, height = 6, dpi = 150)  

## turn showtext off if no longer needed
showtext_auto(FALSE) 

Edit: another workaround to use showtext in RStudio. Run the following code at the beginning of the R session (source)

trace(grDevices::png, exit = quote({
    showtext::showtext_begin()
}), print = FALSE)

Edit 2: Starting from version 0.9, showtext can work well with the RStudio graphics device (RStudioGD). Simply call showtext_auto() in the RStudio session and then the plots will be displayed correctly.


Late to the party, but this might be of interest for people looking to add custom fonts to their ggplots inside a shiny app on shinyapps.io.

You can:

  1. Place custom font in www directory: e.g. IndieFlower.ttf from here
  2. Follow the steps from here

This leads to the following upper section inside the app.R file:

dir.create('~/.fonts')
file.copy("www/IndieFlower.ttf", "~/.fonts")
system('fc-cache -f ~/.fonts')

A full example app can be found here.


A simple answer if you don't want to install anything new

To change all the fonts in your plot plot + theme(text=element_text(family="mono")) Where mono is your chosen font.

List of default font options:

  • mono
  • sans
  • serif
  • Courier
  • Helvetica
  • Times
  • AvantGarde
  • Bookman
  • Helvetica-Narrow
  • NewCenturySchoolbook
  • Palatino
  • URWGothic
  • URWBookman
  • NimbusMon
  • URWHelvetica
  • NimbusSan
  • NimbusSanCond
  • CenturySch
  • URWPalladio
  • URWTimes
  • NimbusRom

R doesn't have great font coverage and, as Mike Wise points out, R uses different names for common fonts.

This page goes through the default fonts in detail.


Examples related to r

How to get AIC from Conway–Maxwell-Poisson regression via COM-poisson package in R? R : how to simply repeat a command? session not created: This version of ChromeDriver only supports Chrome version 74 error with ChromeDriver Chrome using Selenium How to show code but hide output in RMarkdown? remove kernel on jupyter notebook Function to calculate R2 (R-squared) in R Center Plot title in ggplot2 R ggplot2: stat_count() must not be used with a y aesthetic error in Bar graph R multiple conditions in if statement What does "The following object is masked from 'package:xxx'" mean?

Examples related to ggplot2

Center Plot title in ggplot2 R ggplot2: stat_count() must not be used with a y aesthetic error in Bar graph Saving a high resolution image in R Change bar plot colour in geom_bar with ggplot2 in r Remove legend ggplot 2.2 Remove all of x axis labels in ggplot Changing fonts in ggplot2 Explain ggplot2 warning: "Removed k rows containing missing values" Error: package or namespace load failed for ggplot2 and for data.table In R, dealing with Error: ggplot2 doesn't know how to deal with data of class numeric

Examples related to fonts

How to import a new font into a project - Angular 5 Font Awesome 5 font-family issue How do I change the font color in an html table? How to add fonts to create-react-app based projects? Changing fonts in ggplot2 Webpack "OTS parsing error" loading fonts Failed to decode downloaded font Proper MIME type for .woff2 fonts Link a .css on another folder How can I fix the 'Missing Cross-Origin Resource Sharing (CORS) Response Header' webfont issue?

Examples related to extrafont

Changing fonts in ggplot2

Examples related to showtext

Changing fonts in ggplot2