Use argument place holder within ggplot

2020-07-17 05: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)