rggplot2showtext

showtext Breaks ggplot2 Emoji Rendering


I've found that when making ggplots, emojis render fine normally:

library(ggplot2)
library(dplyr)

df <- cars |>
  mutate(
    glyph = case_when(speed > 16 ~ "✅",
                      .default = "❌ "),
    label = case_when(speed > 16 ~ "Fast",
                      .default = "Slow"),
    color = case_when(speed > 16 ~ "red",
                      .default = "green")
  ) |>
  tibble::tibble()

# Before showtext
ggplot() +
  geom_text(
    data = df,
    aes(x = speed, y = dist, label = glyph, colour = color),
    size = 5, family = "fa"
  )

enter image description here

However, for a use case I wish to add a font style and in order to render that in my ggplot I've been using showtext::showtext_auto() combined with showtext::font_add(). Unfortunately this seems to break innate emoji rendering:

showtext::showtext_auto(enable = TRUE)

# After showtext
ggplot() +
  geom_text(
    data = df,
    aes(x = speed, y = dist, label = glyph, colour = color),
    size = 5, family = "fa"
  )

enter image description here

I found users having similar problems in this showtext issue, but there has been no support from the developer and I wanted to gauge if anyone here had thoughts on how to resolve this.

Thank you.


Solution

  • I was able to get my use case to work, following these examples and tips from June Choe and Cara Thompson:

    Using a combination of systemfonts::register_font() for the TTF I wanted to register and systemfonts::registry_fonts() to confirm it's existence, I could then load the font without impacting emoji rendering. Even can combine the two in the same plot:

    df <- cars |>
      mutate(
        glyph = case_when(speed > 16 ~ "✅",
                          .default = fontawesome("fa-car")),
        label = case_when(speed > 16 ~ "Fast",
                          .default = "Slow"),
        color = case_when(speed > 16 ~ "red",
                          .default = "green")
      ) |>
      tibble::tibble()
    
    ggplot() +
      geom_swim_marker(
        data = df,
        aes(x = speed, y = dist, marker = label),
        size = 5, family = "FontAwesome"
      ) +
      scale_marker_discrete(glyphs = df$glyph,
                            colours = df$color,
                            limits = df$label)
    

    enter image description here