如何在 ggplot2' geom_label 中插入换行符

How to insert line breaks in ggplot2' geom_label

注意:此问题已更新,请参阅“编辑”

我正在使用 ggplot2 绘制带有一些注释的条形图。我想在数学符号代码(即%down%)前后添加一个换行符(\n)。但是,geom_label(aes(label=paste(...))) 中的 paste(..., sep = "\n") 失败并出现以下错误:Error in parse(text = text[[i]]) : <text>:2:1: unexpected SPECIAL。我该怎么办?

---
output: 
  bookdown::pdf_document2:
    latex_engine: xelatex
    keep_tex: true
    dev: cairo_pdf
---
knitr::opts_chunk$set(
  dev      = "cairo_pdf",
  dev.args = list(family = "Roboto Medium")
  )
library(tidyverse)
library(magrittr)
tibble(
  F1 = factor(
    c(-0.5, -0.5, 0.5, 0.5), 
    levels = c(-0.5, 0.5), 
    labels = c("A", "H")
  ), 
  F2 = factor(
    c(-0.5, 0.5, -0.5, 0.5), 
    levels=c(-0.5, 0.5), 
    labels=c("A", "H")
  ),
  pct = c(60, 20, 40, 20)
) %>% 
  ggplot(
    ., 
    aes(
      x = F1, 
      y = pct, 
      color = F2, 
      fill = F2
    )
  )+
  geom_bar(
    stat="identity",
    width = 0.6,
    position = position_dodge(width = 0.7)
  ) +
  geom_label(
    parse = TRUE,
    aes(
      label = paste(
        sep = "", # "\n"
        F1, 
        "%down%", 
        F2
      ),
      vjust = -1
    ),
    position = position_dodge2(
      width = 1 
    ),
    fill = "white",
    colour = "black",
    label.size = NA,
    size = 5
  ) 

编辑

虽然 by @the-mad-statter is quite useful and enables me to add a newline, the down arrow character \u2193 does not appear, since my font used in the chart does not seem to have \u2193. I'm using Roboto Medium 通过指定 knitr::opts_chunk$set(dev.args = list(family = "Roboto Medium")).

似乎对我有用的是将 showtext 包与所需的 Unicode 符号结合使用:

---
output: 
  bookdown::pdf_document2:
    latex_engine: xelatex
    keep_tex: true
    dev: cairo_pdf
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(
  echo     = FALSE, 
  dev      = "cairo_pdf",
  dev.args = list(family = "Roboto")
)

library(tidyverse)

library(showtext)
font_add_google("Roboto")
showtext_auto()
```

```{r}
tibble(
  F1 = factor(
    c(-0.5, -0.5, 0.5, 0.5), 
    levels = c(-0.5, 0.5), 
    labels = c("A", "H")
  ), 
  F2 = factor(
    c(-0.5, 0.5, -0.5, 0.5), 
    levels=c(-0.5, 0.5), 
    labels=c("A", "H")
  ),
  pct = c(60, 20, 40, 20)
) %>% 
  ggplot(
    ., 
    aes(
      x = F1, 
      y = pct, 
      color = F2, 
      fill = F2
    )
  )+
  geom_bar(
    stat="identity",
    width = 0.6,
    position = position_dodge(width = 0.7)
  ) +
  geom_label(
    parse = FALSE,
    aes(
      label = paste(
        sep = "\n",
        F1, 
        "\u2193", 
        F2
      ),
      vjust = -1
    ),
    position = position_dodge2(
      width = 1 
    ),
    fill = "white",
    colour = "black",
    label.size = NA,
    size = 5
  )
```