0

This question is strongly related to this one. However, I want to build a wrapper around the geom_text function.

See this example (using example data from the tidyverse):

library(tidyverse)

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

geom_text_pearson <- function(x_ax, y_ax, ...){
  geom_text(aes(x = min(x_ax), y = max(y_ax),  label = corr_eqn(x_ax, y_ax)), 
            hjust = 0, vjust = 1, size = 6)
}


economics %>%
  filter(date >= "1990-11-01") %>%
  ggplot(aes(pop, unemploy)) +  
  geom_point() + 
  geom_text_pearson(x_ax = pop, y_ax= unemploy)

I would get to my desired result if I would replace my costume geom_text_pearson function with

geom_text(aes(x = min(pop), y = max(unemploy), label = corr_eqn(pop, unemploy)), 
      hjust = 0, vjust = 1, size = 6)

Is there a way to do this through my preferred solution?

BeSeLuFri
  • 623
  • 1
  • 5
  • 21

1 Answers1

3

Since you are passing arguments to a function that uses non-standard evaluation, you need to wrap the arguments in {{ (the curly-curly operator).

Note that as suggested by @user20650 in comments to my previous answer, your geom_text_pearson function would benefit from the addition of check_overlap = TRUE:

geom_text_pearson <- function(x_ax, y_ax, ...){
  geom_text(aes(x = min({{x_ax}}), y = max({{y_ax}}),  
                label = corr_eqn({{x_ax}}, {{y_ax}})), 
            hjust = 0, vjust = 1, size = 6, check_overlap = TRUE)
}

economics %>%
  filter(date >= "1990-11-01") %>%
  ggplot(aes(pop, unemploy)) +  
  geom_point() + 
  geom_text_pearson(x_ax = pop, y_ax= unemploy)

enter image description here

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87
  • Perfect - wasn't aware of the curly curly operator. Thank you very much! – BeSeLuFri May 22 '20 at 07:48
  • Is there an easy modification through which I can simply write "+ geom_text_pearson()" and get the same output? I.e. through which the x and the y axis variables in aes() are the default arguments in the geom_text_pearson() fn? – BeSeLuFri Mar 16 '21 at 16:30
  • I am happy to write a new question to this if you think that is more appropriate – BeSeLuFri Mar 16 '21 at 16:30