Add font to R that is not in extrafonts library

12,710

Solution 1

First you get the font you want and install it on your system. Nothing to do with R. Test if the font works by checking in any regular program like MS Word or something.

Then open R, load extrafont package and import the font that you installed. I think it only works with .ttf fonts for now.

library(extrafont)
font_import(pattern="Roboto")

If this works, then this step will add those fonts to the extrafontdb. You will see something like this...

> font_import(pattern="Roboto",prompt=FALSE)
Scanning ttf files in C:\windows\Fonts ...
Extracting .afm files from .ttf files...
C:\Windows\Fonts\Roboto-Black.ttf => C:/R/R-3.5.1/library/extrafontdb/metrics/Roboto-Black
C:\Windows\Fonts\Roboto-BlackItalic.ttf => C:/R/R-3.5.1/library/extrafontdb/metrics/Roboto-BlackItalic
...
C:\Windows\Fonts\RobotoCondensed-Regular.ttf => C:/R/R-3.5.1/library/extrafontdb/metrics/RobotoCondensed-Regular
Found FontName for 30 fonts.
Scanning afm files in C:/R/R-3.5.1/library/extrafontdb/metrics
Writing font table in C:/R/R-3.5.1/library/extrafontdb/fontmap/fonttable.csv
Writing Fontmap to C:/R/R-3.5.1/library/extrafontdb/fontmap/Fontmap...

This is a one time thing. Once imported, it is available within R from then on. All you have to do is run below.

library(extrafont)
# for windows
windowsFonts(sans="Roboto")
loadfonts(device="win")
loadfonts(device="postscript")

Now the defaults should have changed.

plot(x=1:5,y=1:5)

enter image description here

ggplot has base_family which needs to be changed and family argument for text geoms.

library(ggplot2)
p <- ggplot(data.frame(x=1:5,y=1:5),aes(x,y))+
  geom_point()+
  geom_text(aes(label=y),nudge_x=0.5,family="Roboto")+
  theme_bw(base_family="Roboto")
p

Exporting raster images should work too.

ggsave("plot.png",p)

enter image description here

PDFs are a pain. They have an extra family argument. There is also something about embedding and stuff. See link below.

ggsave("plot.pdf",p,family="Roboto")

All the info you need is here.

Solution 2

The solution using the showtext package:

library(showtext)
## Add the font with the corresponding font faces
font_add("national2",
    regular = "National2CondensedTest-Regular.otf",
    bold = "National2CondensedTest-Bold.otf")
## Automatically use showtext to render plots
showtext_auto()

library(ggplot2)
p = ggplot(NULL, aes(x = 1, y = 1)) + ylim(0.8, 1.2) +
    annotate("text", 1, 1.1, label = "National 2 Condensed Bold",
             family = "national2", fontface = "bold", size = 15) +
    annotate("text", 1, 0.9, label = "National 2 Condensed Regular",
             family = "national2", size = 12) +
    theme(axis.title = element_blank(),
          axis.ticks = element_blank(),
          axis.text  = element_blank())

ggsave("test.pdf", p, width = 8, height = 4)

Below is the generated plot:

Output of the plot using showtext

I used a test version of the font files, and in your case simply change the regular and bold arguments to the actual paths of your files.

Share:
12,710
Canovice
Author by

Canovice

Second year Stanford graduate student, studying Statistics and Data Science. Plan to make it big in sports analytics.

Updated on June 05, 2022

Comments

  • Canovice
    Canovice almost 2 years

    After installing R's extrafonts library, and checking what fonts it had to offer, it came up with this list:

    [1] ".Keyboard"               "System Font"             "Andale Mono"             "Apple Braille"           "AppleMyungjo"           
    [6] "Arial Black"             "Arial"                   "Arial Narrow"            "Arial Rounded MT Bold"   "Arial Unicode MS"       
    [11] "Batang"                  "Bodoni Ornaments"        "Bodoni 72 Smallcaps"     "Bookshelf Symbol 7"      ""                       
    [16] "Brush Script MT"         "Calibri"                 "Calibri Light"           "Cambria"                 "Cambria Math"           
    [21] "Candara"                 "Comic Sans MS"           "Consolas"                "Constantia"              "Corbel"                 
    [26] "Courier New"             "DIN Alternate"           "DIN Condensed"           "Franklin Gothic Book"    "Franklin Gothic Medium" 
    [31] "Gabriola"                "Georgia"                 "Gill Sans MT"            "Gulim"                   "Impact"                 
    [36] "Khmer Sangam MN"         "Lao Sangam MN"           "Lucida Console"          "Lucida Sans Unicode"     "Luminari"               
    [41] "Marlett"                 "Meiryo"                  "Microsoft Yi Baiti"      "Microsoft Himalaya"      "Microsoft Sans Serif"   
    [46] "Microsoft Tai Le"        "MingLiU_HKSCS-ExtB"      "MingLiU_HKSCS"           "MingLiU"                 "MingLiU-ExtB"           
    [51] "Mongolian Baiti"         "MS Gothic"               "MS Mincho"               "MS PGothic"              "MS PMincho"             
    [56] "MS Reference Sans Serif" "MS Reference Specialty"  "Palatino Linotype"       "Perpetua"                "PMingLiU"               
    [61] "PMingLiU-ExtB"           "SimHei"                  "SimSun"                  "SimSun-ExtB"             "Tahoma"                 
    [66] "Times New Roman"         "Trattatello"             "Trebuchet MS"            "Tw Cen MT"               "Verdana"                
    [71] "Webdings"                "Wingdings"               "Wingdings 2"             "Wingdings 3"    
    

    However I need to use National 2 Condensed, and National (https://klim.co.nz/retail-fonts/national-2-condensed/).

    Is there a way to download these custom fonts for R to use in ggplot, even though they aren't included in extrafonts? And if not, does anybody know if any of these fonts are particularly similar to National 2 Condensed and National 2?

  • Tung
    Tung over 5 years
    FYI, for other types of fonts, you can use showtext package