R/olink_qc_plot.R

Defines functions olink_qc_plot

Documented in olink_qc_plot

#' Function to plot an overview of a sample cohort per Panel.
#'
#' @description
#' Generates a facet plot per Panel using ggplot2::ggplot and
#' ggplot2::geom_point and stats::IQR plotting IQR vs. median for all samples.
#' Horizontal dashed lines indicate \eqn{\pm}\var{IQR_outlierDef} standard
#' deviations from the mean IQR (default 3). Vertical dashed lines indicate
#' \eqn{\pm}\var{median_outlierDef} standard deviations from the mean sample
#' median (default 3).
#'
#' @param df NPX data frame in long format. Must have columns SampleID, NPX and
#' Panel.
#' @param check_log Optional named list returned by [`check_npx()`]. If `NULL`,
#' an attached `check_log` is used when present; otherwise [`check_npx()`] will
#' be run internally using `df`.
#' @param color_g Character value indicating which column to use as fill color
#' (default QC_Warning). Continuous color scale for Olink(R) Sample Index (OSI)
#' columns OSITimeToCentrifugation, OSIPreparationTemperature and OSISummary is
#' also supported.
#' @param plot_index Boolean. If FALSE (default), a point will be plotted for a
#' sample. If TRUE, a sample's unique index number is displayed.
#' @param label_outliers Boolean. If TRUE, an outlier sample will be labelled
#' with its SampleID. (default FALSE)
#' @param IQR_outlierDef The number of standard deviations from the mean IQR
#' that defines an outlier. (default 3)
#' @param median_outlierDef The number of standard deviations from the mean
#' sample median that defines an outlier. (default 3)
#' @param outlierLines Draw dashed lines at \eqn{\pm}\var{IQR_outlierDef} and
#' \eqn{\pm}\var{median_outlierDef} standard deviations from the mean IQR and
#' sample median respectively. (default TRUE)
#' @param facetNrow The number of rows that the panels are arranged on.
#' @param facetNcol The number of columns that the panels are arranged on.
#' @param ... coloroption passed to specify color order.
#'
#' @return An object of class "ggplot". Scatterplot shows IQR vs median for all
#' samples per panel
#'
#' @keywords NPX
#'
#' @export
#'
#' @examples
#' \donttest{
#' if (rlang::is_installed(pkg = c("ggrepel"))) {
#'
#'   # standard plot
#'   OlinkAnalyze::olink_qc_plot(
#'     df = OlinkAnalyze::npx_data1,
#'     color_g = "QC_Warning",
#'     label_outliers = TRUE
#'   )
#'
#'   # Change the outlier threshold to +/-4SD
#'   OlinkAnalyze::olink_qc_plot(
#'     df = OlinkAnalyze::npx_data1,
#'     color_g = "QC_Warning",
#'     IQR_outlierDef = 4L,
#'     median_outlierDef = 4L,
#'     label_outliers = TRUE
#'   )
#'
#'   # Identify the outliers
#'   qc <- OlinkAnalyze::olink_qc_plot(
#'     df = OlinkAnalyze::npx_data1,
#'     color_g = "QC_Warning",
#'     IQR_outlierDef = 4L,
#'     median_outlierDef = 4L,
#'     label_outliers = TRUE
#'   )
#'
#'   outliers <- qc$data |>
#'     dplyr::filter(
#'       .data[["Outlier"]] == 1L
#'     )
#' }
#' }
#'
olink_qc_plot <- function(df,
                          check_log = NULL,
                          color_g = "QC_Warning",
                          plot_index = FALSE,
                          label_outliers = FALSE,
                          IQR_outlierDef = 3L, # nolint: object_name_linter
                          median_outlierDef = 3L, # nolint: object_name_linter
                          outlierLines = TRUE, # nolint: object_name_linter
                          facetNrow = NULL, # nolint: object_name_linter
                          facetNcol = NULL, # nolint: object_name_linter
                          ...) {

  #checking ellipsis
  if (length(list(...)) > 0L) {

    ellipsis_variables <- names(list(...))

    if (length(ellipsis_variables) == 1L) {

      if (!(ellipsis_variables == "coloroption")) {

        stop(paste0("The ... option only takes the coloroption argument. ",
                    "... currently contains the variable ",
                    ellipsis_variables,
                    "."))

      }

    } else {

      stop(paste0("The ... option only takes one argument.
                  ... currently contains the variables ",
                  paste(ellipsis_variables, collapse = ", "),
                  "."))
    }
  }

  # check input
  check_is_dataset(x = df, error = TRUE)

  # Remove invalid OlinkID, assays with all NA values, and convert non-unique
  # Uniprot IDs. Note that we do not remove samples with duplicate SampleID,
  # control samples or assays, or samples/assays with QC warnings, as this
  # would be the user's decision.
  df <- run_clean_npx(
    df = df,
    check_log = get_check_npx(df = df, check_log = check_log),
    remove_assay_na = TRUE,
    remove_invalid_oid = TRUE,
    remove_dup_sample_id = FALSE,
    remove_control_assay = FALSE,
    remove_control_sample = FALSE,
    remove_qc_warning = FALSE,
    remove_assay_warning = FALSE,
    convert_nonunique_uniprot = TRUE,
    out_df = "tibble",
    verbose = FALSE
  )

  check_log <- get_check_npx(df = df)

  # check IQR_outlierDef and median_outlierDef
  check_is_scalar_numeric(x = IQR_outlierDef, error = TRUE)
  check_is_scalar_numeric(x = median_outlierDef, error = TRUE)

  if (plot_index == TRUE && !("Index" %in% names(df))) {
    warning("Index not available. Setting plot_index to FALSE.")
    plot_index <- FALSE
  }

  # OSI checks - ran only if OSI columns selected to color
  osi_cat_cols <- c("OSICategory")
  osi_cont_cols <- c("OSITimeToCentrifugation",
                     "OSIPreparationTemperature",
                     "OSISummary")

  if (color_g %in% c(osi_cat_cols, osi_cont_cols)) {

    # Check for invalid values and NA columns
    df <- check_osi(df = df,
                    osi_score = color_g)
  }

  if ("qc_warning" %in% names(check_log$col_names)) {
    df_qr <- df |>
      olink_summarize_qc_warning(
        qc_warning = check_log$col_names$qc_warning,
        group = c(
          check_log$col_names$panel,
          check_log$col_names$sample_id
        )
      )
  }

  df_qr <- df_qr |>
    dplyr::group_by(
      .data[[check_log$col_names$panel]],
      .data[[check_log$col_names$sample_id]]
    ) |>
    dplyr::mutate(
      IQR = stats::IQR(
        x = .data[[check_log$col_names$quant]],
        na.rm = TRUE
      ),
      sample_median = stats::median(
        x = .data[[check_log$col_names$quant]],
        na.rm = TRUE
      )
    ) |>
    dplyr::ungroup() |>
    dplyr::select(
      dplyr::all_of(
        c(check_log$col_names$sample_id,
          check_log$col_names$panel,
          "IQR",
          "sample_median",
          color_g
        )
      )
    ) |>
    dplyr::distinct() |>
    dplyr::group_by(
      .data[[check_log$col_names$panel]]
    ) |>
    dplyr::mutate(
      median_low = mean(.data[["sample_median"]],
                        na.rm = TRUE) -
        .env[["median_outlierDef"]] * stats::sd(.data[["sample_median"]],
                                                na.rm = TRUE),
      median_high = mean(.data[["sample_median"]], na.rm = TRUE) +
        .env[["median_outlierDef"]] * stats::sd(.data[["sample_median"]],
                                                na.rm = TRUE),
      iqr_low = mean(.data[["IQR"]], na.rm = TRUE) -
        .env[["IQR_outlierDef"]] * stats::sd(.data[["IQR"]],
                                             na.rm = TRUE),
      iqr_high = mean(.data[["IQR"]], na.rm = TRUE) +
        .env[["IQR_outlierDef"]] * stats::sd(.data[["IQR"]],
                                             na.rm = TRUE)
    ) |>
    dplyr::ungroup() |>
    dplyr::mutate(
      Outlier = dplyr::if_else(
        .data[["sample_median"]] < .data[["median_high"]] &
          .data[["sample_median"]] > .data[["median_low"]] &
          .data[["IQR"]] > .data[["iqr_low"]] &
          .data[["IQR"]] < .data[["iqr_high"]],
        0L,
        1L
      )
    )

  qc_plot <- df_qr |>
    dplyr::mutate(
      !!check_log$col_names$panel := stringr::str_replace(
        string = .data[[check_log$col_names$panel]],
        pattern = "Olink ",
        replacement = ""
      )
    ) |>
    ggplot2::ggplot(
      mapping = ggplot2::aes(
        x = .data[["sample_median"]],
        y = .data[["IQR"]]
      )
    ) +
    ggplot2::xlab(
      label = "Sample Median"
    ) +
    ggplot2::facet_wrap(
      facets = ggplot2::vars(.data[[check_log$col_names$panel]]),
      scale = "free",
      nrow = facetNrow,
      ncol = facetNcol
    ) +
    OlinkAnalyze::set_plot_theme()

  if (color_g %in% osi_cont_cols) {

    qc_plot <- qc_plot +
      ggplot2::scale_color_gradient(
        low = "#FFB200FF",
        high = "#332D56FF",
        limits = c(0L, 1L),
        breaks = seq(from = 0L, to = 1L, by = 0.25),
        oob = scales::squish
      )

  } else {
    qc_plot <- qc_plot +
      OlinkAnalyze::olink_color_discrete(...)
  }

  # Add outlier lines
  if (outlierLines == TRUE) {
    qc_plot <- qc_plot +
      ggplot2::geom_hline(
        mapping = ggplot2::aes(
          yintercept = .data[["iqr_low"]]
        ),
        linetype = "dashed",
        color = "grey"
      ) +
      ggplot2::geom_hline(
        mapping = ggplot2::aes(
          yintercept = .data[["iqr_high"]]
        ),
        linetype = "dashed",
        color = "grey"
      ) +
      ggplot2::geom_vline(
        mapping = ggplot2::aes(
          xintercept = .data[["median_low"]]
        ),
        linetype = "dashed",
        color = "grey"
      ) +
      ggplot2::geom_vline(
        mapping = ggplot2::aes(
          xintercept = .data[["median_high"]]
        ),
        linetype = "dashed",
        color = "grey"
      )
  }

  if (plot_index == TRUE) {
    qc_plot <- qc_plot +
      ggplot2::geom_text(
        mapping = ggplot2::aes(
          color = .data[[color_g]],
          label = .data[["Index"]]
        ),
        size = 3L
      )
  } else {
    qc_plot <- qc_plot +
      ggplot2::geom_point(
        mapping = ggplot2::aes(
          color = .data[[color_g]]
        ),
        size = 2.5
      )
  }

  if (label_outliers == TRUE) {

    rlang::check_installed(
      pkg = c("ggrepel"),
      call = rlang::caller_env()
    )

    outlier_labels <- qc_plot@data |>
      dplyr::mutate(
        SampleIDPlot = dplyr::if_else(
          .data[["Outlier"]] == 1L,
          .data[["SampleID"]],
          ""
        )
      )

    qc_plot <- qc_plot +
      ggrepel::geom_label_repel(
        data = outlier_labels,
        mapping = ggplot2::aes(
          label = .data[["SampleIDPlot"]]
        ),
        box.padding = 0.5,
        min.segment.length = 0.1,
        show.legend = FALSE,
        size = 3L
      )
  }

  return(qc_plot)

}

Try the OlinkAnalyze package in your browser

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

OlinkAnalyze documentation built on Sept. 18, 2026, 5:06 p.m.