Use argument place holder within ggplot

强颜欢笑 提交于 2020-05-26 04:41:21

问题


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.

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

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?

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.


回答1:


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.

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)



来源:https://stackoverflow.com/questions/61931500/use-argument-place-holder-within-ggplot

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!