R/xic_plot.R

Defines functions xic_plot

Documented in xic_plot

#' Make an Extracted Ion Chromatogram
#'
#' @description Generates an interactive or static plot of a XIC generated by get_xic
#'
#' @param XICobj Object of the xic class from get_xic
#' @param Smooth A True/False to indicate whether the plot should be smoothed. Default is FALSE.
#' @param Interactive A True/False to indicate whether the plot should be interactive. Default is FALSE.
#'
#' @examples
#' \dontrun{
#'
#' # Test with bottom up data. See ?get_xic
#' xic_plot(xictest1)
#' xic_plot(xictest1, Smooth = TRUE, Interactive = TRUE)
#'
#' # Test with top down raw data. See ?get_xic
#' xic_plot(xictest2)
#'
#' }
#' @export
xic_plot <- function(XICobj,
                     Smooth = FALSE,
                     Interactive = FALSE) {

  ##################
  ## CHECK INPUTS ##
  ##################

  # Assert that ScanMetadata is a ScanMetadata object.
  if ("xic_pspecter" %in% class(XICobj) == FALSE) {
    stop("XICobj must be a xic_pspecter object generated by get_xic.")
  }

  # Assert that smooth is a logical and not NA
  if (!is.logical(Smooth) || is.na(Smooth)) {
    stop("Smooth parameter must be either TRUE or FALSE.")
  }

  # Assert that interactive is a logical and not NA
  if (!is.logical(Interactive) || is.na(Interactive)) {
    stop("Interactive parameter must be either TRUE or FALSE.")
  }

  #######################
  ## MAKE THE XIC PLOT ##
  #######################

  # Pull out the XIC
  XIC <- XICobj

  # Add trace information for labels
  XIC$Trace <- paste0("[M+", XIC$Isotope, "]^", XIC$Charge)

  # Use smoothing if directed
  if (Smooth) {
    XIC_Plot <- ggplot2::ggplot(XIC, ggplot2::aes(x = RT, y = Intensity, color = Trace)) +
      ggplot2::geom_smooth(se = FALSE) + ggplot2::theme_bw() + ggplot2::ggtitle(paste0("M/Z: ", attr(XICobj, "pspecter")$MZ)) +
      ggplot2::theme(legend.title = ggplot2::element_blank(), plot.title = ggplot2::element_text(hjust = 0.5)) +
      ggplot2::xlab("Retention Time") + ggplot2::ylim(c(0, NA))
  } else {
    XIC_Plot <- ggplot2::ggplot(XIC, ggplot2::aes(x = RT, y = Intensity, color = Trace)) +
      ggplot2::geom_line() + ggplot2::theme_bw() + ggplot2::ggtitle(paste0("M/Z: ", attr(XICobj, "pspecter")$MZ)) +
      ggplot2::theme(legend.title = ggplot2::element_blank(), plot.title = ggplot2::element_text(hjust = 0.5)) +
      ggplot2::xlab("Retention Time")
  }

  # Return either static or interactive plot
  if (Interactive) {XIC_Plot %>% plotly::ggplotly()} else {XIC_Plot}

}
EMSL-Computing/pspecterlib documentation built on Jan. 28, 2024, 8:13 p.m.