Search code examples
rggplot2extrafontshowtext

Import font for female and male symbols in R using extrafont or showtext for ggplot2


I am trying to use the female ♀ and male ♂ symbols in a ggplot figure. When I load the extrafont package and run the required code, it does not work (similar to this post).

I am on a Mac OS X, version 10.11.6, using R for Mac OS X, version 3.5.2.

install.packages("extrafont")
library(extrafont)
extrafont::loadfonts(device="pdf")
extrafont::font_import(pattern="CALIBRI") #pattern that has the ♀ and ♂ symbols
#when I run this as font_import() alone fonts() is still empty

Error message:

Scanning ttf files in /Library/Fonts/, /System/Library/Fonts, ~/Library/Fonts/ ... Extracting .afm files from .ttf files... Error in data.frame(fontfile = ttfiles, FontName = "", stringsAsFactors = FALSE) : arguments imply differing number of rows: 0, 1

And double checking:

> fonts() #empty
 NULL
> fonttable() #empty
 data frame with 0 columns and 0 rows

Does anyone have any idea why this is happening and how I can get this to run properly?

Update:

Alternatively, I am able to get Calibri to load using a different package (see OP here). BUT, I still cannot get the ♀ and ♂ symbols to show up on my ggplot. Suggestions?

install.packages('showtext', dependencies = TRUE)
library(showtext)
font_add_google("Montserrat", "Montserrat")
font_add_google("Roboto", "Roboto")
font_paths() 
font_files()

# syntax: font_add(family = "<family_name>", regular = "/path/to/font/file")
font_add("Calibri", "calibri.ttf")
font_families()
showtext_auto() 

Solution

  • showtext should be able to do the job.

    library(ggplot2)
    library(showtext)
    showtext_auto()
    
    female = intToUtf8(9792)
    male = intToUtf8(9794)
    
    p = ggplot() +
        annotate("text", x = 1, y = 1, label = female, size = 20) +
        annotate("text", x = 2, y = 1, label = male, size = 20) +
        theme_bw(base_family = "sans")
    
    ## On screen
    x11()
    print(p)
    
    ## Save to PDF
    ggsave("symbol.pdf", p, width = 9, height = 6)
    

    enter image description here