【问题标题】:Annotate in ggplot2 does not honor newline is a pasted and parsed commandggplot2 中的注释不支持换行符是粘贴和解析的命令
【发布时间】:2017-11-05 17:04:36
【问题描述】:

问题

我如何在ggplot2annotate 中获得pasteparse 以兑现换行符(\n)?

问题和 MWE

我正在尝试在 ggplot2 中使用 metaMDS 在包 vegan. 中重现 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' 放在额外的单引号和反引号中。

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

【问题讨论】:

  • plotmath 不支持换行符。也许在上面就足够了?请参阅帮助(“plotmath”)。

标签: r ggplot2 vegan


【解决方案1】:

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

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"

【讨论】:

  • 我觉得更大的问题是阶跃函数不是阶跃函数:红线应该只有水平和垂直线段,但它有斜线段。一两行文字没有区别。
  • @Jari Oksanen 感谢您的评论。我完全同意你的看法。将geom_line 更改为geom_step
  • @JariOksanen 我同意文本的行数无关紧要,但我认为两行在美学上更令人愉悦。感谢您提供有关 step 功能和误用的信息。
  • 今天早上让我印象深刻的是ggplot2 的理念是分层构建图。我将每个注释移到它自己的annotate 命令中,这也给了我更大的灵活性。你的y = c(coord_y, 0.95*coord_y) 向我展示了如何获得良好的间距。所以,感谢您的时间和回答。
猜你喜欢
  • 2011-01-06
  • 2017-01-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-26
  • 2022-07-13
  • 1970-01-01
  • 2012-06-10
相关资源
最近更新 更多