BeSeLuFri
BeSeLuFri

Reputation: 653

Wrapper function for geom_text

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?

Upvotes: 0

Views: 126

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 173793

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

Upvotes: 3

Related Questions