R/uplot_freq_ma.R

Defines functions uplot_freq_ma

Documented in uplot_freq_ma

#' @title Histogram of Mass Accuracy
#' @name uplot_freq_ma
#' @family plots
#'
#' @description
#' Creates a histogram of mass accuracy values (ppm).
#' Includes summary statistics (median, 2.5% and 97.5% quantiles).
#' Follows general uplot behavior:
#'   - returns a ggplot2 object by default
#'   - converts to plotly *only if* plotly = TRUE
#'   - uses caption-style UME logo
#'
#' @inheritParams main_docu
#'
#' @param ma_col Character string. Column name containing mass accuracy values.
#' @param col Histogram fill color.
#'
#' @return ggplot2 object, or plotly object if plotly = TRUE.
#'
#' @import data.table
#' @import ggplot2
#' @importFrom plotly ggplotly
#' @export
uplot_freq_ma <- function(
    mfd,
    ma_col = "ppm",
    col = "grey",
    gg_size = 12,
    logo = TRUE,
    plotly = FALSE,
    ...
) {

  mfd <- data.table::as.data.table(mfd)

  # ---- Check column -----------------------------------------------------------
  if (!ma_col %in% names(mfd)) {
    stop("Column '", ma_col, "' not found in dataset.")
  }

  x <- mfd[[ma_col]]

  # ---- Summary statistics ------------------------------------------------------
  med  <- round(stats::median(x, na.rm = TRUE), 2)
  q975 <- round(stats::quantile(x, 0.975, na.rm = TRUE), 2)
  q025 <- round(stats::quantile(x, 0.025, na.rm = TRUE), 2)

  title_text <- paste0(
    "Mass accuracy histogram\n",
    "(Median: ", med, " ppm; ",
    "97.5% quantile: ", q975, " ppm; ",
    "2.5% quantile: ", q025, " ppm)"
  )

  # ---- ggplot construction ----------------------------------------------------
  p <- ggplot2::ggplot(mfd, aes(x = .data[[ma_col]])) +
    geom_histogram(
      bins = 100,
      fill = col,
      color = "black",
      linewidth = 0.25
    ) +
    labs(
      title   = title_text,
      x       = "Mass accuracy (ppm)",
      y       = "Count",
      caption = if (logo) "UltraMassExplorer" else NULL
    ) +
    theme_minimal(base_size = gg_size) +
    theme(
      plot.title  = element_text(size = gg_size + 3, face = "bold"),
      axis.title  = element_text(size = gg_size + 2),
      axis.text   = element_text(size = gg_size),
      plot.caption = element_text(
        size = gg_size - 2,
        hjust = 1,
        face = "italic",
        colour = "grey40"
      )
    )

  # ---- Convert to plotly only if requested -----------------------------------
  if (isTRUE(plotly)) {
    return(plotly::ggplotly(p))
  }

  # ---- Return ggplot ----------------------------------------------------------
  return(p)
}

Try the ume package in your browser

Any scripts or data that you put into this service are public.

ume documentation built on Dec. 13, 2025, 1:06 a.m.