R/plotting_output.R

#' @title plots a combination plot e.g. CHAIN + SATURATION. Replacement for lipidPlot
#'
#' @description  This makes a combination plot
#' @param treat_groups takes an object generated by summarise_lipids function
#' @param columns takes an object generated by summarise_lipids function
#' @param select_chains takes an object generated by summarise_lipids function
#' @param statistic takes an object generated by summarise_lipids function
#' @import ggplot2
#' @import tidyverse
#' @import purrr
#' @import magrittr
#' @export plotting_output
#' @return NULL
plotting_output = function(filename, treat_groups=NULL, columns, select_chains=NULL, statistic = 'means +/- se'){

  raw = parse_raw(filename = filename,
                  selected_chains = select_chains,
                  columns = columns,
                  treat_groups = treat_groups
  )


  if(length(treat_groups) == 2 & statistic != 'percentage'){

    chainsum = summarise_lipids(raw, grouping = 'CHAIN', statistic = statistic)
    saturationsum = summarise_lipids(raw, grouping = 'SATURATION', statistic = statistic)

    p1 = lipidPlot(chainsum)
    p2 = lipidPlot(saturationsum)

    pymin = ggplot_build(p1)$layout$panel_params[[1]]$y.range[1]
    pymax = ggplot_build(p1)$layout$panel_params[[1]]$y.range[2]
    title = ''

    if (statistic == 'means +/- se'){

      xmin = 5
      xmax = 12.5
      ymin = pymax/2
      ymax = Inf
      position = c(0.9,0.75)

    } else if(statistic == 'response'){

      xmin = 3.5
      xmax = 6.5
      ymin = ifelse(abs(pymin)>pymax, -Inf, pymax/2)
      ymax = ifelse(abs(pymin)>pymax, pymin/2, Inf)
      position = if (abs(pymin)>pymax) c(0.9,0.1) else c(0.9,0.75)
      title = paste0(raw@treatments, collapse = '-')

    }

    plot = p1 +
      annotation_custom(
        ggplotGrob(p2 + theme(legend.justification=c(1,-0.1), legend.position=position)),
        xmin = xmin, xmax = xmax, ymin = ymin , ymax = ymax
      )


  } else {

    chainsum = summarise_lipids(raw, grouping = 'CHAIN', statistic = statistic)

    plot = lipidPlot(chainsum)

  }

  return(plot)

}
GitShepard1/lipidtools documentation built on May 15, 2019, 10:47 a.m.