Search code examples
rggplot2facet-grid

How to pass a list of arguments to facet_grid()


I am trying to pass a list of arguments to facet_grid() to give a function more flexibility but facet_grid() seems to consider everything in the list as faceting variables or something. It's not returning an error but it also is not having the behavior I expected. Here is the code I tried putting together to achieve this:

facet_plot <- function(facet.args){
  ggplot(iris, aes(x = Sepal.Length, y = Petal.Length)) +
    geom_point() +
    facet_grid(paste0('~', facet.args$facets), facet.args[which(names(facet.args) != 'facets')])
}
facet_plot(list(facets = 'Species', scales = 'free_x'))

what I am trying to achieve is this:

ggplot(iris, aes(x = Sepal.Length, y = Petal.Length)) +
        geom_point() +
        facet_grid(~Species, scales = 'free_x')

I would like to be able to pass any number of additional arguments to facet_grid().


Solution

  • You just forgot to name the second argument so you passed it to margin instead of passing it to scales (and you need double brackets for the argument to be a vector):

    facet_plot <- function(facet.args){
      ggplot(iris, aes(x = Sepal.Length, y = Petal.Length)) +
        geom_point() +
        facet_grid(paste0('~', facet.args$facets), scales= facet.args[[which(names(facet.args) != 'facets')]])
    }
    facet_plot(list(facets = 'Species', scales = 'free_x'))
    

    To be more general you could use do.call:

    facet_plot <- function(facet.args){
      facet.args$facets <- paste0('~', facet.args$facets)
      ggplot(iris, aes(x = Sepal.Length, y = Petal.Length)) +
        geom_point() +
        do.call(facet_grid,facet.args)
    }
    facet_plot(list(facets = 'Species', scales = 'free_x'))