简体   繁体   中英

ggplot within a function within a function: passing arguments

I am having difficulty figuring out how to pass an argument through a nested function call to ggplot. An example will help illustrate:

library('tidyverse')

dset <- tibble(
  xvar = 1:5,
  yvar = 6:10
)

plot_inner <- function(.outcome) {

  ggplot(dset, aes(x=xvar)) +
    geom_line(aes_(y=substitute(.outcome)))
}

Now I can call plot_inner(.outcome=yvar) and it will correctly plot a line chart of yvar against xvar . However, the issue arises when I want to nest plot_inner() inside another function:

plot_outer <- function(..outcome) {

  plot_inner(.outcome=..outcome)
}

The intention is to let me call plot_outer() and specify ..outcome as a column of dset which then gets passed through to .outcome in plot_inner() which then gets plotted by ggplot() . But it doesn't work:

> plot_outer(..outcome=yvar)
Error in FUN(X[[i]], ...) : object '..outcome' not found

I've tried various combinations of parse() , eval() , substitute() , and deparse() , but could not figure out how to make this kind of nested function call work.

I also tried an alternative approach:

plot_inner_2 <- function(.outcome) {

  .outcome <- enquo(.outcome)

  dset %>% rename(value = UQ(.outcome)) %>%

    ggplot(aes(xvar, value)) +
      geom_line()
}

With this approach I can call plot_inner_2(.outcome=yvar) and it correctly produces the line chart of yvar against xvar . However, again I run into an error when I try to nest this inside another function and then call the outer function:

plot_outer_2 <- function(..outcome) {

  plot_inner_2(.outcome=..outcome)
}

> plot_outer_2(..outcome=yvar)
 Error: `..outcome` contains unknown variables

Any help would be appreciated. I would prefer a solution along the lines of the first approach I tried, but if anyone has a solution along the lines of the second approach, or some other approach entirely, I would be happy to learn whatever works.

Following the link in @aosmith's comment, wrapping plot_inner() inside of eval(substitute()) within the plot_outer() function seems to be a solution.

plot_outer <- function(..outcome) {

  eval(substitute(plot_inner(.outcome=..outcome)))
}

Now the call to plot_outer(..outcome=yvar) works as intended, passing yvar through to .outcome in inner_plot() which is then passed to ggplot() and plotted against xvar .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM