#' Make a bar plot of fragments per ion
#'
#' @description Generates a bar plot of counts of all fragments, fragments without
#' isotopes, and fragments with unique charge states per ion.
#'
#' @param MatchedPeaks Object of the matched_peaks class from get_matched_peaks. Default is NULL. Required.
#' @param Interactive A logical to determine whether the plot should be interactive or not. Default is FALSE.
#'
#' @examples
#' \dontrun{
#'
#' # Test with bottom up data
#' BU_Peak <- get_peak_data(ScanMetadata = BU_ScanMetadata, ScanNumber = 31728)
#' BU_Match <- get_matched_peaks(ScanMetadata = BU_ScanMetadata, PeakData = BU_Peak)
#'
#' # Make the plot interactive or not
#' ion_bar_plot(MatchedPeaks = BU_Match)
#' ion_bar_plot(MatchedPeaks = BU_Match, Interactive = TRUE)
#'
#' }
#'
#' @export
ion_bar_plot <- function(MatchedPeaks,
Interactive = FALSE) {
##################
## CHECK INPUTS ##
##################
# Assert that Matched Peaks is of the correct type
if (is.null(MatchedPeaks) == FALSE && "matched_peaks" %in% class(MatchedPeaks) == FALSE) {
stop("MatchedPeaks must be of the class matched_peaks generated by get_matched_peaks.")
}
# Assert that Interactive is a single logical
if (is.logical(Interactive) == FALSE || length(Interactive) > 1) {
stop("Interactive must be a single logical value TRUE or FALSE.")
}
if (is.na(Interactive)) {
Interactive <- FALSE
}
############################
## DEFINE LOCAL FUNCTIONS ##
############################
countBar <- function(vector) {
counts <- vector %>% table() %>% data.frame()
colnames(counts) <- c("Ion", "Count")
counts <- rbind(counts, data.frame("Ion" = "Total", "Count" = sum(counts$Count)))
return(counts)
}
#############################
## GENERATE PLOT DATAFRAME ##
#############################
# Get MatchedPeaks object
class(MatchedPeaks) <- "data.frame"
# Count All Ions
IonsAll <- countBar(MatchedPeaks$Type)
# Count Ions Exluding Isotopes
IonsNoIso <- MatchedPeaks %>% subset(Isotope == "M") %>% dplyr::select(Type) %>% countBar()
# Count Unique Ions Per Fragment
IonsUnique <- MatchedPeaks %>% dplyr::select(Ion, Type) %>% unique() %>% dplyr::select(Type) %>% countBar()
# Generate plotting dataframe
BarplotDF <- cbind("Method" = c(rep("All Ions", nrow(IonsAll)),
rep("Ions without Isotopes", nrow(IonsNoIso)),
rep("Unique ions per fragment", nrow(IonsUnique))),
rbind(IonsAll, IonsNoIso, IonsUnique)) %>% data.frame()
###############
## MAKE PLOT ##
###############
# Generate the plot
BarPlot <- ggplot2::ggplot(BarplotDF, ggplot2::aes(x = Ion, y = Count, fill = Method)) +
ggplot2::geom_bar(stat = "identity", position = ggplot2::position_dodge(), color = "black") +
ggplot2::theme_bw() + ggplot2::scale_fill_brewer(palette = "greens")
# Return interactive if TRUE
if (Interactive) {
return(BarPlot %>% plotly::ggplotly())
} else {return(BarPlot)}
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.