Home > OS >  How to parameterize code for adding layers in ggplot2
How to parameterize code for adding layers in ggplot2

Time:09-17

We know that ggplot2 includes a special method for ggplot objects, which uses to add layers to plots.

library(ggplot2)
df <- structure(list(Percent = c(1, 2, 3, 4, 5), 
               Test = c(4, 2, 3, 5, 2),
               Train = c(10, 12, 10, 13, 15)), 
          .Names = c("Percent", "Test", "Train"), 
          row.names = c(NA, 5L), class = "data.frame")

ggplot(df, aes(x = Percent))   
  geom_point(aes(y = Test), colour = "red")   
  geom_line(aes(y = Test), colour = "red")

Out:

enter image description here

I turned the above plotting program into a function plot_func, but I hope we could control whether I need to add scatter via a parameter, not by commenting out this line: geom_point(aes(y = Test ), colour = "red") .

plot_func <- function(data){
  p <- ggplot(df, aes(x = Percent))   
    geom_point(aes(y = Test), colour = "red")   
    geom_line(aes(y = Test), colour = "red")
  return(print(p))
}

plot_func(df)

The expected result would be something like this. Suppose we have a parameter add_point in our function plot_func, and we set add_point=FALSE, it will achieve a plot similar to that after commenting out geom_point(aes(y = Test), colour = "red") .

How to achieve this? Thanks.

plot_func <- function(data, add_point=FALSE){
  p <- ggplot(df, aes(x = Percent))   
    # geom_point(aes(y = Test), colour = "red")   
    geom_line(aes(y = Test), colour = "red")
  return(print(p))
}

plot_func(df)

Out:

enter image description here

CodePudding user response:

As @Limey suggests in his comments, here is how we could do it:

with if ... else:

plot_func <- function(data, add_point) {
  
  if (add_point == TRUE) {
    p1 <- ggplot(data, aes(x = Percent))   
      geom_point(aes(y = Test), colour = "red")   
      geom_line(aes(y = Test), colour = "red")
    return(p1)
    }
  else  {
    p2 <- ggplot(data, aes(x = Percent))   
    geom_line(aes(y = Test), colour = "red")
    return(p2)
    }
  }

or if ... if

plot_func <- function(data, add_point) {
  
  if (add_point == TRUE) {
    p1 <- ggplot(data, aes(x = Percent))   
      geom_point(aes(y = Test), colour = "red")   
      geom_line(aes(y = Test), colour = "red")
    return(p1)
    }
  if (add_point == FALSE) {
    p2 <- ggplot(data, aes(x = Percent))   
    geom_line(aes(y = Test), colour = "red")
    return(p2)
    }
  }
plot_func(df, FALSE)

enter image description here

plot_func(df, TRUE)

enter image description here

  • Related