Capturing extra arguments in future_walk

Hi all,
I'm looking to create a function that can save a ggplot plot into several different formats. At the moment, the function partially works, but is not passing any of the extra arguments passed to the ggsave function nested within such as width, dpi, etc, and the plots are being saved in the default 7 x 7 inches.

library("ggplot2")
library("furrr")
#> Loading required package: future
library("glue")
library("fs")
library("rlang")

plan(multisession, workers = 2)

save_figures <- function(plotname, plot = ggplot2::last_plot(), ...) {
  
  fig_ext <- c("jpg", "pdf", "png")
  
  filepath <- glue("~/Desktop/{plotname}")
  dir_create(filepath)

  future_walk(fig_ext,
    ~ggsave(filename = glue("{plotname}.{.x}"), plot = plot, device = .x,
      path = filepath), ...)
}

hpplot <- ggplot(mtcars, aes(hp, mpg)) +
  geom_point()

save_figures(plotname = "hpplot", plot = hpplot,  width = 100, height = 100,
  dpi = 300, units = "mm")
#> Saving 7 x 7 in image
#> Saving 7 x 7 in image
#> Saving 7 x 7 in image

plan(sequential)

Created on 2021-03-17 by the reprex package (v1.0.0)

It looks like the closing parenthesis for ggsave comes right after path=filepath, rather than after ....

Thanks, @joels. Turns out it was an XY problem, where ggsave wasn't recognizing the extra arguments passed via the ellipses. I ended up using your suggestion plus explicitly capturing the arguments and passing them to ggsave.

library("ggplot2")
library("furrr")
#> Loading required package: future
library("glue")

plan(multisession, workers = 4)

save_figures <- function(plotname, plot = ggplot2::last_plot(), ...) {
  
  fig_ext <- c("jpg", "pdf", "png")
  extra_args <- rlang::dots_list(...)
  filepath <- glue("~/Desktop/{plotname}")
  fs::dir_create(filepath)

  future_walk(fig_ext,
    ~ggsave(filename = glue::glue("{plotname}.{.x}"), plot = plot, device = .x,
      path = filepath, width = extra_args[["width"]],
      height = extra_args[["height"]], dpi = extra_args[["dpi"]],
      units = extra_args[["units"]]))
}

hpplot <- ggplot(mtcars, aes(hp, mpg)) +
  geom_point()

save_figures(plotname = "hpplot", plot = hpplot, width = 100, height = 50,
  dpi = 300, units = "mm")

Created on 2021-03-17 by the reprex package (v1.0.0)

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.