R/figures.R

Defines functions metabolism_diag metabolism_trend plot_maven_overview

Documented in metabolism_diag metabolism_trend plot_maven_overview

#' Plot MAVEn experimental overview data.
#'
#' \code{plot_maven_overview} generates four plots to track the instrumental
#' timecourse and requires the full MAVEn dataset (readings + baseline)
#' generated by setting `baseline` = T in \code{read_maven}. The graphic can be
#' automatically saved.
#'
#' @param maven_raw Complete MAVEn dataset including baseline readings.
#' @param maven_experiment Experiment name. Applied to both figures and files.
#' @param outdir Folder where figure should be stored.
#' @param out_filename Figure name.
#' @param out_filetype Figure file type.
#'
#' @importFrom magrittr %>%
#' @importFrom dplyr select mutate
#' @importFrom tidyr pivot_longer
#' @importFrom ggplot2 ggplot ggsave aes geom_line facet_wrap labs theme
#' 
#' @return Four panel plot of experimental overview for quick diagnostics. Includes, Chamber readings, Thermocouple 1 (TC1), Flow rate in the sample/animal chamber (ml/min) (FRC_mlmin), and carbon dioxide (CO[2], ppm).
#' 
#' @export
plot_maven_overview <- function(maven_raw, maven_experiment = "",
                                outdir = NULL, out_filename = "ExpOverview",
                                out_filetype = ".png") {
  
  experiment <- maven_raw %>% 
    select(Seconds, TC1, FRC_mlmin, CO2ppm, Chamber) %>% 
    pivot_longer(names_to = "Measurement", 
                 values_to = "value", -Seconds) %>% 
    mutate(minutes = Seconds / 60)
  
  p <- ggplot(data = experiment, aes(x = minutes, y = value)) + 
    geom_line() + 
    facet_wrap(~Measurement, scales = "free_y", ncol = 1) + 
    labs(title = "MAVEn run summary", 
         x = "Time (min)", 
         y = "Result value",
         caption = maven_experiment) + 
    theme(plot.title.position = "plot", 
          plot.caption.position =  "plot")
  
  if(!is.null(outdir)){
    fpath <- file.path(outdir)
    
    if(!dir.exists(fpath)){
      dir.create(fpath)
    }
    
    outpath <- file.path(outdir, 
                         out_filename = paste0(Sys.Date(),"_",maven_experiment, 
                                               "_", out_filename, out_filetype))
    
    ggsave(p, filename = outpath, dpi = 300, scale = 1.5, 
           width = 4, height = 4)
  }
  
  return(p)
}


#'Plot animal metabolism trends.
#'
#' \code{metabolism_trend} graphcially displays the animal metabolism data by
#' chamber. The data are adjusted to a standardized measurement reading for
#' illustration.
#'
#' @param animal_metabolism animal metabolism dataframe extracted from the MAVEn
#'  without baseline using \code{extract_metabolism}.
#' @param maven_experiment Experiment name. Applied to both figures and files.
#' @param outdir Folder where figure should be stored.
#' @param out_filename Figure name.
#' @param out_filetype Figure file type.
#'
#' @importFrom magrittr %>%
#' @importFrom dplyr mutate
#' @importFrom ggplot2 ggplot aes geom_line facet_wrap labs scale_color_viridis_d theme ggsave
#' 
#' @return Plot of standardized metabolism readings for each cycle within each chamber. 
#' @export
#'
#' @examples #metabolism_trend(animal_metabolism, outdir = "output",
#' #out_filename = "", out_filetype = ".png")
metabolism_trend <- function(animal_metabolism, maven_experiment = "",
                            outdir = NULL, out_filename = "MetabolismTrends",
                            out_filetype = ".png") {
  
  p <- ggplot(data = animal_metabolism %>% 
                mutate(result = co2_convertion(result)), 
              aes(x = measurement_number, y = result, col = cycle)) + 
    geom_line(size = 2) + 
    facet_wrap(~ Chamber, scales = "free_y") + 
    labs(title = "Animal Metabolism Trends", 
         x = "Measurement Time", 
         y = expression(CO[2] ~ (mu * L ~ h^-1)),
         caption = maven_experiment) + 
    scale_color_viridis_d(option = "D", begin = 0.2, end = 0.8) +
    theme(legend.position = "bottom",
          plot.title.position = "plot", 
          plot.caption.position =  "plot")
  
  if(!is.null(outdir)){
    fpath <- file.path(outdir)
    
    if(!dir.exists(fpath)){
      dir.create(fpath)
    }
    
  outpath <- file.path(outdir, 
                       out_filename = paste0(Sys.Date(),"_",
                                             maven_experiment, "_",
                                             out_filename, out_filetype))
  
  ggsave(p, filename = outpath, dpi = 300, scale = 1.5, 
         width = 7, height = 4)}
  
  return(p)
}

#' Visual diagnostic for metabolism data using MAVEn with baseline
#'
#' @param maven_raw Complete MAVEn dataset including baseline readings.
#' @param metabolism_summary_cycle Dataframe calculated by
#'   \code{summarize_metabolism} with the "by_cycle" type indicated.
#' @param maven_experiment Experiment name. Applied to both figures and files.
#' @param outdir Folder where figure should be stored.
#' @param out_filename Figure name.
#' @param out_filetype Figure file type.
#'
#' @importFrom magrittr %>%
#' @importFrom dplyr select mutate
#' @importFrom tidyr pivot_longer
#' @importFrom ggplot2 ggplot aes facet_grid geom_line geom_point ggsave
#' 
#' @return Plot with raw MAVEn data and calculated median metabolism.
#' @export
#'
#' @examples #metabolism_diag(maven_raw, metabolism_summary_cycle, 
#' #outdir = "output", out_filename = "MetabolismDiagnostic", 
#' #out_filetype = ".png")
metabolism_diag <- function(maven_raw, metabolism_summary_cycle, 
                            maven_experiment = "",
                            outdir = NULL, 
                            out_filename = "MetabolismDiagnostic",
                            out_filetype = ".png") {
  
  df <- maven_raw %>% 
    select(Seconds:BP_kPa, c_FRC_mlmin:CO2_mlmin, 
           CO2_mlminFly1:CO2_mlminFly16) %>% 
    pivot_longer(cols = CO2_mlminFly1:CO2_mlminFly16, 
                 names_to = "parameter", 
                 values_to = "result") %>% 
    mutate(parameter = as.numeric(gsub(x = parameter, "CO2_mlminFly", "")),
           result = co2_convertion(result))
  
  
  p <- ggplot(data = df, aes(x = Seconds, y = result)) + 
    facet_grid(parameter ~ .) + 
    geom_line() + 
    geom_point(data = metabolism_summary_cycle %>% 
                 mutate(parameter = Chamber), 
               aes(x = median_time, y = median_co2_ul.h, 
                   col = parameter), 
               size = 3, col = "red") + 
    labs(title = "Metabolism diagnostic", 
         x = "Seconds", 
         y = expression(CO[2] ~ (mu * L ~ h^-1)),
         caption = maven_experiment) +
    theme(legend.position = "none",
          plot.title.position = "plot", 
          plot.caption.position =  "plot")
  
  if(!is.null(outdir)){
    fpath <- file.path(outdir)
    
    if(!dir.exists(fpath)){
      dir.create(fpath)
    }
    
  outpath <- file.path(outdir, 
                       out_filename = paste0(Sys.Date(),"_",
                                             maven_experiment, "_",
                                             out_filename, out_filetype))
  
  ggsave(p, filename = outpath, dpi = 300, scale = 1.5, 
         width = 4, height = 8)}
  
  return(p)
  
}

#'Plot animal activity trends.
#'
#' \code{activity_trend} graphcially displays the animal activity data by chamber.
#' The data are adjusted to a standardized measurement reading for illustration.
#'
#' @param animal_activity animal activity dataframe extracted from the MAVEn without
#'  baseline using \code{extract_activity}.
#' @param maven_experiment Experiment name. Applied to both figures and files.
#' @param outdir Folder where figure should be stored.
#' @param out_filename Figure name.
#' @param out_filetype Figure file type.
#' @param activity_baseline Baseline value for data inclusion.
#'
#' @export
#' @importFrom ggplot2 ggplot aes geom_point facet_wrap labs scale_color_viridis_d
#' scale_y_continuous geom_hline theme ggsave
#'
#' @return Plot of standardized activity readings for each cycle within each chamber 
#' for selected interval. 
#'
#' @examples 
#' #activity_trend(animal_activity, maven_experiment = "experiment_name")
activity_trend <- function(animal_activity, 
                           maven_experiment = "",
                           outdir = NULL, 
                           out_filename = "ActivityTrends", 
                           out_filetype = ".png",
                           activity_baseline = "") {
  
  p <- ggplot(data = animal_activity, 
              aes(x = measurement_number, y = result, col = cycle)) + 
    geom_point() +
    geom_point(data = animal_activity %>% 
                 filter(result_flag == "bth"), 
                        col = "grey") + # color the points below the threshold
    facet_wrap(~ Chamber) + 
    scale_y_continuous(limits = c(0, NA)) +
    labs(title = "Animal Activity Trends", 
         x = "Measurement Number", 
         y = "Activity",
         caption = maven_experiment) + 
    scale_color_viridis_d(option = "D", begin = 0.2, end = 0.8) +
    geom_hline(yintercept = activity_baseline) +
    theme(legend.position = "bottom",
          plot.title.position = "plot", 
          plot.caption.position =  "plot")
  
  if(!is.null(outdir)){
    fpath <- file.path(outdir)
    
    if(!dir.exists(fpath)){
      dir.create(fpath)
    }
    
  outpath <- file.path(outdir, 
                       out_filename = paste0(Sys.Date(),"_", 
                                             maven_experiment, "_",
                                             out_filename, out_filetype))
  
  ggsave(p, filename = outpath, dpi = 300, scale = 1.5, 
         width = 7, height = 4)}
  
  return(p)
}



#' Visual diagnostic for activity data using MAVEn with baseline
#'
#' @param maven_raw Complete MAVEn dataset including baseline readings.
#' @param metabolism_summary_cycle Dataframe calculated by
#'   \code{summarize_metabolism} with the "by_cycle" type indicated.
#' @param activity_summary_cycle Dataframe calculated by
#'   \code{summarize_activity} with the "by_cycle" type indicated.
#' @param maven_experiment Experiment name. Applied to both figures and files.
#' @param interval Time interval for analysis. 
#' @param outdir Folder where figure should be stored.
#' @param out_filename Figure name.
#' @param out_filetype Figure file type.
#' 
#' @importFrom magrittr %>%
#' @importFrom dplyr select mutate
#' @importFrom tidyr pivot_longer
#' @importFrom ggplot2 ggplot aes geom_point facet_grid labs theme element_text geom_rect geom_line scale_fill_manual scale_color_manual ggsave
#' @importFrom cowplot plot_grid
#' @importFrom stats setNames
#' 
#' @return Plot with raw MAVEn data, calculated median metabolism, and 
#' animal activity. Coloured boxes represent the calculated activity 
#' state based on activity threshold.
#'
#' @export
#'
activity_diag <- function(maven_raw = "maven_raw",
                          metabolism_summary_cycle = "metabolism_summary_cycle",
                          activity_summary_cycle = "activity_summary_cycle",
                          interval = "",
                          outdir = NULL,
                          maven_experiment = "",
                          out_filename = "ActivityDiagnostic",
                          out_filetype = ".png") {
  
  df <- maven_raw %>%
    select(Seconds:BP_kPa, c_FRC_mlmin:CO2_mlmin, Act_1:Act_16) %>%
    pivot_longer(cols = Act_1:Act_16,
                 names_to = 'parameter',
                 values_to = 'result') %>%
    mutate(parameter = as.numeric(gsub(x = parameter, 'Act_', '')))
  
  
  maven_summary <- maven_datatable(metabolism_summary_cycle,
                                   activity_summary_cycle,
                                   out_filename = NULL) %>%
    mutate(parameter = Chamber,
           interval.start = median_time - interval,
           interval.end = median_time + interval)
  
  
  p.met <- ggplot(data = maven_summary,
                  aes(x = cycle,
                      y = median_co2_ul.h,
                      col = parameter, shape = cycle)) +
    geom_point(size = 2, col = "blue") +
    facet_grid(parameter ~ .) +
    labs(x = "cycle", y = expression(Median~CO[2]),
         title = "Activity diagnostic",
         subtitle = "median metabolism") +
    theme(legend.position = "none",
          plot.caption = element_text(hjust = 0),
          plot.title.position = "plot",
          plot.caption.position =  "plot")
  
  activity_colors <- setNames(c("#1B9E77", "#D95F02", "grey"),
                              c("Active", "Inactive", "Inactive (< Threshold)"))
  
  p <- ggplot() +
    geom_rect(data = maven_summary,
              aes(xmin = interval.start,
                  xmax = interval.end,
                  ymin = -Inf,
                  ymax = Inf, fill = activity_state),
              alpha = 0.4) +
    geom_line(data = df, aes(x = Seconds, y = result)) +
    facet_grid(parameter ~ .) +
    geom_point(data = maven_summary,
               aes(x = median_time,
                   y = mean_activity,
                   col = activity_state, shape = cycle)) +
    labs(subtitle = 'activity timeseries',
         x = 'Seconds',
         y = "Activity",
         caption = maven_experiment) +
    theme(legend.position = "bottom",
          plot.title.position = "plot",
          plot.caption.position =  "plot") +
    scale_fill_manual(values = activity_colors) +
    scale_color_manual(values = activity_colors)

  
  p.merge <- plot_grid(p.met, p, ncol = 2, align = "hv", axis = "tb",
                       rel_widths = c(0.75,2))
  
  if(!is.null(outdir)){
    fpath <- file.path(outdir)
    
    if(!dir.exists(fpath)){
      dir.create(fpath)
    }
    
  outpath <- file.path(outdir,
                       out_filename = paste0(Sys.Date(),"_",
                                             maven_experiment, "_",
                                             out_filename, out_filetype))
  
  ggsave(p.merge, filename = outpath, dpi = 300, scale = 1.5,
         width = 6, height = 8)}
  
  return(p.merge)
}
dapperstats/MAVEn documentation built on Jan. 22, 2021, 3:39 p.m.