r - 如何将 bquote 与 ggplot2 geom_label 结合使用?

标签 r ggplot2 plotmath

我已经阅读了以下文章:
https://trinkerrstuff.wordpress.com/2018/03/15/2246/

现在我正在尝试使用建议的方法 bquote在我的情节中。但是我无法让它工作。我有以下代码

x <- seq(0, 2*pi, 0.01)
y <- sin(x)
y_median <- median(y)
ggplot(mapping = aes(x = x, y = y)) + 
  geom_line() + 
  geom_label(aes(label = bquote("median" ~ y==~.y_median), x = 1, y = y_median))

我收到以下错误:
Error in as.data.frame.default(x[[i]], optional = TRUE) : 
  cannot coerce class ‘"formula"’ to a data.frame

我究竟做错了什么?

最佳答案

ggplot(mapping = aes(x = x, y = y)) + 
  geom_line() + 
  geom_label(aes(label = list(bquote("median" ~ y==~.(y_median))),
                 x = 1, y = y_median), 
             parse=TRUE)

关键点:

1.) 我修复了 "median" ~ y==~.(y_median) 中缺少的括号.这在 ?bquote 中讨论帮助页面:

‘bquote’ quotes its argument except that terms wrapped in ‘.()’ are evaluated in the specified ‘where’ environment.



2.) 输入 bquote在列表中,因为 aes需要一个向量或一个列表。

3.) 告诉 geom_label通过将相应的参数设置为 TRUE 来解析表达式。

enter image description here

关于r - 如何将 bquote 与 ggplot2 geom_label 结合使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51991695/

相关文章:

r - 在facet_wrap的某些面板上的geom_rect

R ggplot 使用三个值和 bgroup 用 atop 进行注释

r - 绘图符号显示为白色矩形

R 数学注释

r - 如何在 ggplot 中创建气泡网格图?

r - 过滤 R data.frames 时更新因子水平

regex - R正则表达式获取单引号之间的文本

r - 设置ggplot2标签背景色

r - 使用 ggplot2 出现意外的 Walker 别名表输出

r - 计算在多个变量上具有特定值的组数