Search code examples
rggplot2visualizationfacet-grid

How to pass parameters of facet_grid() in a function?


Lets say I have the following dataset.

library(ggplot2)    
test_data <- rnorm(40, 4, 3)
factory <- sample(c("A", "B", "C"), 40, replace = TRUE)
df <- data.frame(test_data, factory)

And I have a function that creates a graph such as following:

graph_builder <- function(data_set, y_axis_parameter, category, attribute_name) {
  graph <- ggplot(data_set, aes(x=seq(length({{y_axis_parameter}})), y={{y_axis_parameter}},
    colour= {{category}})) +
    geom_line() +
    geom_point() +
    facet_grid(.~{{category}}) +
    ylab(paste0(attribute_name, " Measured Values")) +
    xlab("Data Points") +
    labs(title = paste0(attribute_name)) +
    theme(legend.position = "none") 

  graph
}

graph_builder(df, test_data, category, "Test graph" )

This code functions correctly in all lines except for facet_grid(). I assumed that passing the column name in double curly braces {{}} would work. However, it appears that facet_grid() does not support passing the column name in this manner.

How can I resolve this issue?


Solution

  • I'd recommend passing a raw variable name like factory, and feeding that in curly braces to the rows and/or cols parameters of facet_grid:

    graph_builder <- function(data_set, y_axis_parameter, category, attribute_name) {
        graph <- ggplot(data_set, aes(x=seq(length({{y_axis_parameter}})), y={{y_axis_parameter}},
                                      colour= {{category}})) +
          geom_line() +
          geom_point() +
          facet_grid(rows = vars({{category}})) +
          ylab(paste0(attribute_name, " Measured Values")) +
          xlab("Data Points") +
          labs(title = paste0(attribute_name)) +
          theme(legend.position = "none") 
        
        graph
      }
    
    graph_builder(df, test_data, factory, "Test graph" )
    

    enter image description here