r - 在 ggplot 中使用参数占位符

标签 r ggplot2 magrittr

我正在尝试使用参数占位符 .ggplot() 内.但由于某种我不完全确定的原因,它不起作用。

我正在做的是这个(使用来自 ggplot2/the tidyverse 的样本数据):

library(tidyverse)
library(magrittr)

corr_eqn <- function(x, y, digits = 2) {
  corr_coef <-
    round(cor(x, y, use = "pairwise.complete.obs"), digits = digits)
  paste("r = ", corr_coef)
}


economics %>%
  filter(date >= "1990-11-01") %>%
  ggplot(aes(pop, unemploy)) +  
  geom_point()+
  annotate(geom = "text", x=-Inf, y=Inf, hjust=0, vjust=1,
           label = economics[economics$date>="1990-11-01",] %$% corr_eqn(pop, unemploy))

但是,我想将 label 后面的命令减少到 label = . %$% corr_eqn(pop, unemploy) . IE。我不想打电话 economics[economics$date>="1990-11-01",]再次因为我已经过滤了这个:
economics %>%
  filter(date >= "1990-11-01") %>%
  ggplot(aes(pop, unemploy)) +  
  geom_point()+
  annotate(geom = "text", x=-Inf, y=Inf, hjust=0, vjust=1,
           label = . %$% corr_eqn(pop, unemploy))

但是,它不适用于参数占位符 . .我应该怎么做?

另外,如果有可能 nat 必须列出 popunemploy作为 corr_eqn 中的单独参数fn 再次,这也将是惊人的。

最佳答案

问题是 annotate不在管道内,所以 .那里没有任何意义。 + ggplot 中的运算符与 %>% 的功能不同在马格利特;在您的代码中,管道在调用 ggplot() 时有效地停止。 . +运算符将允许下一个函数将各种元素添加到绘图中,但通常不允许您访问提供给 ggplot() 的数据。以您使用 %>% 的方式调用电话运算符(operator)。

另一方面,如果您使用 geom_text而不是 annotate ,这些问题消失了,因为您正在直接访问子集数据中的变量:

economics %>%
  filter(date >= "1990-11-01") %>%
  ggplot(aes(pop, unemploy)) +  
  geom_point() + 
  geom_text(aes(x = min(pop), y = max(unemploy), label = corr_eqn(pop, unemploy)), 
            hjust = 0, vjust = 1, size = 6)

enter image description here

关于r - 在 ggplot 中使用参数占位符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61931500/

相关文章:

r - 构建所有格式时 insert_chapter_script(config, "before") 中出现错误

r - 根据条件修改列中的值?

r - 在管链中捕获对象的 "safe state"

r - 如何调用使用 magrittr 管道创建的对象的元素?

r - 从 nlme 对象中提取随机公式

regex - 每两列相减

r - ggplot2添加地质时间轴注释: filled rects with names between axis and data

r - 使用 ggplot2 绘制比例频率,但省略了某些类别的数据

r - ggplot - 带有多个箭头的 geom_segment()

r - 使用 dplyr 过滤 data.frame 中的完整案例(按案例删除)