1

I am trying to figure out the best way of utilising conditional clauses together with ggplot2 to introduce the logic of which layers to plot. In my real cases I sometimes have data frames that will turn out to be empty and I would like to catch that case and avoid plotting if lets say nrow(df) == 0. I created some simulation data to test conditional clauses and ggplot2 but clearly IF clauses cannot be processed within a ggplot() call.

Obviously I would like to avoid having loads of conditionals that in the end invoke a separate ggplot() call depending on if my data frame layers are populated or not.

Below is my attempt to plot df3 only using conditional clauses to select the layer to plot. In an expanded case, as mentioned above, I would like to over-plot multiple layers based on some different conditional clauses being assessed as TRUE e.g. to plot df1 and df2 if both logicals in the if clauses return TRUE.

  #########################################
  ## Using if functions within ggplot2() ##
  #########################################

  #rm(list=ls())
  library(ggplot2)
  ##Generat simul data
  df1_gene_list <- c("a", "b", "c", "d", "e", "f")
  df2_gene_list <- c("A", "B", "C", "D", "E", "F")
  df3_gene_list <- c("Aa", "Bb", "Cc", "Dd", "Ee", "Ff")
  df1 <- data.frame(x = df1_gene_list, y = rnorm(6))
  df2 <- data.frame(x = df2_gene_list, y = rnorm(6))
  df3 <- data.frame(x = df2_gene_list, y = rnorm(6))
  df1$grp <- c( rep(c(1),3), rep(c(2), 3) )
  df1$col  <- c( rep(c("grey"),3), rep(c("blue"), 3) )
  df2$grp <- c( rep(c(1),3), rep(c(2), 3) )
  df2$col  <- c( rep(c("grey"),3), rep(c("blue"), 3) )
  df3$grp <- c( rep(c(1),3), rep(c(2), 3) )
  df3$col  <- c( rep(c("grey"),3), rep(c("blue"), 3) )



  ##Reformat order
  my_factor <- factor(df1_gene_list, levels = df1_gene_list)
  df1$x <- my_factor

  my_factor <- factor(df2_gene_list, levels = df2_gene_list)
  df2$x <- my_factor

  my_factor <- factor(df3_gene_list, levels = df3_gene_list)
  df3$x <- my_factor

  ggplot() +
    if(FALSE){
      geom_col(df1, mapping = aes(x=x, y=y, fill = y)) 
    }
    else if(FALSE){
     geom_col(df2, mapping = aes(x=x, y=y, fill = y)) 
     }
    else if(TRUE){
      geom_col(df3, mapping = aes(x=x, y=y, fill = y))
    }

Axeman
  • 32,068
  • 8
  • 81
  • 94
S.Jamal
  • 137
  • 2
  • 11

0 Answers0