在ggplot中使用参数占位符 [英] Use argument place holder within ggplot

查看:80
本文介绍了在ggplot中使用参数占位符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在ggplot()中使用参数占位符..但这由于某种原因我无法完全确定.

I am trying to use an argument place holder . within a ggplot(). But it doesn't work for some reason I am not entirely sure of.

我正在做的是这件事(使用来自ggplot2/tidyverse的示例数据):

What I am doing is this (using the sample data from 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 = . %$% corr_eqn(pop, unemploy). IE.我不想再次致电economics[economics$date>="1990-11-01",],因为我已经对此进行了过滤:

However, I want to reduce the command behind label to label = . %$% corr_eqn(pop, unemploy). I.e. I do not want to call economics[economics$date>="1990-11-01",] again as I have already filtered for this:

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

但是,它不适用于自变量占位符..我该怎么办?

However, it doesn't work with the argument place holder .. What should I do instead?

此外,如果可以不必再次将popunemploy列为corr_eqn fn中的单独参数,这也将是惊人的.

Plus, if it would be possible to nat having to list pop and unemploy as seperate arguments in the corr_eqn fn again, this would be also amazing.

推荐答案

问题是annotate不在管道中,因此.在这里没有意义. ggplot中的+运算符与magrittr中的%>%具有不同的功能;在您的代码中,管道实际上在对ggplot()的调用处停止. +运算符将允许下一个函数向绘图中添加各种元素,但通常不允许您以与%>%相同的方式访问馈入ggplot()调用的数据操作员.

The problem is that annotate is not within the pipe, so . has no meaning there. The + operator in ggplot does not have the same function as the %>% in magrittr; in your code the pipe effectively stops at the call to ggplot(). The + operator will allow the next function to add various elements to the plot, but it won't in general allow you to access the data that was fed to the ggplot() call in the way you would with the %>% operator.

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

On the other hand, if you use geom_text instead of annotate, these problems vanish because you are accessing the variables in your subsetted data directly:

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)

这篇关于在ggplot中使用参数占位符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆