Create customized plotting function and run it with dynamic parameters using R

Solution 1:

Try something like this. You can specify the X/Y and the grouping etc in the function.

EDIT: added dataframe as argument to function per the question

set.seed(1)

df1 <- slice_sample(iris, n = 10)


library(ggplot2)
library(patchwork)
    
my_plot = function(DF=df, X="", Y="", GROUP=""){
  
  # Create ggplot2 scatterplot
  p1 <- ggplot(DF,               
               aes(x = .data[[X]],
                   y = .data[[Y]],
                   col = Species)) +
    geom_point()
  p1
  # Create ggplot2 barchart
  p2 <- ggplot(DF,               
               aes(x = .data[[GROUP]],
                   y = .data[[Y]],
                   fill = .data[[GROUP]])) +
    geom_bar(stat = "identity")
  p2
  
  # Create ggplot2 boxplot
  p3 <- ggplot(DF,
               aes(x = .data[[GROUP]],
                   y = .data[[Y]],
                   col = .data[[GROUP]])) +
    geom_boxplot()
  p3
  
  # Create plot composition
  p <- (p1 + p2) / p3
  # Draw plot composition
  return(p)
  
}

test = my_plot(DF=iris, X= "Sepal.Length",Y = "Sepal.Width", GROUP="Species")