ggplot2 中的注释不支持换行符是粘贴和解析的命令

Annotate in ggplot2 does not honor newline is a pasted and parsed command

问题

如何在 ggplot2annotate 中获取 pasteparse 以支持换行 (\n) 字符?

问题和MWE

我正在尝试在 ggplot2 中使用包 vegan. 中的 metaMDS 重现 NMDS 分析的应力图 这是我的 MWE,然后是结果图。

library(ggplot2)
library(tibble)
library(vegan)

set.seed(42) # for reproducibility

data(dune)
fit <- metaMDS(dune)
tib <- tibble(fit$diss, fit$dist, fit$dhat)
colnames(tib) <- c("diss", "dist", "dhat")
stress <- fit$stress
coord_x <- min(tib$diss)
coord_y <- max(tib$dist)
nonmetric_r2 <- round(1 - stress * stress, digits = 3)
linear_r2 <- round(summary(lm(fit$dist~fit$dhat))$adj.r.squared, 3)

## How do I get the newline character to be honored?
nonmetric_label = paste0("Non-metric~fit~italic(R)^2 ==", nonmetric_r2, "~\n Linear~fit~italic(R)^2 ==", linear_r2)

ggplot(tib,
       aes(x = diss, y = dist)) +
  geom_point(color = "blue") +
  geom_line(aes(x = diss, y = dhat), color = "red") +
  annotate(
    geom = "text",
    x = coord_x,
    y = coord_y,
    hjust = 0,
    #vjust = 1,
    label = nonmetric_label, parse = TRUE) +
  labs(x = "Observed Dissimilarity",
       y = "Ordination Distance")

上面的单个注释行应该在两个单独的行上,如下所示(来自stressplot(fit))。

违规行是

nonmetric_label = paste0("Non-metric~fit~italic(R)^2 ==", nonmetric_r2, "~\n Linear~fit~italic(R)^2 ==", linear_r2)

如果我在 \n 之前不包含波浪号,那么换行符之后的所有内容都会消失。我尝试了波浪号放置的各种组合,并将 '\n~Linear~fit' 放在额外的单引号和 back-ticks.

如何让所需的注释出现在两行上?

一种方法是使用字符串向量作为标签,并使用坐标向量来匹配所需的注释:

nonmetric_label = c(paste0("Non-metric~fit~italic(R)^2 ==", nonmetric_r2),
                    paste0("Linear~fit~italic(R)^2 ==", linear_r2)) 

ggplot(tib,
       aes(x = diss, y = dist)) +
  geom_point(color = "blue") +
  geom_step(aes(x = diss, y = dhat), color = "red", direction = "vh") +
  annotate(
    geom = "text",
    x = coord_x,
    y = c(coord_y, 0.95*coord_y),
    hjust = 0,
    #vjust = 1,
    label = nonmetric_label, parse = TRUE) +
  labs(x = "Observed Dissimilarity",
       y = "Ordination Distance")

根据 Jari Oksanen 的建议,我已将 geom_line 更改为 geom_step。要匹配 stressplot(fit) 的输出,需要一个额外的参数 direction = "vh"