ggplot geom_point 形状(和 pdf)中未显示的 unicode 符号

unicode symbol(s) not showing in ggplot geom_point shapes (and pdf)

我正在尝试使用 unicode 符号作为 ggplot 中的 geom_point 形状。它主要按预期工作,但一个符号 (▶, "\u25b6") 未显示在 RStudio 图中,而在 pdf none 中显示了符号。这是我的例子(数据显示用户在听音乐时的输入):

library(tidyverse)
library(ggplot2)
library(Cairo)

event_levels <- c("open", "play", "q", "pause", "ff", "exit")
# 1st try: add the symbols directly
event_shapes1 <- c("⏏️", "▶", "❓", "⏸️", "⏩", "⏹️")
# 2nd try: add unicode
event_shapes2 <- c("\u23cf", "\u25b6", "\u2753", "\u23f8", "\u23e9", "\u23f9")
# 3rd try: add unicode with ucap letters
event_shapes3 <- c("\U23CF", "\U25B6", "\U2753", "\U23F8", "\U23E9", "\U23F9")
event_colours <- c("black", "green", "red", "orange", "blue", "black")

data <- tibble(event = factor(c("open", "play", "q", "play", "q", "play", "pause", "play", "ff", "exit"), levels = event_levels),
               time = seq(0, 100, length.out = length(event)),
               pos = c(0, 0, 50, 50, 100, 100, 150, 150, 200, 300))

p <- ggplot(data) +
  geom_line(mapping = aes(x = time, y = pos), alpha = 0.5) +
  geom_point(mapping = aes(x = time, y = pos, color = event, shape = event), size = 6) +
  scale_shape_manual(values = event_shapes2) + 
  # event_shapes1 doesn't work, no difference between event_shapes2 and event_shapes3
  scale_color_manual(values = event_colours)

ggsave("test.pdf", plot = p, device=cairo_pdf)

我可能做错了什么,也可能是系统特定的错误 (Win 10)。我尝试在 ggsave 行(以及许多其他字体系列)中使用 library(extrafont)par(family = "Consolas")symbolfamily="Consolas",但没有成功。

我还尝试用 geom_text 打印符号并将符号添加到 tibble 中,如下所示:

data <- data %>%
  mutate(event_shape = case_when(
    event == "open" ~ "⏏️",
    event == "play"~ "▶",
    event == "q" ~ "❓",
    event == "pause" ~ "⏸️",
    event == "ff" ~ "⏩",
    event == "exit" ~ "⏹️",
  ), .after = event)

p <- ggplot(data) +
  geom_line(mapping = aes(x = time, y = pos), alpha = 0.5) +
  geom_text(mapping = aes(x = time, y = pos, label = event_shape), size = 6)

但是还是没有成功。我能做什么?我不想每次都下载符号,也许我可以在本地将符号保存为 png 或 svg,然后将它们添加到图形中?或者更简单的东西?

emojifont 包解决了这个问题。

这是一个例子:

library(emojifont)
library(ggplot2)
library(Cairo)

df <- data.frame(
  x=1,
  y=1,
  text="\u25b6"
)

p <- ggplot(df, aes(x=x,y=y, label=text)) +
  geom_text()
ggsave('test.pdf', p)