Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading