Search code examples
rggplot2dplyr

Within a custom function that makes a plot, can you set the linetype or color by variables to NULL?


I made a custom function, drugPlot, which plots drug response data and colors by a color variable and changes the linetype by a different variable. Here is simplified code to run this function:

# func to plot drug response
drugPlot <- function(df, drug, colorByVar, lineTypeVar){
  x<- df %>%
    filter(drug == !!drug) %>% 
           ggplot(aes(x = drugDose, y = viability, color=as.factor(.data[[colorByVar]]), linetype = as.factor(.data[[lineTypeVar]])) )+
                    labs( x = "Dose ", y = "Viability", color = colorByVar, linetype= lineTypeVar)+
      geom_point(size = 0.6)+
      geom_smooth( se=F, size = 0.5)
  
  return(x)
}

# example df
df <- data.frame(
   cellLine = rep(c("CellLine1", "CellLine2"), each = 4),
     subtype = rep(c("SubtypeA", "SubtypeB"), each = 4),
     drug = rep(c("DrugA", "DrugB", "DrugC"), each = 4 * 2),
     drugDose = rep(seq(1, 10, length.out = 4), 6),
     viability = rnorm(4 * 6, mean = 80, sd = 10)
 )
# run the func
 drugPlot(df, "DrugA", colorByVar = "subtype", lineTypeVar = "cellLine")

My question is: is there a way where I can make the linetype or color variables NULL? I use this function repeatedly and sometimes I'd like to have variables for both color and linetype but other times I just want color. Is there a way to do this without creating a new function?

I have tried setting lineTypeVar = NA, "", c(), but get an error each time.

Thank you!


Solution

  • Using an if and setting the default values for both optional arguments to NULL you could do:

    # example df
    df <- data.frame(
      cellLine = rep(c("CellLine1", "CellLine2"), each = 4),
      subtype = rep(c("SubtypeA", "SubtypeB"), each = 4),
      drug = rep(c("DrugA", "DrugB", "DrugC"), each = 4 * 2),
      drugDose = rep(seq(1, 10, length.out = 4), 6),
      viability = rnorm(4 * 6, mean = 80, sd = 10)
    )
    
    library(dplyr, warn = FALSE)
    library(ggplot2)
    
    drugPlot <- function(df,
                         drug,
                         colorByVar = NULL,
                         lineTypeVar = NULL) {
      df %>%
        filter(drug %in% .env$drug) %>%
        ggplot(aes(
          x = drugDose, y = viability,
          color = if (!is.null(colorByVar)) as.factor(.data[[colorByVar]]),
          linetype = if (!is.null(lineTypeVar)) as.factor(.data[[lineTypeVar]]),
        )) +
        labs(x = "Dose ", y = "Viability", color = colorByVar, linetype = lineTypeVar) +
        geom_point(size = 0.6) +
        geom_smooth(se = F, size = 0.5)
    }
    
    drugPlot(df, "DrugA", colorByVar = "subtype", lineTypeVar = "cellLine")
    

    
    drugPlot(df, "DrugA", colorByVar = "subtype")
    

    
    drugPlot(df, "DrugA")