0

I faced a problem that R does't see the argument I specify in ggplot function. Here is the code I use:

s_plot <- function(data, aaa, bbb,){
  ggplot(data, aes(x = aaa, y = bbb))+geom_point(size=2, shape=8, col="red")
}

As a result I got an error:

object aaa not found

What's the problem? How to resolve it?

Thanks a lot.

UPD:

Sorry, but I provide you with the simplest example and it doesn't translate the whole problem. Here is the full code I use:

s_plot <- function(data, n_after, perc_cap, n_xlab, n_ylab, x_min){
  ggplot(data, aes(x={{n_after}}, y={{perc_cap}})) + geom_point(size=2, shape=8, col="red")+
        xlab(n_xlab)+ ylab(n_ylab)+xlim(x_min, 1.1*max(data$n_after))+  ylim(0, 1.1*max(data$perc_cap))+
    geom_text(aes(x=n_after, y=perc_cap, label = NAME), hjust=0, vjust=-1.5)+
    geom_vline(xintercept=8,  col = "darkgreen",lty=2, size=1)+
    geom_text(aes(x=8, label=label, y=20), colour="steelblue", angle=90, hjust=-1)+
    theme(axis.title.y = element_text(size=15),
          axis.title.x = element_text(size=15))

As you may see n_after and perc_cap are mentioned in several places. And this probably is the source of problem. How to resolve it in this particular case?

  • See https://ggplot2.tidyverse.org/reference/aes.html#quasiquotation – Konrad Rudolph Mar 03 '20 at 17:18
  • How are you trying to call this function? You likely need tidyeval; see the [dplyr vignette](https://dplyr.tidyverse.org/articles/programming.html) that should be extendable to ggplot – camille Mar 03 '20 at 17:19
  • Does this answer your question? [How to use a variable to specify column name in ggplot](https://stackoverflow.com/questions/22309285/how-to-use-a-variable-to-specify-column-name-in-ggplot) – camille Mar 03 '20 at 17:38
  • Also see [this](https://stackoverflow.com/q/16295234/5325862), [this](https://stackoverflow.com/q/45824409/5325862), [this](https://stackoverflow.com/q/44548819/5325862) – camille Mar 03 '20 at 17:42

1 Answers1

2

You can use the {{ }} operator. As in the example:

f <- function (data, x) {ggplot(data= data, aes(x={{x}})) + geom_bar()}

f(mtcars, gear)

enter image description here

André Costa
  • 377
  • 1
  • 11
  • 1
    This isn't a major issue, but you reversed the data and column arguments from what 1) what the OP shows and 2) standard tidyverse practice which would give you easy access to functions' first arguments – camille Mar 03 '20 at 17:21