showtext 破坏 ggplot2 表情符号渲染

问题描述 投票:0回答:1

我发现在制作 ggplots 时,表情符号通常渲染得很好:

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

但是,对于一个用例,我希望添加字体样式,并且为了在我的 ggplot 中渲染它,我一直在使用

showtext::showtext_auto()
showtext::font_add()
结合使用。不幸的是,这似乎破坏了固有的表情符号渲染:

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

我发现用户在这个

showtext
问题中遇到类似的问题,但没有得到开发人员的支持,我想看看这里是否有人对如何解决这个问题有想法。

谢谢你。

r ggplot2 showtext
1个回答
0
投票

遵循 June Choe 和 Cara Thompson 的这些示例和技巧,我能够让我的用例发挥作用:

结合使用

systemfonts::register_font()
来注册我想要注册的 TTF,并使用
systemfonts::registry_fonts()
来确认它的存在,然后我可以加载字体,而不会影响表情符号渲染。甚至可以将两者结合在同一个情节中:

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

© www.soinside.com 2019 - 2024. All rights reserved.