Search code examples
rggplot2fonts

How to select a styles within a font family for a ggplot


I've used

font_add_google(name = "Outfit", family = "Outfit")

to install the Outfit font family at https://fonts.google.com/specimen/Outfit.

Using, e.g.

element_text(family = "Outfit")

I can successfully apply the regular Outfit font to my ggplot objects. That all works fine. How can I access the substyles of this font, e.g. Thin, ExtraLight, Light, etc.?


Solution

  • The "different" fonts differ only in the weight, i.e. Regular has a weight of 400, whereas ExtraLight has a weight of 200. By default font_add_google downloads the (regular) font with weight 400 and one with a weight of 700 used with fontface="bold". However, both weights could be set via the regular.wt and the bold.wt argument.

    This said, if you want to use multiple variants or styles of the same font you have to download them separately with their respective weights and of course assign a different label to each via the family argument.

    library(showtext)
    #> Loading required package: sysfonts
    #> Loading required package: showtextdb
    library(ggplot2)
    
    wt <- seq(100, 900, 100)
    
    purrr::walk(
      wt,
      \(x) font_add_google(
        name = "Outfit",
        family = paste0("Outfit", x),
        regular.wt = x
      )
    )
    
    showtext_auto()
    
    dat <- data.frame(
      wt = wt,
      name = paste0("Outfit", wt)
    )
    
    ggplot(dat) +
      geom_text(aes(label = name, x = 0, y = wt, family = name),
        size = 10
      )