How can I import a specific font into R and use it in ggplot graphs?

55 views Asked by At

I'm trying to set the font of all my text in all my graphs to be Tenorite. I have it installed in my laptop in

C:\Users\[me]\AppData\Local\Microsoft\FontCache\4\CloudFonts

It's also easy to download from the internet. I'm trying to load the font using extrafont and then setting the base_family in the set_theme() command.

Here is what I'm doing. I'm running R version 4.2.2.

library(ggplot2)
library(extrafont)

font_import(paths = [mypath])

This seems to work fine. At this point the output is

Scanning ttf files in [mypath] ... Extracting .afm files from .ttf files... [mypath]\26512206606.ttf : Tenorite-BoldItalic already registered in fonts database. Skipping. [mypath]\26622973498.ttf : Tenorite-Italic already registered in fonts database. Skipping. [mypath]\27733932592.ttf : Tenorite-Bold already registered in fonts database. Skipping. [mypath]\29595851800.ttf : Tenorite-Regular already registered in fonts database. Skipping. Found FontName for 0 fonts. Scanning afm files in C:/Users/[me]/AppData/Local/Programs/R/R-lib/extrafontdb/metrics

Originally it seemed to add the font(s) to the database.

I then load the fonts.

loadfonts(device = "win")

and get output

Tenorite already registered with windowsFonts().

When I run fonts() I get:

[1] "Tenorite"

I then try to set the theme and plot something

theme_set(theme_bw(base_family = "Tenorite"))
plot = ggplot(data = data.frame(x = c(1, 2, 3), y = c(6, 7, 8)))+
  aes(x = x, y = y)+
  geom_point()+
  labs(title = "TEST font!")

plot

which results in the following plot. This looks no different from the base font. I am, however, able to change the font this way. If I then do

theme_set(theme_bw(base_family = "mono"))
plot

I get the same plot with different font. Does anyone know why this isn't working?

1

There are 1 answers

0
gbp On

I never figured out why what I tried was not working, but using showtext works perfectly.

library(showtext)
font_add(family = "Tenorite", regular = "C:/[path].ttf")
showtext_auto()
theme_set(theme_bw(base_family = "Tenorite", base_size = 18))

plot = ggplot(data = data.frame(x = c(1, 2, 3), y = c(6, 7, 8)))+
  aes(x = x, y = y)+
  geom_point()+
  labs(title = "TEST font!")

plot

Gives me this graph with the correct font!