我发现在制作 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"
)
但是,对于一个用例,我希望添加字体样式,并且为了在我的 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"
)
showtext
问题中遇到类似的问题,但没有得到开发人员的支持,我想看看这里是否有人对如何解决这个问题有想法。
谢谢你。
遵循 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)