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

标签 r ggplot2 vegan

问题

如何在 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")

enter image description here

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

Stressplot produced using vegan's stressplot function.

违规行是

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

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

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

最佳答案

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

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")

enter image description here

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

关于r - ggplot2 中的注释不支持换行符是粘贴和解析的命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47124238/

相关文章:

r - 在 R 'factoextra' 中,当我使用函数 'fviz_eig' 时,如何调整列宽和标签大小

r - 按变量合并 st_voronoi 多边形

r - 如果数据包含 NA 值,则计算余弦相似度

r - 如何在 R 中显示 Simper() 的 P 和全局 R?

r - 用不同颜色的线段绘制Y轴线

r - 在 R 函数中注入(inject)一组命名参数

r - 使用ggrepel覆盖水平定位

r - 使用 ggplot2 将标签置于条形中心并将标签移动到 R 中误差条的顶部

r - 如何在rarecurve(纯素包)中单独为线条着色