Home > Software design >  how to pass ggplot parameters through a function?
how to pass ggplot parameters through a function?

Time:02-23

I have a simple code that creates a combined barplot and line plot with two axes. I wanted to make this code dynamic so that I can pass the columns to plot as parameters of a function. Here is the code outside the function,it works fine:

data <- data.frame(group = LETTERS[1:5],    # Create example data
                   sample = c(1000, 800, 1200, 900, 800),
                   responses1 = c(0.6, 0.9, 0.9, 0.5, 0.8),
                   responses2 = c(0.2, 0.4, 0.7, 0.1, 0.3)
                   )

ggp1 <- ggplot(data)                       
  geom_bar(aes(group, sample), stat = "identity")   
  geom_line(aes(group, responses * max(sample), group = 1),
            col = "#1b98e0", lwd = 3)   
  scale_y_continuous(sec.axis = sec_axis(~ . / max(data$sample)))

ggp1 

Now when trying to put it in a function it becomes challenging a little bit for me:

plot_func <- function(var1, var2) {
  ggp1 <- ggplot(data)                       
    geom_bar(aes(group, var1), stat = "identity")   
    geom_line(aes(group, var2 * max(var1), group = 1),
              col = "#1b98e0", lwd = 3)   
    scale_y_continuous(sec.axis = sec_axis(~ . / max(data[[var1]])))
  
  ggp1
}

CodePudding user response:

If you are passing var1 and var1 unquoted, you could try something like this:

plot_func <- function(df, var1, var2) {
  ggp1 <- ggplot(df)                       
    geom_bar(aes(group, {{var1}}), stat = "identity")  
    geom_line(aes(group, {{var2}} * max({{var1}}), group = 1), col = "#1b98e0", lwd = 3)   
    scale_y_continuous(sec.axis = sec_axis(~ . / max(df %>% pull({{var1}}))))
  ggp1
}

Then try:

plot_func(data,sample, responses1)

On the other hand, if var1 and var2 are like this "sample" and "responses1", respectively, you can define the function this way:

plot_func2 <- function(df, var1, var2) {

  var1_max = max(data[[var1]])
  data$line_y = data[[var2]]*var1_max
  
  ggp1 <- ggplot(df)                       
    geom_bar(aes_string("group", var1), stat = "identity")  
    geom_line(aes_string("group", "line_y", "group" = 1), col = "#1b98e0", lwd = 3)  
    scale_y_continuous(sec.axis = sec_axis(~ . / var1_max))
  ggp1
}

And then use it like this:

var1="sample"
var2="responses1"
plot_func2(data,var1,var2)
  • Related