将 (x,y) 坐标对放置在 ggplot 注释标签中

问题描述 投票:0回答:1

我有一个 ggplot,用于通过 RMarkdown 文档说明一些三角函数概念。

annotate("text",
             x = 0.97,
             y = 0.5,
             label = str_c("(~frac(sqrt(3),pi)", ",", "~frac(1,2))"),
             parse = TRUE,
             size = 3
             )

此操作失败,并抱怨引用的逗号。我很困惑。每次我在标签中使用逗号字符编织文档时,它都会失败,抱怨“意外的','”。

有没有人有办法在文本注释的标签中插入文字逗号,如下所示。 注意:这些注释是一次性的,不属于其他数据源。

我已经尝试过:

label = str_c("(~frac(sqrt(3),pi)", ",", "~frac(1,2))")
label = str_c("(~frac(sqrt(3),pi)", "~,", "~frac(1,2))")
label = str_c("(~frac(sqrt(3),pi)", "&#2C", "~frac(1,2))")

label = "(~frac(sqrt(3),pi),~frac(1,2))"
label = "(~frac(sqrt(3),pi)~,~frac(1,2))"

所有结果都导致引用逗号字符的错误。 如果删除该逗号,我会得到预期的输出,两个值被括号包围,但由空格而不是逗号分隔。

r ggplot2 annotate
1个回答
0
投票

原义逗号是一个“特殊”字符。因此,您必须将其放在引号中。另外添加

~
*
使其成为有效表达式:

library(ggplot2)

ggplot() +
  annotate("text",
    x = 0.97,
    y = 0.5,
    label = paste0(
      "(~frac(sqrt(3),pi)",
      "~','",
      "~frac(1,2))"
    ),
    parse = TRUE,
    size = 8
  )

© www.soinside.com 2019 - 2024. All rights reserved.