{"repo_name": "ggalign", "file_name": "/ggalign/R/fortify-matrix-.R", "inference_info": {"prefix_code": "#' Build a Matrix\n#'\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' This function converts various objects into a matrix format. By default, it\n#' calls [`as.matrix()`] to build a matrix.\n#'\n#' @param data An object to be converted into a matrix.\n#' @param ... Additional arguments passed to methods.\n#' @param data_arg The argument name for `data`. Developers can use it to\n#' improve messages. Not used by the user.\n#' @param call The execution environment where `data` and other arguments for\n#' the method are collected. Developers can use it to improve messages. Not\n#' used by the user.\n#' @return A matrix.\n#' @eval\n#' rd_collect_family(\"fortify_matrix\", \"`fortify_matrix` method collections\")\n#' @export\nfortify_matrix <- function(data, ..., data_arg = NULL,\n call = NULL) {\n UseMethod(\"fortify_matrix\")\n}\n\n#' @inheritParams rlang::args_dots_empty\n#' @inherit fortify_matrix title return\n#' @description\n#' By default, it calls [`as.matrix()`] to build a matrix.\n#' @inheritParams fortify_matrix\n#' @family fortify_matrix\n#' @importFrom rlang try_fetch\n#' @export\nfortify_matrix.default <- function(data, ..., data_arg = NULL,\n call = NULL) {\n call <- call %||% current_call()\n data_arg <- data_arg %||% \"data\"\n rlang::check_dots_empty(call = call)\n try_fetch(\n as.matrix(data),\n error = ", "suffix_code": "\n )\n}\n\n#' @export\nfortify_matrix.waiver <- function(data, ..., data_arg = NULL,\n call = NULL) {\n call <- call %||% current_call()\n rlang::check_dots_empty(call = call)\n data\n}\n\n#' @export\nfortify_matrix.NULL <- fortify_matrix.waiver\n\n#' @export\nfortify_matrix.function <- fortify_matrix.waiver\n\n#' @export\nfortify_matrix.formula <- function(data, ..., data_arg = NULL,\n call = NULL) {\n call <- call %||% current_call()\n rlang::check_dots_empty(call = call)\n rlang::as_function(data)\n}\n", "middle_code": "function(cnd) {\n cli_abort(\n paste0(\n \"{.arg {data_arg}} must be a {.cls matrix}, \",\n \"or an object coercible by {.fn fortify_matrix}, or a valid \",\n \"{.cls matrix}-like object coercible by {.fn as.matrix}\"\n ),\n call = call\n )\n }", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "r", "sub_task_type": null}, "context_code": [["/ggalign/R/fortify-data-frame-.R", "#' Build a data frame\n#'\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' This function converts various objects to a data frame.\n#'\n#' @param data An object to be converted to a data frame.\n#' @param ... Arguments passed to methods.\n#' @inheritParams fortify_matrix\n#' @return A data frame.\n#' @eval\n#' rd_collect_family(\"fortify_data_frame\",\n#' \"`fortify_data_frame` method collections\"\n#' )\n#' @export\nfortify_data_frame <- function(data, ..., data_arg = NULL, call = NULL) {\n UseMethod(\"fortify_data_frame\")\n}\n\n#' @inherit fortify_data_frame title description\n#' @param ... Additional arguments passed to [`fortify()`][ggplot2::fortify].\n#' @inheritParams fortify_data_frame\n#' @details\n#' By default, it calls [`fortify()`][ggplot2::fortify] to build the\n#' data frame.\n#' @family fortify_data_frame\n#' @export\nfortify_data_frame.default <- function(data, ..., data_arg = NULL,\n call = NULL) {\n ggplot2::fortify(model = data, ...)\n}\n\n#' @inherit fortify_data_frame.default title description\n#' @param data An object to be converted to a data frame.\n#' @inheritParams rlang::args_dots_empty\n#' @inheritParams fortify_data_frame\n#' @return A data frame with following columns:\n#'\n#' - `.names`: the names for the vector (only applicable if names exist).\n#' - `value`: the actual value of the vector.\n#'\n#' @family fortify_data_frame\n#' @export\nfortify_data_frame.character <- function(data, ..., data_arg = NULL,\n call = NULL) {\n call <- call %||% current_call()\n rlang::check_dots_empty(call = call)\n ans <- list(.names = vec_names(data), value = data)\n if (is.null(.subset2(ans, \".names\"))) ans$.names <- NULL\n new_data_frame(ans)\n}\n\n#' @rdname fortify_data_frame.character\n#' @export\nfortify_data_frame.numeric <- fortify_data_frame.character\n\n#' @rdname fortify_data_frame.character\n#' @export\nfortify_data_frame.logical <- fortify_data_frame.character\n\n#' @rdname fortify_data_frame.character\n#' @export\nfortify_data_frame.complex <- fortify_data_frame.character\n\n#' @export\nfortify_data_frame.waiver <- function(data, ..., data_arg = NULL,\n call = NULL) {\n call <- call %||% current_call()\n rlang::check_dots_empty(call = call)\n data\n}\n\n#' @export\nfortify_data_frame.NULL <- fortify_data_frame.waiver\n\n#' @inherit fortify_data_frame.default title description\n#' @param data An object to be converted to a data frame.\n#' @inheritParams fortify_data_frame\n#' @return A data frame with at least following columns:\n#'\n#' - `seqnames`: The sequence (e.g., chromosome) names.\n#' - `start`: The start positions of the ranges.\n#' - `end`: The end positions of the ranges.\n#' - `width`: The width of each range.\n#'\n#' @family fortify_data_frame\n#' @export\nfortify_data_frame.GRanges <- function(data, ..., data_arg = NULL,\n call = NULL) {\n as.data.frame(data, ...)\n}\n\n#' @inherit fortify_data_frame.default title description\n#' @param data A matrix-like object.\n#' @param lvls A logical value indicating whether to restore factor levels using\n#' those stored in [`ggalign_lvls()`], or a character vector specifying custom\n#' levels for the `value` column. If levels are provided or restored, the\n#' `value` column will be returned as a factor.\n#' @inheritParams rlang::args_dots_empty\n#' @inheritParams fortify_data_frame\n#' @return\n#' Matrix will be transformed into a long-form data frame, where each row\n#' represents a unique combination of matrix indices and their corresponding\n#' values. The resulting data frame will contain the following columns:\n#'\n#' - `.row_names` and `.row_index`: the row names (only applicable when names\n#' exist) and an integer representing the row index of the original matrix.\n#'\n#' - `.column_names` and `.column_index`: the column names (only applicable\n#' when names exist) and column index of the original matrix.\n#'\n#' - `value`: the matrix value, returned as a factor if levels are specified or\n#' restored.\n#'\n#' @family fortify_data_frame\n#' @export\nfortify_data_frame.matrix <- function(data, lvls = NULL, ...,\n data_arg = NULL, call = NULL) {\n call <- call %||% current_call()\n rlang::check_dots_empty(call = call)\n row_nms <- vec_names(data)\n col_nms <- colnames(data)\n if (isFALSE(lvls)) {\n lvls <- NULL\n } else if (isTRUE(lvls)) {\n lvls <- ggalign_lvls_get(lvls)\n } else if (!is.null(lvls) && !is.character(lvls)) {\n cli_abort(\n \"{.arg lvls} must be a single boolean value or a character\",\n call = call\n )\n }\n data <- new_data_frame(list(\n .row_index = vec_rep(seq_len(nrow(data)), ncol(data)),\n .column_index = vec_rep_each(seq_len(ncol(data)), nrow(data)),\n value = c(data)\n ))\n if (!is.null(row_nms)) data$.row_names <- row_nms[data$.row_index]\n if (!is.null(col_nms)) data$.column_names <- col_nms[data$.column_index]\n if (!is.null(lvls)) data$value <- factor(data$value, levels = lvls)\n data\n}\n\n#' @export\n#' @rdname fortify_data_frame.matrix\nfortify_data_frame.DelayedMatrix <- function(data, ...) {\n fortify_data_frame(as.matrix(data), ...)\n}\n\n#' @export\n#' @rdname fortify_data_frame.matrix\nfortify_data_frame.Matrix <- function(data, ...) {\n fortify_data_frame(as.matrix(data), ...)\n}\n"], ["/ggalign/R/fortify-matrix-matrix.R", "#' Build a matrix\n#'\n#' @param data A matrix object.\n#' @inheritParams rlang::args_dots_empty\n#' @inheritParams fortify_matrix\n#' @section shape:\n#' - `upset`: [`fortify_matrix.matrix_upset()`]\n#' - `oncoplot`: [`fortify_matrix.matrix_oncoplot()`]\n#' @family fortify_matrix\n#' @export\nfortify_matrix.matrix <- fortify_matrix.waiver\n\n#' Convert the shape of a matrix for fortify method\n#'\n#' @param data A matrix.\n#' @param shape A string of `r oxford_or(c(\"upset\", \"oncoplot\"))`.\n#' @seealso\n#' - [`fortify_matrix.matrix()`]\n#' - [`fortify_matrix.matrix_upset()`]\n#' - [`fortify_matrix.matrix_oncoplot()`]\n#' @family tune\n#' @importFrom rlang arg_match0\n#' @export\ntune.matrix <- function(data, shape) {\n shape <- arg_match0(shape, c(\"upset\", \"oncoplot\"))\n if (identical(shape, \"oncoplot\")) {\n if (!is.character(data)) {\n cli_abort(\n \"{.arg data} must be a character matrix to use {shape} shape\"\n )\n }\n }\n new_tune(data, class = sprintf(\"matrix_%s\", shape))\n}\n\n#' @inherit fortify_matrix.list_upset title\n#' @description\n#' Converts a matrix suitable for creating an UpSet plot. [`tune.matrix()`]\n#' helps convert `matrix` object to a `matrix_upset` object.\n#' @param data A matrix where each row represents an element, and each column\n#' defines a set. The values in the matrix indicate whether the element is part\n#' of the set. Any non-missing value signifies that the element exists in the\n#' set.\n#' @inheritParams fortify_matrix.list_upset\n#' @inheritDotParams fortify_matrix.list_upset\n#' @inheritSection fortify_matrix.list_upset ggalign attributes\n#' @seealso [`tune.matrix()`]\n#' @family fortify_matrix\n#' @export\nfortify_matrix.matrix_upset <- function(data, ..., data_arg = NULL,\n call = NULL) {\n call <- call %||% current_call()\n data <- !is.na(tune_data(data))\n elements <- vec_seq_along(data)\n fortify_matrix.list_upset(\n lapply(seq_len(ncol(data)), function(i) {\n .subset(elements, data[, i, drop = TRUE])\n }),\n ...,\n data_arg = data_arg,\n call = call\n )\n}\n\n#' Build a Matrix for OncoPrint\n#'\n#' @description\n#' Converts a matrix suitable for creating an OncoPrint. [`tune.matrix()`]\n#' helps convert `matrix` object to a `matrix_oncoplot` object.\n#'\n#' @param data A matrix where each row represents an genes, and each column\n#' represents samples. The values in the matrix indicate whether the element is\n#' part of the set.\n#' @inheritParams fortify_matrix.MAF\n#' @section ggalign attributes:\n#' - `gene_summary`: An integer vector of the altered samples for each gene.\n#' - `sample_summary`: An integer vector of the altered genes for each sample.\n#' - `n_genes`: Total number of genes.\n#' - `n_samples`: Total number of samples.\n#'\n#' @seealso [`tune.matrix()`]\n#' @family fortify_matrix\n#' @export\nfortify_matrix.matrix_oncoplot <- function(data, ...,\n genes = NULL, n_top = NULL,\n remove_empty_genes = TRUE,\n remove_empty_samples = TRUE,\n missing_genes = \"error\",\n data_arg = NULL,\n call = NULL) {\n call <- call %||% current_call()\n rlang::check_dots_empty(call = call)\n\n # check arguments\n missing_genes <- arg_match0(\n missing_genes, c(\"error\", \"remove\"),\n error_call = call\n )\n\n data <- tune_data(data)\n alt <- !is.na(data)\n storage.mode(alt) <- \"integer\"\n gene_summary <- rowSums(alt)\n sample_summary <- colSums(alt)\n n_genes <- nrow(data)\n n_samples <- ncol(data)\n\n # filter by genes --------------------------------------\n if (!is.null(genes)) {\n genes <- vec_cast(genes, character())\n if (vec_any_missing(genes)) {\n cli_abort(\n \"{.arg genes} cannot contain missing values\",\n call = call\n )\n }\n if (vec_duplicate_any(genes)) {\n cli_abort(\n \"{.arg genes} cannot contain duplicated values\",\n call = call\n )\n }\n if (identical(missing_genes, \"remove\")) {\n genes <- genes[genes %in% rownames(data)]\n }\n if (is_empty(genes)) {\n cli_abort(\n \"No {.arg genes} remain after removing missing genes\",\n call = call\n )\n }\n index <- vec_as_location(\n genes,\n n = vec_size(data),\n names = rownames(data),\n missing = \"error\"\n )\n data <- vec_slice(data, index)\n alt <- vec_slice(alt, index)\n gene_summary <- vec_slice(gene_summary, index)\n }\n\n if (!is.null(n_top)) {\n n_top <- min(n_top, vec_size(alt))\n index <- vec_slice(\n order(rowSums(alt), decreasing = TRUE),\n seq_len(n_top)\n )\n data <- vec_slice(data, index)\n alt <- vec_slice(alt, index)\n gene_summary <- vec_slice(gene_summary, index)\n }\n\n # filter empty genes\n if (remove_empty_genes) {\n keep <- rowSums(alt) > 0L\n data <- vec_slice(data, keep)\n gene_summary <- vec_slice(gene_summary, keep)\n }\n\n # filter empty samples\n if (remove_empty_samples) {\n keep <- colSums(alt) > 0L\n data <- data[, keep, drop = FALSE]\n sample_summary <- vec_slice(sample_summary, keep)\n }\n\n ggalign_data_set(data,\n sample_summary = sample_summary,\n gene_summary = gene_summary,\n n_samples = n_samples,\n n_genes = n_genes\n )\n}\n"], ["/ggalign/R/layout-chain-stack-.R", "#' Arrange plots horizontally or vertically\n#'\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' If `limits` is provided, a continuous variable will be required and aligned\n#' in the direction specified (`stack_continuous`). Otherwise, a discrete\n#' variable will be required and aligned (`stack_discrete`).\n#'\n#' Several aliases are provided for convenience:\n#' - `stack_vertical`: A special case of `stack_layout` that sets `direction\n#' = \"v\"`.\n#' - `stack_horizontal`: A special case of `stack_layout` that sets `direction\n#' = \"h\"`.\n#' - `stack_discretev`: A special case of `stack_discrete` that sets `direction\n#' = \"v\"`.\n#' - `stack_discreteh`: A special case of `stack_discrete` that sets `direction\n#' = \"h\"`.\n#' - `stack_continuousv()`: A special case of `stack_free` that sets `direction\n#' = \"v\"`.\n#' - `stack_continuoush()`: A special case of `stack_free` that sets `direction\n#' = \"h\"`.\n#'\n#' For historical reasons, the following aliases are available:\n#' - `stack_align` is an alias for `stack_discrete`.\n#' - `stack_alignv` is an alias for `stack_discretev`.\n#' - `stack_alignh` is an alias for `stack_discreteh`.\n#' - `stack_free` is an alias for `stack_continuous`.\n#' - `stack_freev` is an alias for `stack_continuousv`.\n#' - `stack_freeh` is an alias for `stack_continuoush`.\n#'\n#' @param direction A string indicating the direction of the stack layout,\n#' either `\"h\"`(`horizontal`) or `\"v\"`(`vertical`).\n#' @param data `r rd_layout_data()`:\n#' - If `limits` is not provided, [`fortify_matrix()`] will be used to get a\n#' matrix.\n#' - If `limits` is specified, [`fortify_data_frame()`] will be used to get a\n#' data frame.\n#'\n#' @param ... Additional arguments passed to [`fortify_data_frame()`] or\n#' [`fortify_matrix()`].\n#' @param theme A [`theme()`][ggplot2::theme] object used to customize various\n#' elements of the layout, including `guides`, `title`, `subtitle`, `caption`,\n#' `margins`, `panel.border`, and `background`. By default, the theme will\n#' inherit from the parent `layout`. It also controls the panel spacing for all\n#' plots in the layout.\n#'\n#' @param sizes A numeric value or a [`unit`][grid::unit] object. When used for\n#' the [`quad_layout()`] annotation, it must be of length `1`. When used in the\n#' [`stack_layout()`] with a nested [`quad_layout()`], it should be of length\n#' `3`, specifying the relative heights (for `direction = \"h\"`) or widths (for\n#' `direction = \"v\"`) to be applied to the layout.\n#' @param limits A [`continuous_limits()`] object specifying the left/lower\n#' limit and the right/upper limit of the scale. Used to align the continuous\n#' axis.\n#' @return A `StackLayout` object.\n#' @examples\n#' set.seed(123)\n#' small_mat <- matrix(rnorm(56), nrow = 7L)\n#'\n#' stack_horizontal(small_mat) + align_dendro()\n#'\n#' # this is the same with:\n#' stack_discrete(\"h\", small_mat) + align_dendro()\n#'\n#' stack_discreteh(small_mat) + align_dendro()\n#'\n#' # For vertical layout:\n#' stack_vertical(small_mat) + align_dendro()\n#'\n#' @export\nstack_layout <- function(direction, data = NULL, ...,\n theme = NULL, sizes = NA, limits = waiver()) {\n if (is.waive(limits)) {\n stack_discrete(\n data = data, direction = direction, ...,\n theme = theme, sizes = sizes\n )\n } else {\n stack_continuous(\n data = data, direction = direction, ...,\n theme = theme, sizes = sizes, limits = limits\n )\n }\n}\n\n#' @export\n#' @rdname stack_layout\nstack_horizontal <- function(data = NULL, ..., limits = waiver()) {\n stack_layout(data = data, direction = \"h\", limits = limits, ...)\n}\n\n#' @export\n#' @rdname stack_layout\nstack_vertical <- function(data = NULL, ..., limits = waiver()) {\n stack_layout(data = data, direction = \"v\", limits = limits, ...)\n}\n\n###################################################################\n#' @export\n#' @rdname stack_layout\nstack_discrete <- function(direction, data = NULL, ...,\n theme = NULL, sizes = NA) {\n UseMethod(\"stack_discrete\", data)\n}\n\n#' @usage NULL\n#' @export\n#' @rdname stack_layout\nstack_align <- stack_discrete\n\n#' @export\n#' @rdname stack_layout\nstack_discretev <- function(data = NULL, ...) {\n stack_discrete(data = data, direction = \"v\", ...)\n}\n\n#' @usage NULL\n#' @export\n#' @rdname stack_layout\nstack_alignv <- stack_discretev\n\n#' @export\n#' @rdname stack_layout\nstack_discreteh <- function(data = NULL, ...) {\n stack_discrete(data = data, direction = \"h\", ...)\n}\n\n#' @usage NULL\n#' @export\n#' @rdname stack_layout\nstack_alignh <- stack_discreteh\n\n#' @export\nstack_discrete.default <- function(direction, data = NULL, ...,\n theme = NULL, sizes = NA) {\n direction <- check_direction(direction)\n # the observations are rows, we use matrix to easily\n # reshape it into a long formated data frame for ggplot,\n # and we can easily determine the number of observations\n # from matrix\n data <- data %|w|% NULL\n data <- fortify_matrix(data = data, ...)\n schemes <- default_schemes()\n if (!is.null(data) && !is.function(data)) {\n # if we have provided data, we initialize the `nobs`\n nobs <- vec_size(data)\n\n # for data has dimention but one dimention is 0\n # as.matrix(data.frame(row.names = letters))\n if (nobs == 0L) {\n cli_abort(\"empty data is no allowed\")\n }\n } else {\n nobs <- NULL\n }\n new_stack_layout(\n name = \"stack_discrete\",\n data = data, direction = direction,\n design = discrete_design(nobs = nobs),\n schemes = schemes, theme = theme, sizes = sizes\n )\n}\n\n#' @export\nstack_discrete.function <- function(direction, data = NULL, ...) {\n cli_abort(paste0(\n \"{.arg data} must be a {.cls matrix}, \",\n \"or an object coercible by {.fn fortify_matrix}, or a valid \",\n \"{.cls matrix}-like object coercible by {.fn as.matrix}\"\n ))\n}\n\n#' @export\nstack_discrete.formula <- stack_discrete.function\n\n################################################################\n#' @export\n#' @rdname stack_layout\nstack_continuous <- function(direction, data = NULL, ..., limits = NULL,\n theme = NULL, sizes = NA) {\n UseMethod(\"stack_continuous\", data)\n}\n\n#' @usage NULL\n#' @export\n#' @rdname stack_layout\nstack_free <- stack_continuous\n\n#' @export\n#' @rdname stack_layout\nstack_continuousv <- function(data = NULL, ...) {\n stack_continuous(data = data, direction = \"v\", ...)\n}\n\n#' @usage NULL\n#' @export\n#' @rdname stack_layout\nstack_freev <- stack_continuousv\n\n#' @export\n#' @rdname stack_layout\nstack_continuoush <- function(data = NULL, ...) {\n stack_continuous(data = data, direction = \"h\", ...)\n}\n\n#' @usage NULL\n#' @export\n#' @rdname stack_layout\nstack_freeh <- stack_continuoush\n\n#' @export\nstack_continuous.default <- function(direction, data = NULL, ...,\n limits = NULL, theme = NULL, sizes = NA) {\n assert_limits(limits)\n direction <- check_direction(direction)\n data <- data %|w|% NULL\n data <- fortify_data_frame(data = data, ...)\n schemes <- default_schemes()\n new_stack_layout(\n name = \"stack_continuous\",\n data = data, direction = direction, design = limits,\n schemes = schemes, theme = theme, sizes = sizes\n )\n}\n\n#' @export\nstack_continuous.function <- function(direction, data = NULL, ...) {\n cli_abort(paste0(\n \"{.arg data} must be a {.cls data.frame}, \",\n \"or an object coercible by {.fn fortify_data_frame}, or a valid \",\n \"{.cls data.frame}-like object coercible by {.fn as.data.frame}\"\n ))\n}\n\n#' @export\nstack_continuous.formula <- stack_continuous.function\n\n#' @importFrom methods new\nnew_stack_layout <- function(data, direction, design,\n schemes = NULL, theme = NULL, sizes = NA,\n name = NULL, call = caller_call()) {\n sizes <- check_stack_sizes(sizes, call = call)\n if (!is.null(theme)) assert_s3_class(theme, \"theme\", call = call)\n if (is.null(name)) {\n if (is_continuous_design(design)) {\n name <- \"stack_continuous\"\n } else {\n name <- \"stack_discrete\"\n }\n }\n new(\n \"StackLayout\",\n name = name, data = data,\n direction = direction,\n theme = theme, schemes = schemes, # used by the layout\n sizes = sizes, design = design\n )\n}\n\n############################################################\n# Used to place multiple objects in one axis\n#' @importFrom grid unit\n#' @importFrom ggplot2 waiver\n#' @keywords internal\n#' @include layout-chain-.R\nmethods::setClass(\n \"StackLayout\",\n contains = \"ChainLayout\",\n list(\n direction = \"character\",\n heatmap = \"list\", # used by heatmap annotation\n sizes = \"ANY\" # used by stack layout\n ),\n prototype = list(\n heatmap = list(\n position = NULL,\n free_guides = waiver(),\n # indicate whether or not the data is from the quad-layout matrix\n quad_matrix = FALSE\n )\n )\n)\n"], ["/ggalign/R/fortify-matrix-list.R", "#' Convert the shape of a list for fortify method\n#'\n#' @param data A list\n#' @param shape Not used currently.\n#' @seealso [`fortify_matrix.list_upset()`]\n#' @family tune\n#' @export\ntune.list <- function(data, shape = NULL) {\n if (!is.null(shape)) {\n cli_abort(\"{.arg shape} cannot be used currently for {.cls list} object\")\n }\n new_tune(data, class = \"list_upset\")\n}\n\n#' Build a Matrix for UpSet plot\n#'\n#' @description\n#' `r lifecycle::badge('experimental')`\n#'\n#' This function converts a list into a matrix format suitable for creating an\n#' UpSet plot. It always returns a matrix for a `horizontal` UpSet plot.\n#' @inheritParams rlang::args_dots_empty\n#' @param data A list of sets.\n#' @param mode A string of `r oxford_or(c(\"distinct\", \"intersect\", \"union\"))`\n#' indicates the mode to define the set intersections. Check\n#' \n#' for details.\n#' @inheritParams fortify_matrix\n#' @section ggalign attributes:\n#' - `intersection_sizes`: An integer vector indicating the size of each\n#' intersection.\n#' - `set_sizes`: An integer vector indicating the size of each set.\n#' @seealso [`tune.list()`]\n#' @family fortify_matrix\n#' @aliases fortify_matrix.list\n#' @export\nfortify_matrix.list_upset <- function(data, mode = \"distinct\", ...,\n data_arg = NULL, call = NULL) {\n call <- call %||% current_call()\n rlang::check_dots_empty(call = call)\n mode <- arg_match0(mode, c(\"distinct\", \"intersect\", \"union\"),\n error_call = call\n )\n data <- lapply(tune_data(data), function(x) {\n vec_unique(vec_slice(x, !vec_detect_missing(x)))\n })\n data <- list_drop_empty(data)\n if (length(data) == 0L) {\n cli::cli_abort(\n \"No valid data: All input lists are either empty or contain only missing values.\",\n call = call\n )\n }\n\n # Based on the explanation from\n # https://jokergoo.github.io/ComplexHeatmap-reference/book/upset-plot.html\n action <- switch(mode,\n distinct = function(data, intersection) {\n out <- NULL\n for (i in which(intersection)) {\n if (is.null(out)) {\n out <- .subset2(data, i)\n } else if (vec_size(out) == 0L) { # early exit for empty items\n return(out)\n } else {\n out <- vec_set_intersect(out, .subset2(data, i))\n }\n }\n for (i in which(!intersection)) {\n if (vec_size(out) == 0L) { # early exit for empty items\n return(out)\n }\n out <- vec_set_difference(out, .subset2(data, i))\n }\n return(out)\n },\n intersect = function(data, intersection) {\n out <- NULL\n for (i in which(intersection)) {\n if (is.null(out)) {\n out <- .subset2(data, i)\n } else if (vec_size(out) == 0L) { # early exit for empty items\n return(out)\n } else {\n out <- vec_set_intersect(out, .subset2(data, i))\n }\n }\n out\n },\n union = function(data, intersection) {\n Reduce(vec_set_union, .subset(data, intersection))\n }\n )\n\n intersection <- logical(vec_size(data)) # template\n intersection_and_size <- lapply(\n seq_len(vec_size(intersection)),\n function(n) {\n # generate all possible intersections\n utils::combn(vec_size(intersection), n, function(index) {\n intersection[index] <- TRUE\n list(\n intersection = intersection,\n # for each intersection, we define the size\n size = vec_size(action(data, intersection))\n )\n }, simplify = FALSE)\n }\n )\n\n # https://en.wikipedia.org/wiki/UpSet_plot\n # UpSets can be used horizontally and vertically.\n # In a vertical UpSet plot, the columns of the matrix correspond to the\n # sets, the rows correspond to the intersections.\n # we by default use `horizontal` upset, the rows of the matrix correspond\n # to the sets, the columns correspond to the intersections.\n ans <- list_transpose(unlist(intersection_and_size, FALSE, FALSE))\n intersections <- inject(cbind(!!!.subset2(ans, \"intersection\")))\n rownames(intersections) <- names(data)\n intersection_sizes <- unlist(.subset2(ans, \"size\"), FALSE, FALSE)\n keep <- intersection_sizes > 0L # remove intersection without items\n intersections <- intersections[, keep, drop = FALSE]\n intersection_sizes <- intersection_sizes[keep]\n ggalign_data_set(intersections,\n intersection_sizes = intersection_sizes,\n set_sizes = list_sizes(data),\n upset_mode = mode\n )\n}\n"], ["/ggalign/R/fortify-matrix-maftools.R", "#' Build a Matrix for OncoPrint\n#'\n#' @description\n#' Convert `MAF` object to a matrix:\n#' - `fortify_matrix.MAF`: Extract genomic alterations for genes.\n#' - `fortify_matrix.MAF_pathways`: Extract genomic alterations for pathways.\n#' [`tune.MAF()`] helps convert `MAF` object to a `MAF_pathways` object.\n#'\n#' @inheritParams rlang::args_dots_empty\n#' @param data A [`MAF`][maftools::read.maf] object.\n#' @param genes An atomic character defines the genes to draw.\n#' @param n_top A single number indicates how many top genes to be drawn.\n#' @param remove_empty_genes A single boolean value indicats whether to drop\n#' genes without any genomic alterations.\n#' @param remove_empty_samples A single boolean value indicats whether to drop\n#' samples without any genomic alterations.\n#' @param collapse_vars A single boolean value indicating whether to collapse\n#' multiple alterations in the same sample and gene into a single value\n#' `\"Multi_Hit\"`. Alternatively, you can provide a single string indicates the\n#' collapsed values.\n#' @param use_syn A single boolean value indicates whether to include synonymous\n#' variants when Classifies SNPs into transitions and transversions.\n#' @param missing_genes A string, either `\"error\"` or `\"remove\"`, specifying the\n#' action for handling missing genes.\n#' @inheritParams fortify_matrix\n#' @section ggalign attributes:\n#' For `fortify_matrix.MAF`:\n#' - `gene_summary`: A data frame of gene summary informations. See\n#' `maftools::getGeneSummary()` for details.\n#' - `sample_summary`: A data frame of sample summary informations. See\n#' `maftools::getSampleSummary()` for details.\n#' - `sample_anno`: A data frame of sample clinical informations. See\n#' `maftools::getClinicalData()` for details.\n#' - `variant_weights`: A data frame of variant weights. Each gene in a sample\n#' is assigned a total weight of `1`. When multiple variants occur in the\n#' same gene-sample pair, the weight for each variant reflects its proportion\n#' of the total.\n#' - `n_genes`: Total number of genes.\n#' - `n_samples`: Total number of samples.\n#' - `titv`: A list of data frame with Transitions and Transversions\n#' summary. See `maftools::titv()` for details.\n#'\n#' The levels of `Variant_Classification` will be stored in [`ggalign_lvls()`].\n#' If they do not exist, alphabetical ordering will be used.\n#'\n#' @family fortify_matrix\n#' @importFrom utils getFromNamespace\n#' @importFrom rlang is_string\n#' @export\nfortify_matrix.MAF <- function(data, ..., genes = NULL, n_top = NULL,\n remove_empty_genes = TRUE,\n remove_empty_samples = TRUE,\n collapse_vars = TRUE, use_syn = TRUE,\n missing_genes = \"error\",\n data_arg = NULL, call = NULL) {\n call <- call %||% current_call()\n rlang::check_dots_empty(call = call)\n rlang::check_installed(\n \"maftools\", \"to make alterations matrix from `MAF` object\"\n )\n # prepare arguments\n missing_genes <- arg_match0(\n missing_genes, c(\"error\", \"remove\"),\n error_call = call\n )\n if (isTRUE(collapse_vars)) {\n collapse_vars <- \"Multi_Hit\"\n } else if (isFALSE(collapse_vars)) {\n collapse_vars <- NULL\n } else if (is_string(collapse_vars)) {\n if (collapse_vars == \"\") {\n cli_abort(\"{.arg collapse_vars} cannot be an empty string\",\n call = call\n )\n }\n } else {\n cli_abort(\n paste(\n \"{.arg collapse_vars} must be a single boolean value or a string,\",\n \"but you provide {.obj_type_friendly {collapse_vars}}\"\n ),\n call = call\n )\n }\n\n getSampleSummary <- getExportedValue(\"maftools\", \"getSampleSummary\")\n getGeneSummary <- getExportedValue(\"maftools\", \"getGeneSummary\")\n getClinicalData <- getExportedValue(\"maftools\", \"getClinicalData\")\n\n # if `maftools` is installed, `data.table` must have been installed\n # No need to check if `data.table` is installed\n dcast <- getExportedValue(\"data.table\", \"dcast\")\n setDT <- getExportedValue(\"data.table\", \"setDT\")\n setDF <- getExportedValue(\"data.table\", \"setDF\")\n\n sample_summary <- new_data_frame(getSampleSummary(data))\n gene_summary <- new_data_frame(getGeneSummary(data))\n sample_anno <- new_data_frame(getClinicalData(data))\n\n titv <- getExportedValue(\"maftools\", \"titv\")\n titv <- titv(data, useSyn = use_syn, plot = FALSE)\n titv <- lapply(titv, new_data_frame)\n\n # we transform the data into a normal data frame\n data <- new_data_frame(data@data)[\n c(\"Tumor_Sample_Barcode\", \"Hugo_Symbol\", \"Variant_Classification\")\n ]\n n_genes <- vec_unique_count(.subset2(data, \"Hugo_Symbol\"))\n n_samples <- vec_unique_count(.subset2(data, \"Tumor_Sample_Barcode\"))\n\n # filter by genes --------------------------------------\n if (!is.null(genes)) {\n # reorder the gene annotation based on the provided genes\n genes <- vec_cast(genes, character())\n if (vec_any_missing(genes)) {\n cli_abort(\n \"{.arg genes} cannot contain missing values\",\n call = call\n )\n }\n if (vec_duplicate_any(genes)) {\n cli_abort(\n \"{.arg genes} cannot contain duplicated values\",\n call = call\n )\n }\n if (identical(missing_genes, \"remove\")) {\n genes <- genes[genes %in% .subset2(gene_summary, \"Hugo_Symbol\")]\n }\n if (is_empty(genes)) {\n cli_abort(\n \"No {.arg genes} remain after removing missing genes\",\n call = call\n )\n }\n gene_summary <- vec_slice(\n gene_summary,\n vec_as_location(\n genes,\n n = vec_size(gene_summary),\n names = .subset2(gene_summary, \"Hugo_Symbol\"),\n missing = \"error\"\n )\n )\n }\n genes <- .subset2(gene_summary, \"Hugo_Symbol\")\n if (!is.null(n_top)) {\n n_top <- min(n_top, vec_size(genes))\n index <- vec_slice(\n order(gene_summary$AlteredSamples, decreasing = TRUE),\n seq_len(n_top)\n )\n index <- sort(index) # don't change the order, we do only subset\n genes <- vec_slice(genes, index)\n gene_summary <- vec_slice(gene_summary, index)\n }\n data <- vec_slice(data, .subset2(data, \"Hugo_Symbol\") %in% genes)\n\n # Group variants --------------------------------------\n indices <- vec_group_loc(data[c(\"Tumor_Sample_Barcode\", \"Hugo_Symbol\")])\n vars <- .subset2(data, \"Variant_Classification\")\n lvls <- levels(vars) %||% sort(vec_unique(vars))\n nlvls <- vec_size(lvls)\n var_list <- vec_chop(as.character(vars), indices = .subset2(indices, \"loc\"))\n\n # calcualte the variant weights -----------------------\n variant_weights <- lapply(var_list, function(var) {\n o <- numeric(nlvls)\n names(o) <- lvls\n counts <- vec_count(var)\n o[.subset2(counts, \"key\")] <- .subset2(counts, \"count\") /\n sum(.subset2(counts, \"count\"))\n o\n })\n variant_weights <- inject(rbind(!!!variant_weights))\n gene_indices <- vec_group_loc(\n .subset2(.subset2(indices, \"key\"), \"Hugo_Symbol\")\n )\n variant_weights <- lapply(\n vec_chop(variant_weights, indices = .subset2(gene_indices, \"loc\")),\n colSums\n )\n variant_weights <- vec_cbind(\n Hugo_Symbol = .subset2(gene_indices, \"key\"),\n vec_rbind(!!!variant_weights)\n )\n\n # collapse the vars ------------------------------------\n if (is.null(collapse_vars)) {\n vars <- vapply(var_list, function(var) {\n if (length(var) > 1L) {\n paste(var, collapse = \";\")\n } else {\n var\n }\n }, character(1L), USE.NAMES = FALSE)\n } else {\n vars <- vapply(var_list, function(var) {\n if (vec_unique_count(var) > 1L) {\n collapse_vars\n } else if (length(var) > 1L) {\n paste(var, collapse = \";\")\n } else {\n var\n }\n }, character(1L), USE.NAMES = FALSE)\n if (any(vars == collapse_vars)) lvls <- c(lvls, collapse_vars)\n }\n ans <- vec_cbind(\n .subset2(indices, \"key\"),\n new_data_frame(list(Variant_Classification = vars))\n )\n\n # restore all samples, this will introduce `NA` in `Hugo_Symbol`\n ans <- right_join(ans, data_frame0(\n Tumor_Sample_Barcode = vec_unique(sample_summary$Tumor_Sample_Barcode)\n ))\n setDT(ans)\n ans <- dcast(ans, Hugo_Symbol ~ Tumor_Sample_Barcode,\n value.var = \"Variant_Classification\"\n )\n setDF(ans)\n ans <- vec_slice(ans, !is.na(.subset2(ans, \"Hugo_Symbol\")))\n\n # convert data into a matrix\n if (remove_empty_genes) {\n # convert to a matrix\n ans <- as.matrix(column_to_rownames(ans, \"Hugo_Symbol\"))\n\n # reorder the rows based on the `genes` specified\n index <- match(genes, rownames(ans))\n ans <- vec_slice(ans, index[!is.na(index)])\n } else {\n # restore all genes\n ans <- right_join(ans, data_frame0(Hugo_Symbol = genes))\n\n # convert to a matrix\n ans <- as.matrix(column_to_rownames(ans, \"Hugo_Symbol\"))\n\n # reorder the rows based on the `genes` specified\n ans <- vec_slice(ans, genes)\n }\n\n # filter samples when necessary\n if (remove_empty_samples) {\n keep <- colSums(!is.na(ans)) > 0L\n ans <- ans[, keep, drop = FALSE]\n }\n\n # reorder the rows based on the gene ordering\n gene_summary <- vec_slice(\n gene_summary,\n vec_as_location(\n rownames(ans),\n n = vec_size(gene_summary),\n names = vec_cast(gene_summary$Hugo_Symbol, character())\n )\n )\n variant_weights <- vec_slice(\n variant_weights,\n vec_as_location(\n rownames(ans),\n n = vec_size(variant_weights),\n names = variant_weights$Hugo_Symbol\n )\n )\n\n # reorder columns based on the sample ordering\n sample_summary <- vec_slice(\n sample_summary,\n vec_as_location(\n colnames(ans),\n n = vec_size(sample_summary),\n names = vec_cast(sample_summary$Tumor_Sample_Barcode, character())\n )\n )\n sample_anno <- vec_slice(\n sample_anno,\n vec_as_location(\n colnames(ans),\n n = vec_size(sample_anno),\n names = sample_anno$Tumor_Sample_Barcode\n )\n )\n titv <- lapply(titv, function(data) {\n data <- left_join(\n data_frame0(Tumor_Sample_Barcode = colnames(ans)),\n data\n )\n vec_slice(data, vec_as_location(\n colnames(ans),\n n = vec_size(data),\n names = vec_cast(data$Tumor_Sample_Barcode, character())\n ))\n })\n ggalign_data_set(ans,\n sample_summary = sample_summary,\n gene_summary = gene_summary,\n sample_anno = sample_anno,\n variant_weights = variant_weights,\n n_samples = n_samples, n_genes = n_genes, titv = titv,\n .lvls = lvls\n )\n}\n\n#' Convert the shape of a MAF for fortify method\n#'\n#' @param data A [`MAF`][maftools::read.maf] object.\n#' @param shape Not used currently.\n#' @seealso [`fortify_matrix.MAF_pathways()`]\n#' @family tune\n#' @export\ntune.MAF <- function(data, shape = NULL) {\n if (!is.null(shape)) {\n cli_abort(\"{.arg shape} cannot be used currently for {.cls MAF} object\")\n }\n new_tune(data, class = \"MAF_pathways\")\n}\n\n#' @param pathdb A string of `r oxford_or(c(\"smgbp\", \"sigpw\"))`, or a named list\n#' of genes to define the pathways.\n#' @param remove_empty_pathways A single boolean value indicats whether to drop\n#' pathways without any genomic alterations.\n#' @section ggalign attributes:\n#' For `fortify_matrix.MAF_pathways`:\n#' - `gene_list`: the pathway contents.\n#' - `pathway_summary`: pathway summary informations. See\n#' `maftools::pathways()` for details.\n#' - `sample_summary`: sample summary informations. See\n#' `maftools::getSampleSummary()` for details.\n#' - `sample_anno`: sample clinical informations. See\n#' `maftools::getClinicalData()` for details.\n#' @export\n#' @rdname fortify_matrix.MAF\nfortify_matrix.MAF_pathways <- function(data, ..., pathdb = \"smgbp\",\n remove_empty_pathways = TRUE,\n remove_empty_samples = TRUE,\n data_arg = NULL,\n call = NULL) {\n call <- call %||% current_call()\n rlang::check_dots_empty(call = call)\n rlang::check_installed(\n \"maftools\", \"to make alterations matrix from `MAF` object\"\n )\n get_pw_summary <- getFromNamespace(\"get_pw_summary\", \"maftools\")\n maf <- tune_data(data)\n if (rlang::is_string(pathdb)) {\n pathdb <- arg_match0(pathdb, c(\"sigpw\", \"smgbp\"))\n pathway_summary <- get_pw_summary(maf, pathways = pathdb)\n } else if (is.data.frame(pathdb)) {\n cli_abort(\"{.arg pathdb} cannot be a data frame\", call = call)\n } else if (is.list(pathdb)) {\n if (!rlang::is_named(pathdb)) {\n cli_abort(sprintf(\n \"{.arg pathdb} must be a named list of a single string of %s\",\n oxford_or(c(\"sigpw\", \"smgbp\"))\n ), call = call)\n }\n pathdb <- data_frame0(\n Pathway = factor(\n vec_rep_each(names(pathdb), lengths(pathdb)),\n names(pathdb)\n ),\n Gene = unlist(pathdb, FALSE, FALSE)\n )\n pathdb <- vec_unique(pathdb)\n pathway_summary <- get_pw_summary(maf, pathways = pathdb)\n }\n getSampleSummary <- getExportedValue(\"maftools\", \"getSampleSummary\")\n getClinicalData <- getExportedValue(\"maftools\", \"getClinicalData\")\n sample_summary <- new_data_frame(getSampleSummary(maf))\n sample_anno <- new_data_frame(getClinicalData(maf))\n\n gene_list <- attr(pathway_summary, \"genes\") # a list of genes\n ans <- new_data_frame(maf@data)[\n c(\"Tumor_Sample_Barcode\", \"Hugo_Symbol\", \"Variant_Classification\")\n ]\n full_genes <- unlist(gene_list, FALSE, FALSE)\n ans$pathways <- vec_slice(\n vec_set_names(\n vec_rep_each(names(gene_list), lengths(gene_list)),\n full_genes\n ),\n if_else(ans$Hugo_Symbol %in% full_genes,\n ans$Hugo_Symbol, NA_character_\n )\n )\n ans$Alt <- if_else(is.na(.subset2(ans, \"pathways\")), NA_character_, \"Alt\")\n ans <- vec_unique(ans[c(\"Tumor_Sample_Barcode\", \"pathways\", \"Alt\")])\n\n # if `maftools` is installed, `data.table` must have been installed\n # No need to check if `data.table` is installed\n dcast <- getExportedValue(\"data.table\", \"dcast\")\n setDT <- getExportedValue(\"data.table\", \"setDT\")\n setDF <- getExportedValue(\"data.table\", \"setDF\")\n setDT(ans)\n ans <- dcast(ans, pathways ~ Tumor_Sample_Barcode,\n value.var = \"Alt\", fill = NA_character_\n )\n setDF(ans)\n ans <- vec_slice(ans, !is.na(.subset2(ans, \"pathways\")))\n\n # convert data into a matrix\n if (remove_empty_pathways) {\n # convert to a matrix\n ans <- as.matrix(column_to_rownames(ans, \"pathways\"))\n\n # reorder the rows based on the `pathways` specified\n index <- match(names(gene_list), rownames(ans))\n gene_list <- gene_list[!is.na(index)]\n ans <- vec_slice(ans, index[!is.na(index)])\n } else {\n # restore all pathways\n ans <- right_join(ans, data_frame0(pathways = names(gene_list)))\n\n # convert to a matrix\n ans <- as.matrix(column_to_rownames(ans, \"pathways\"))\n\n # reorder the rows based on the `pathways` specified\n ans <- vec_slice(ans, names(gene_list))\n }\n\n # filter samples when necessary\n if (remove_empty_samples) {\n keep <- colSums(!is.na(ans)) > 0L\n ans <- ans[, keep, drop = FALSE]\n }\n\n # reorder the rows based on the pathways ordering\n setDF(pathway_summary)\n pathway_summary <- vec_slice(\n pathway_summary,\n vec_as_location(\n rownames(ans),\n n = vec_size(pathway_summary),\n names = vec_cast(pathway_summary$Pathway, character())\n )\n )\n\n # reorder columns based on the sample ordering\n sample_summary <- vec_slice(\n sample_summary,\n vec_as_location(\n colnames(ans),\n n = vec_size(sample_summary),\n names = vec_cast(sample_summary$Tumor_Sample_Barcode, character())\n )\n )\n sample_anno <- vec_slice(\n sample_anno,\n vec_as_location(\n colnames(ans),\n n = vec_size(sample_anno),\n names = sample_anno$Tumor_Sample_Barcode\n )\n )\n ggalign_data_set(ans,\n gene_list = gene_list,\n pathway_summary = pathway_summary,\n sample_summary = sample_summary,\n sample_anno = sample_anno\n )\n}\n\n#' Build a matrix from a maftools object\n#'\n#' @inheritParams rlang::args_dots_empty\n#' @param data A [`GISTIC`][maftools::readGistic] object.\n#' @param n_top A single number indicates how many top bands to be drawn.\n#' @param bands An atomic character defines the bands to draw.\n#' @param ignored_bands An atomic character defines the bands to be ignored.\n#' @param sample_anno A data frame of sample clinical features to be added.\n#' @param remove_empty_samples A single boolean value indicating whether to drop\n#' samples without any genomic alterations.\n#' @inheritParams fortify_matrix\n#' @section ggalign attributes:\n#' - `sample_anno`: sample clinical informations provided in `sample_anno`.\n#' - `sample_summary`: sample copy number summary informations. See\n#' `data@@cnv.summary` for details.\n#' - `cytoband_summary`: cytoband summary informations. See\n#' `data@@cytoband.summary` for details.\n#' - `gene_summary`: gene summary informations. See\n#' `data@@gene.summary` for details.\n#' - `summary`: A data frame of summary information. See `data@@summary` for\n#' details.\n#' @family fortify_matrix\n#' @export\nfortify_matrix.GISTIC <- function(data, ..., n_top = NULL, bands = NULL,\n ignored_bands = NULL, sample_anno = NULL,\n remove_empty_samples = TRUE,\n data_arg = NULL,\n call = NULL) {\n call <- call %||% current_call()\n rlang::check_dots_empty(call = call)\n rlang::check_installed(\n \"maftools\",\n \"to make CNV matrix from `GISTIC` object\"\n )\n assert_number_whole(n_top,\n allow_null = TRUE,\n call = call\n )\n assert_character(bands,\n allow_null = TRUE,\n call = call\n )\n assert_character(ignored_bands,\n allow_null = TRUE,\n call = call\n )\n assert_s3_class(sample_anno, \"data.frame\",\n allow_null = TRUE,\n call = call\n )\n assert_bool(remove_empty_samples,\n call = call\n )\n cn_mat <- data@cnMatrix\n if (is.null(bands)) {\n bands <- rownames(cn_mat)\n } else {\n bands <- intersect(bands, rownames(cn_mat))\n }\n if (!is.null(ignored_bands)) {\n bands <- setdiff(bands, ignored_bands)\n }\n if (!is.null(bands)) {\n cn_mat <- vec_slice(cn_mat, rownames(cn_mat) %in% bands)\n }\n if (!is.null(n_top)) {\n cn_mat <- vec_slice(cn_mat, seq_len(min(n_top, nrow(cn_mat))))\n }\n if (remove_empty_samples) {\n keep <- colSums(cn_mat != \"\") > 0L\n cn_mat <- cn_mat[, keep, drop = FALSE]\n }\n if (!is.null(sample_anno)) {\n loc <- vec_locate_matches(\n colnames(cn_mat),\n .subset2(sample_anno, \"Tumor_Sample_Barcode\") %||%\n .subset2(sample_anno, 1L),\n relationship = \"one-to-one\",\n needles_arg = \"data\",\n haystack_arg = \"sample_anno\",\n error_call = call\n )\n sample_anno <- vec_slice(sample_anno, .subset2(loc, \"haystack\"))\n }\n sample_summary <- new_data_frame(data@cnv.summary)\n sample_summary <- vec_slice(\n sample_summary,\n vec_as_location(\n colnames(cn_mat),\n n = vec_size(sample_summary),\n names = vec_cast(sample_summary$Tumor_Sample_Barcode, character())\n )\n )\n gene_summary <- new_data_frame(data@gene.summary)\n cytoband_sumamry <- new_data_frame(data@cytoband.summary)\n cytoband_sumamry <- vec_slice(\n cytoband_sumamry,\n vec_as_location(\n rownames(cn_mat),\n n = vec_size(cytoband_sumamry),\n names = vec_cast(cytoband_sumamry$Unique_Name, character())\n )\n )\n ggalign_data_set(cn_mat,\n sample_anno = sample_anno,\n sample_summary = sample_summary,\n cytoband_sumamry = cytoband_sumamry,\n gene_summary = gene_summary,\n sumamry = data@summary\n )\n}\n"], ["/ggalign/R/craft-align-phylo.R", "#' Plot Phylogenetics tree\n#'\n#' @param phylo A [`phylo`][ape::as.phylo] object.\n#' @param ... <[dyn-dots][rlang::dyn-dots]> Additional arguments passed to\n#' [`geom_segment()`][ggplot2::geom_segment].\n#' @param ladderize A single string of `r oxford_or(c(\"left\", \"right\"))`,\n#' indicating whether to ladderize the tree. Ladderizing arranges the tree so\n#' that the smallest clade is positioned on the `\"right\"` or the `\"left\"`. By\n#' default, `NULL` means the tree will not be ladderized.\n#' @inheritParams fortify_data_frame.phylo\n#' @inheritParams ggalign\n#' @export\nalign_phylo <- function(phylo, ..., ladderize = NULL, type = \"rectangle\",\n center = FALSE, tree_type = NULL,\n no_axes = NULL, active = NULL,\n size = NULL) {\n if (!is.null(ladderize)) {\n ladderize <- arg_match0(ladderize, c(\"left\", \"right\"))\n rlang::check_installed(\"ape\", \"to ladderize phylogenetics tree\")\n }\n assert_s3_class(phylo, \"phylo\")\n assert_active(active)\n active <- update_active(active, new_active(use = TRUE))\n align(\n align = AlignPhylo,\n phylo = phylo,\n ladderize = ladderize,\n no_axes = no_axes,\n plot = ggplot() +\n ggplot2::geom_segment(\n mapping = aes(\n x = .data$x, y = .data$y,\n xend = .data$xend, yend = .data$yend\n ),\n ...,\n stat = \"identity\",\n data = function(data) ggalign_attr(data, \"edge\")\n ),\n data_params = list(type = type, center = center, tree_type = tree_type),\n active = active,\n size = size\n )\n}\n\nAlignPhylo <- ggproto(\"AlignPhylo\", CraftAlign,\n interact_layout = function(self, layout) {\n layout <- ggproto_parent(CraftAlign, self)$interact_layout(layout)\n\n # we keep the names from the layout data for usage\n tip_labels <- self$phylo$tip.label\n if (is.null(tip_labels)) {\n cli_abort(\n \"{.arg phylo} must have tip labels to match the layout data\",\n call = self$call\n )\n } else if (vec_duplicate_any(tip_labels)) {\n cli_abort(\n \"{.arg phylo} cannot have duplicated tip labels\",\n call = self$call\n )\n }\n\n # we ensure the layout data has names to match the phylo tree\n if (is.null(layout_labels <- vec_names(layout@data))) {\n cli_abort(c(\n sprintf(\n \"Cannot add %s to %s\", object_name(self),\n self$layout_name\n ),\n i = sprintf(\n \"%s has no labels (rownames) to match {.arg phylo}\",\n self$layout_name\n )\n ))\n } else if (vec_duplicate_any(layout_labels)) {\n cli_abort(c(\n sprintf(\n \"Cannot add %s to %s\", object_name(self),\n self$layout_name\n ),\n i = sprintf(\"%s has duplicated labels\", self$layout_name)\n ))\n }\n assert_mismatch_nobs(\n self, .subset2(layout@design, \"nobs\"), vec_size(tip_labels),\n arg = \"phylo\"\n )\n\n # we keep the names from the layout data for usage\n self$labels <- layout_labels\n layout\n },\n compute = function(self, panel, index) {\n phylo <- self$phylo\n # R CMD check won't give error even we don't add `ape` to the dependency\n if (!is.null(self$ladderize)) {\n phylo <- ape::ladderize(phylo,\n right = identical(self$ladderize, \"right\")\n )\n }\n inject(fortify_data_frame.phylo(\n data = phylo, !!!self$data_params,\n data_arg = \"phylo\", call = self$call\n ))\n },\n align = function(self, panel, index) {\n data <- self$statistics\n tip <- vec_slice(data, .subset2(data, \"tip\"))\n ordered <- .subset2(tip, \"label\")[order(.subset2(tip, \"x\"))]\n index <- match(ordered, self$labels)\n if (!is.null(panel) && nlevels(panel) > 1L &&\n !all(index == reorder_index(panel, index))) {\n layout_name <- self$layout_name\n object_name <- object_name(self)\n cli_abort(c(\n sprintf(\"Cannot add %s to %s\", object_name, layout_name),\n i = sprintf(\n \"Group of %s will disrupt the ordering index of %s\", layout_name, object_name\n )\n ), call = self$call)\n }\n list(panel, index)\n },\n setup_plot = function(self, plot) {\n ggadd_default(plot, aes(x = .data$x, y = .data$y)) + switch_direction(\n self$direction,\n ggplot2::labs(x = \"timing\"),\n ggplot2::labs(y = \"timing\")\n )\n },\n build_plot = function(self, plot, design, extra_design = NULL,\n previous_design = NULL) {\n if (!is.null(panel <- .subset2(design, \"panel\")) &&\n nlevels(panel) > 1L) {\n layout_name <- self$layout_name\n object_name <- object_name(self)\n cli_abort(c(\n sprintf(\"Cannot add %s to %s\", object_name, layout_name),\n i = sprintf(\"%s cannot span multiple panels\", object_name)\n ))\n }\n\n data <- self$statistics\n edge <- ggalign_attr(data, \"edge\")\n node <- data\n node$.panel <- unique(panel)\n edge$.panel <- unique(panel)\n\n # add names\n if (!is.null(node$label)) {\n node$.names <- node$label\n }\n if (!is.null(edge$label)) {\n edge$.names <- edge$label\n }\n if (is_horizontal(self$direction)) {\n edge <- rename(\n edge,\n c(x = \"y\", xend = \"yend\", y = \"x\", yend = \"xend\")\n )\n node <- rename(node, c(x = \"y\", y = \"x\"))\n }\n plot <- gguse_data(plot, ggalign_data_set(node, edge = edge))\n position <- self$position\n if (!self$in_linear || # for circular layout\n # for top annotation, reverse y-axis\n (!is.null(position) && position == \"top\")) {\n plot <- reverse_continuous_axis(plot, \"y\")\n } else if (!is.null(position) && position == \"right\") {\n # for right annotation, reverse x-axis\n plot <- reverse_continuous_axis(plot, \"x\")\n }\n\n # always turn off clip, this is what dendrogram dependends on\n old_coord <- plot$coordinates\n if (!identical(old_coord$clip, \"off\")) {\n # to prevent from changing the input of user.\n plot$coordinates <- ggproto(NULL, old_coord, clip = \"off\")\n }\n plot\n },\n summary_align = function(self) c(TRUE, FALSE)\n)\n\n#' Build a matrix from `phylo` object\n#'\n#' @description This method allows a [`phylo`][ape::as.phylo] object to be\n#' directly input into `stack_discrete()` or `circle_discrete()`. This makes it\n#' possible to add [`align_phylo()`] to the stack independently, as\n#' [`align_phylo()`] requires the layout to have labels.\n#' @inheritParams rlang::args_dots_empty\n#' @param data A [`phylo`][ape::as.phylo] object.\n#' @inheritParams fortify_matrix\n#' @return A one-column matrix where the tip labels are the values, and the row\n#' names will also be the tip labels.\n#' @family fortify_matrix\n#' @export\nfortify_matrix.phylo <- function(data, ..., data_arg = caller_arg(data),\n call = NULL) {\n call <- call %||% current_call()\n rlang::check_dots_empty(call = call)\n if (is.null(labels <- data$tip.label)) {\n cli_abort(\n \"{.arg {data_arg}} must have tip labels to match the layout data\",\n call = call\n )\n }\n as.matrix(vec_set_names(labels, labels))\n}\n\n#' @inherit fortify_data_frame.default title description\n#' @inheritParams rlang::args_dots_empty\n#' @inheritParams fortify_data_frame.dendrogram\n#' @param tree_type A single string, one of\n#' `r oxford_or(c(\"phylogram\", \"cladogram\"))`, indicating the type of tree.\n#' - `phylogram`: Represents a phylogenetic tree where branch lengths indicate\n#' evolutionary distance or time.\n#' - `cladogram`: Represents a tree where branch lengths are not used, or the\n#' branches do not reflect evolutionary time.\n#'\n#' Usually, you don't need to modify this.\n#'\n#' @param tip_pos The x-coordinates of the tip. Must be the same length\n#' of the number of tips in `tree`.\n#' @return A `data frame` with the node coordinates:\n#' - `.index`: the original index in the tree for the the tip/node.\n#' - `label`: the tip/node label text.\n#' - `x` and `y`: x-axis and y-axis coordinates for the tip/node.\n#' - `tip`: A logical value indicates whether current node is a tip.\n#' @section ggalign attributes:\n#' `edge`: A `data frame` for edge coordinates:\n#'\n#' - `x` and `y`: x-axis and y-axis coordinates for the start node of the edge.\n#' - `xend` and `yend`: the x-axis and y-axis coordinates of the terminal node\n#' for edge.\n#' @family fortify_data_frame\n#' @export\nfortify_data_frame.phylo <- function(data, ..., type = \"rectangle\",\n center = FALSE,\n tree_type = NULL, tip_pos = NULL,\n data_arg = NULL, call = NULL) {\n call <- call %||% current_call()\n data_arg <- data_arg %||% \"data\"\n rlang::check_dots_empty(call = call)\n type <- arg_match0(type, c(\"rectangle\", \"triangle\"))\n rectangle <- type == \"rectangle\"\n edge <- data$edge\n edge_lengths <- data$edge.length\n if (!is.null(tree_type)) {\n tree_type <- arg_match0(tree_type,\n c(\"phylogram\", \"cladogram\"),\n error_call = call\n )\n if (tree_type == \"phylogram\" && is.null(edge_lengths)) {\n cli_warn(c(\n \"Cannot use {.code tree_type = 'phylogram'}\",\n \"No branch length found in {.arg {data_arg}}\"\n ))\n tree_type <- \"cladogram\"\n }\n }\n if (identical(tree_type, \"cladogram\")) {\n edge_lengths <- NULL\n }\n parent <- edge[, 1L, drop = TRUE]\n child <- edge[, 2L, drop = TRUE]\n tip_labels <- data$tip.label\n node_labels <- data$node.label\n N <- length(tip_labels)\n if (is.null(tip_pos)) {\n tip_pos <- seq_len(N)\n } else if (length(tip_pos) != N) {\n cli_abort(\n \"{.arg tip_pos} must have the same length as the number of tips in {.arg {data_arg}}\",\n call = call\n )\n }\n i <- 0L # tip index\n phylo_data <- function(index, level, timing) {\n if (any(select <- parent == index)) {\n # recursively for each child\n data <- list(index = child[select])\n # if we have edge length, timing should be available\n if (!is.null(edge_lengths)) {\n data <- c(data, list(timing = timing + edge_lengths[select]))\n }\n data <- list_transpose(.mapply(\n function(index, timing = NULL) {\n phylo_data(index, level = level + 1L, timing = timing)\n },\n data, NULL\n ))\n\n # integrate the data for each child\n node <- vec_rbind(!!!.subset2(data, \"node\"))\n edge <- vec_rbind(!!!.subset2(data, \"edge\"))\n\n # all coordinate for direct children nodes -------------\n direct_leaves_x <- unlist(\n .subset2(data, \"x\"),\n recursive = FALSE, use.names = FALSE\n )\n direct_leaves_y <- unlist(\n .subset2(data, \"y\"),\n recursive = FALSE, use.names = FALSE\n )\n\n # prepare node data ------------------------------------\n # all x coordinate for children nodes ------------------\n # used if center is `TRUE`, we'll calculate the center position\n # among all children nodes\n leaves <- vec_slice(node, .subset2(node, \"tip\")) # all leaves\n\n # x coordinate for current node: the midpoint\n if (center) {\n x <- sum(range(.subset2(leaves, \"x\"))) / 2L\n } else {\n x <- sum(range(direct_leaves_x)) / 2L\n }\n\n # y coordinate for current node\n if (is.null(edge_lengths) && is.null(timing)) {\n y <- min(direct_leaves_y) * level / (level + 1L)\n } else {\n y <- timing\n }\n\n # there is no node data for the root\n node <- vec_rbind(data_frame0(\n .index = index,\n label = node_labels[index - N],\n x = x, y = y, tip = FALSE\n ), node)\n\n # if it's the `rectangle`\n if (rectangle) {\n # vertical lines\n vertical_lines <- data_frame0(\n x = direct_leaves_x,\n xend = direct_leaves_x,\n y = y,\n yend = direct_leaves_y\n )\n added_edge <- vec_rbind(\n vertical_lines,\n # horizontal line\n data_frame0(\n x = x,\n xend = direct_leaves_x,\n y = y,\n yend = y\n )\n )\n } else {\n added_edge <- data_frame0(\n x = x,\n xend = direct_leaves_x,\n y = y,\n yend = direct_leaves_y\n )\n }\n if (is.null(edge)) {\n edge <- added_edge\n } else {\n edge <- vec_rbind(added_edge, edge)\n }\n list(node = node, edge = edge, x = x, y = y)\n } else if (any(select <- child == index)) { # for the tip\n i <<- i + 1L\n x <- tip_pos[i]\n if (is.null(edge_lengths)) {\n y <- 1L\n } else {\n y <- timing\n }\n\n list(\n node = data_frame0(\n .index = index,\n label = tip_labels[index],\n x = x,\n y = y,\n tip = TRUE\n ),\n edge = NULL,\n x = x, y = y\n )\n } else {\n cli_abort(\"Invalid {.cls phylo} provided in {.arg {data_arg}}\",\n call = call\n )\n }\n }\n\n # from ape::is.rooted, this should be the most ancester\n ans <- phylo_data(N + 1L, 0L, timing = 0)\n ggalign_data_set(.subset2(ans, \"node\"), edge = .subset2(ans, \"edge\"))\n}\n"], ["/ggalign/R/layout-chain-circle-.R", "#' Arrange plots in a circular layout\n#'\n#' @description\n#' `r lifecycle::badge('experimental')`\n#'\n#' If `limits` is provided, a continuous variable will be required and aligned\n#' in the direction specified (`circle_continuous`). Otherwise, a discrete\n#' variable will be required and aligned (`circle_discrete`).\n#'\n#' @param radial A [`coord_circle()`]/[`coord_radial()`][ggplot2::coord_radial]\n#' object that defines the global parameters for coordinate across all plots\n#' in the layout. The parameters `start`, `end`, `direction`, and `expand` will\n#' be inherited and applied uniformly to all plots within the layout. The\n#' parameters `theta` and `r.axis.inside` will always be ignored and will be set\n#' to `\"x\"` and `TRUE`, respectively, for all plots.\n#' @param direction A single string of `r oxford_or(c(\"inward\", \"outward\"))`,\n#' indicating the direction in which the plot is added.\n#' - `outward`: The plot is added from the inner to the outer.\n#' - `inward`: The plot is added from the outer to the inner.\n#' @inheritParams stack_layout\n#' @return A `CircleLayout` object.\n#' @examples\n#' set.seed(123)\n#'\n#' small_mat <- matrix(rnorm(56), nrow = 7)\n#' rownames(small_mat) <- paste0(\"row\", seq_len(nrow(small_mat)))\n#' colnames(small_mat) <- paste0(\"column\", seq_len(ncol(small_mat)))\n#'\n#' # circle_layout\n#' # same for circle_discrete()\n#' circle_layout(small_mat) +\n#' ggalign() +\n#' geom_tile(aes(y = .column_index, fill = value)) +\n#' scale_fill_viridis_c() +\n#' align_dendro(aes(color = branch), k = 3L) +\n#' scale_color_brewer(palette = \"Dark2\")\n#'\n#' # same for circle_continuous()\n#' circle_layout(mpg, limits = continuous_limits(c(3, 5))) +\n#' ggalign(mapping = aes(displ, hwy, colour = class)) +\n#' geom_point(size = 2) +\n#' ggalign(mapping = aes(displ, hwy, colour = class)) +\n#' geom_point(size = 2) &\n#' scale_color_brewer(palette = \"Dark2\") &\n#' theme_bw()\n#'\n#' @export\ncircle_layout <- function(data = NULL, ..., radial = NULL,\n direction = \"outward\", sector_spacing = NULL,\n limits = waiver(), theme = NULL,\n spacing_theta = deprecated()) {\n if (is.waive(limits)) {\n circle_discrete(\n data = data, ..., radial = radial,\n direction = direction, sector_spacing = sector_spacing,\n theme = theme, spacing_theta = spacing_theta\n )\n } else {\n circle_continuous(\n data = data, ..., radial = radial,\n direction = direction, theme = theme, limits = limits,\n spacing_theta = spacing_theta\n )\n }\n}\n\n############################################################\n#' @inheritParams facet_sector\n#' @examples\n#' # circle_discrete()\n#' # direction outward\n#' circle_discrete(small_mat) +\n#' align_dendro(aes(color = branch), k = 3L) +\n#' scale_color_brewer(palette = \"Dark2\") +\n#' ggalign() +\n#' geom_tile(aes(y = .column_index, fill = value)) +\n#' scale_fill_viridis_c()\n#'\n#' # direction inward\n#' circle_discrete(small_mat, direction = \"inward\") +\n#' ggalign() +\n#' geom_tile(aes(y = .column_index, fill = value)) +\n#' scale_fill_viridis_c() +\n#' align_dendro(aes(color = branch), k = 3L) +\n#' scale_color_brewer(palette = \"Dark2\")\n#'\n#' @export\n#' @rdname circle_layout\ncircle_discrete <- function(data = NULL, ..., radial = NULL,\n direction = \"outward\", sector_spacing = NULL,\n theme = NULL, spacing_theta = deprecated()) {\n UseMethod(\"circle_discrete\", data)\n}\n\n#' @export\ncircle_discrete.default <- function(data = NULL, ..., radial = NULL,\n direction = \"outward\",\n sector_spacing = NULL,\n theme = NULL,\n spacing_theta = deprecated()) {\n # the observations are rows, we use matrix to easily\n # reshape it into a long formated data frame for ggplot,\n # and we can easily determine the number of observations\n # from matrix\n data <- data %|w|% NULL\n data <- fortify_matrix(data = data, ...)\n schemes <- default_schemes()\n if (!is.null(data) && !is.function(data)) {\n # if we have provided data, we initialize the `nobs`\n nobs <- vec_size(data)\n } else {\n nobs <- NULL\n }\n new_circle_layout(\n data = data,\n design = discrete_design(nobs = nobs),\n radial = radial, direction = direction, sector_spacing = sector_spacing,\n schemes = schemes, theme = theme, spacing_theta = spacing_theta\n )\n}\n\n#' @export\ncircle_discrete.function <- function(data = NULL, ...) {\n cli_abort(paste0(\n \"{.arg data} must be a {.cls matrix}, \",\n \"or an object coercible by {.fn fortify_matrix}, or a valid \",\n \"{.cls matrix}-like object coercible by {.fn as.matrix}\"\n ))\n}\n\n#' @export\ncircle_discrete.formula <- circle_discrete.function\n\n################################################################\n#' @examples\n#' # circle_continuous()\n#' circle_continuous(mpg, limits = continuous_limits(c(3, 5))) +\n#' ggalign(mapping = aes(displ, hwy, colour = class)) +\n#' geom_point(size = 2) +\n#' ggalign(mapping = aes(displ, hwy, colour = class)) +\n#' geom_point(size = 2) &\n#' scale_color_brewer(palette = \"Dark2\") &\n#' theme_bw()\n#' @export\n#' @rdname circle_layout\ncircle_continuous <- function(data = NULL, ..., radial = NULL,\n direction = \"outward\", sector_spacing = NULL,\n limits = NULL, theme = NULL,\n spacing_theta = deprecated()) {\n UseMethod(\"circle_continuous\", data)\n}\n\n#' @export\ncircle_continuous.default <- function(data = NULL, ..., radial = NULL,\n direction = \"outward\",\n sector_spacing = NULL,\n limits = NULL, theme = NULL,\n spacing_theta = deprecated()) {\n assert_limits(limits)\n data <- data %|w|% NULL\n data <- fortify_data_frame(data = data, ...)\n schemes <- default_schemes()\n new_circle_layout(\n data = data, design = limits,\n radial = radial, direction = direction, sector_spacing = sector_spacing,\n schemes = schemes, theme = theme, spacing_theta = spacing_theta\n )\n}\n\n#' @export\ncircle_continuous.function <- function(data = NULL, ...) {\n cli_abort(paste0(\n \"{.arg data} must be a {.cls data.frame}, \",\n \"or an object coercible by {.fn fortify_data_frame}, or a valid \",\n \"{.cls data.frame}-like object coercible by {.fn as.data.frame}\"\n ))\n}\n\n#' @export\ncircle_continuous.formula <- circle_continuous.function\n\n#' @importFrom methods new\nnew_circle_layout <- function(data, design, radial, direction,\n sector_spacing = NULL, schemes = NULL,\n theme = NULL, name = NULL,\n spacing_theta = deprecated(),\n call = caller_call()) {\n if (!is.null(theme)) assert_s3_class(theme, \"theme\", call = call)\n if (!is.null(radial) && !inherits(radial, c(\"CoordRadial\"))) {\n cli_abort(\"{.arg radial} must be created with {.fn coord_circle}\",\n call = call\n )\n }\n if (!is.null(radial) && abs(diff(radial$arc)) < pi / 2L) {\n cli_abort(\n \"Cannot create circle of acute angle < 90 in {.arg radial}\",\n call = call\n )\n }\n direction <- arg_match0(direction, c(\"inward\", \"outward\"))\n if (is.null(name)) {\n if (is_continuous_design(design)) {\n name <- \"circle_continuous\"\n } else {\n name <- \"circle_discrete\"\n }\n }\n if (lifecycle::is_present(spacing_theta)) {\n lifecycle::deprecate_warn(\n \"1.0.2\",\n \"facet_sector(spacing_theta = )\",\n \"facet_sector(sector_spacing = )\"\n )\n if (is.null(sector_spacing)) sector_spacing <- spacing_theta\n }\n new(\n \"CircleLayout\",\n name = name, data = data,\n schemes = schemes, # used by the layout\n design = design,\n sector_spacing = sector_spacing,\n theme = theme,\n radial = radial, direction = direction\n )\n}\n\n############################################################\n# Used to place multiple objects in one axis\n#' @importFrom grid unit\n#' @importFrom ggplot2 waiver\n#' @keywords internal\n#' @include layout-chain-.R\nmethods::setClass(\"CircleLayout\",\n contains = \"ChainLayout\",\n list(radial = \"ANY\", sector_spacing = \"ANY\", direction = \"character\")\n)\n"], ["/ggalign/R/layout-quad-.R", "#' Arrange plots in the quad-side of a main plot\n#'\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' This function arranges plots around the quad-sides of a main plot, aligning\n#' both horizontal and vertical axes, and can handle either discrete or\n#' continuous variables.\n#'\n#' - If `xlim` is provided, a continuous variable will be required and aligned\n#' in the vertical direction. Otherwise, a discrete variable will be required\n#' and aligned.\n#' - If `ylim` is provided, a continuous variable will be required and aligned\n#' in the horizontal direction. Otherwise, a discrete variable will be\n#' required and aligned.\n#'\n#' The `quad_discrete` is a special case where both `xlim` and `ylim` are not\n#' provided.\n#'\n#' The `quad_continuous` is a special case where both `xlim` and `ylim` are\n#' provided.\n#'\n#' For historical reasons, the following aliases are available:\n#' - `quad_alignh`: Align discrete variables in the horizontal direction and\n#' continuous variables in vertical direction.\n#' - `quad_alignv`: Align discrete variables in the vertical direction and\n#' continuous variables in horizontal direction.\n#' - `quad_alignb` is an alias for `quad_discrete`.\n#' - `quad_free` is an alias for `quad_continuous`.\n#'\n#' @param data `r rd_layout_data()`. By default, this will attempt\n#' to inherit from the parent layout.\n#'\n#' If both `xlim` and `ylim` are provided, a `data frame` is required, and\n#' [`fortify_data_frame()`] will be used to convert the data to a data frame.\n#' When inherited by an annotation stack, no transposition will be applied.\n#'\n#' Otherwise, a `matrix` is required, and [`fortify_matrix()`] will be used to\n#' convert the data to a matrix. When inherited by the column annotation\n#' stack, the data will be transposed.\n#' @param mapping Default list of aesthetic mappings to use for main plot in the\n#' layout. If not specified, must be supplied in each layer added to the main\n#' plot.\n#' @param xlim,ylim A [`continuous_limits()`] object specifying the left/lower\n#' limit and the right/upper limit of the scale. Used to align the continuous\n#' axis.\n#' @param width,height The relative width/height of the main plot, can be a\n#' [`unit`][grid::unit] object.\n#' @inheritParams stack_layout\n#' @inheritParams align\n#' @return A `QuadLayout` object.\n#' @section ggplot2 specification:\n#' If either `xlim` or `ylim` is not provided, the data input will be converted\n#' to a matrix using [`fortify_matrix()`], and the data in the underlying main\n#' plot will contain the following columns:\n#'\n#' - `.panel_x` and `.panel_y`: the column and row panel groups.\n#'\n#' - `.x` and `.y`: an integer index of `x` and `y` coordinates\n#'\n#' - `.discrete_x` and `.discrete_y`: a factor of the data labels (only\n#' applicable when `.row_names` and `.column_names` exists).\n#'\n#' - `.row_names` and `.column_names`: A character of the row and column names\n#' of the original matrix (only applicable when names exist).\n#'\n#' - `.row_index` and `.column_index`: the row and column index of the original\n#' matrix.\n#'\n#' - `value`: the actual matrix value.\n#'\n#' Otherwise, the data input will be used for the main plot.\n#'\n#' @export\nquad_layout <- function(data = waiver(), mapping = aes(),\n xlim = waiver(), ylim = waiver(),\n ...,\n theme = NULL, active = NULL,\n width = NA, height = NA) {\n if (is.waive(xlim) && is.waive(ylim)) {\n quad_discrete(\n data = data, mapping = mapping,\n ..., active = active, theme = theme,\n width = width, height = height\n )\n } else if (!is.waive(xlim) && !is.waive(ylim)) {\n quad_continuous(\n data = data, mapping = mapping, xlim = xlim, ylim = ylim,\n ..., active = active, theme = theme,\n width = width, height = height\n )\n } else {\n data <- fortify_matrix(data = data, ...)\n new_quad_layout(\n name = \"quad_layout\",\n data = data, ylim = ylim, xlim = xlim,\n mapping = mapping, active = active, theme = theme,\n width = width, height = height\n )\n }\n}\n\n#' @export\n#' @rdname quad_layout\nquad_alignh <- function(..., ylim = waiver()) {\n quad_layout(..., xlim = NULL, ylim = ylim)\n}\n\n#' @export\n#' @rdname quad_layout\nquad_alignv <- function(..., xlim = waiver()) {\n quad_layout(..., xlim = xlim, ylim = NULL)\n}\n\n##########################################################\n#' @export\n#' @rdname quad_layout\nquad_discrete <- function(data = waiver(), mapping = aes(),\n ...,\n theme = NULL, active = NULL,\n width = NA, height = NA) {\n UseMethod(\"quad_discrete\")\n}\n\n#' @export\n#' @rdname quad_layout\n#' @usage NULL\nquad_alignb <- quad_discrete\n\n#' @export\nquad_discrete.default <- function(data = waiver(), mapping = aes(),\n ...,\n theme = NULL, active = NULL,\n width = NA, height = NA) {\n data <- fortify_matrix(data = data, ...)\n new_quad_layout(\n name = \"quad_discrete\", data = data, xlim = waiver(), ylim = waiver(),\n mapping = mapping, active = active, theme = theme,\n width = width, height = height\n )\n}\n\n#' @export\nquad_discrete.uneval <- function(data, ...) {\n cli_abort(c(\n \"{.arg data} cannot be {.obj_type_friendly {data}}\",\n \"i\" = \"Have you misspelled the {.arg data} argument in {.fn quad_discrete}\"\n ))\n}\n\n#############################################################\n#' @export\n#' @rdname quad_layout\nquad_continuous <- function(data = waiver(), mapping = aes(),\n xlim = NULL, ylim = NULL,\n ...,\n theme = NULL, active = NULL,\n width = NA, height = NA) {\n UseMethod(\"quad_continuous\")\n}\n\n#' @usage NULL\n#' @export\n#' @rdname quad_layout\nggside <- quad_continuous\n\n#' @usage NULL\n#' @export\n#' @rdname quad_layout\nquad_free <- quad_continuous\n\n#' @export\nquad_continuous.default <- function(data = waiver(), mapping = aes(),\n xlim = NULL, ylim = NULL,\n ...,\n theme = NULL, active = NULL,\n width = NA, height = NA) {\n xlim <- xlim %|w|% NULL\n ylim <- ylim %|w|% NULL\n data <- fortify_data_frame(data = data, ...)\n new_quad_layout(\n name = \"quad_continuous\",\n data = data, xlim = xlim, ylim = ylim,\n mapping = mapping, active = active, theme = theme,\n width = width, height = height\n )\n}\n\n#' @export\nquad_continuous.uneval <- function(data, ...) {\n cli_abort(c(\n \"{.arg data} cannot be {.obj_type_friendly {data}}\",\n \"i\" = \"Have you misspelled the {.arg data} argument in {.fn quad_free}\"\n ))\n}\n\n#####################################################\n#' @importFrom ggplot2 ggplot\n#' @importFrom methods new\nnew_quad_layout <- function(name, data, xlim = waiver(), ylim = waiver(),\n mapping = aes(), theme = NULL, active = NULL,\n width = NA, height = NA,\n class = \"QuadLayout\",\n call = caller_call()) {\n if (!is.waive(xlim)) assert_limits(xlim, call = call)\n if (!is.waive(ylim)) assert_limits(ylim, call = call)\n if (is.waive(xlim) || is.waive(ylim)) {\n # If we need align discrete variables, data cannot be `NULL` and\n # must be provided, here, we convert it to waiver() to indicate\n # inherit from the parent layout\n data <- data %||% waiver()\n if (!is.waive(data) && !is.function(data)) {\n nrows <- NROW(data)\n ncols <- ncol(data)\n\n # for data has dimention but one dimention is 0\n # as.matrix(data.frame(row.names = letters))\n if (nrows == 0L || ncols == 0L) {\n cli_abort(\"empty data is no allowed\")\n }\n } else {\n nrows <- NULL\n ncols <- NULL\n }\n }\n horizontal <- ylim %|w|% discrete_design(nobs = nrows)\n vertical <- xlim %|w|% discrete_design(nobs = ncols)\n\n # always remove default axis titles\n # https://stackoverflow.com/questions/72402570/why-doesnt-gplot2labs-overwrite-update-the-name-argument-of-scales-function\n # There are multiple ways to set labels in a plot, which take different\n # priorities. Here are the priorities from highest to lowest.\n # 1. The guide title.\n # 2. The scale name.\n # 3. The `labs()` function.\n # 4. The captured expression in aes().\n plot <- ggplot(mapping = mapping) +\n ggplot2::labs(x = NULL, y = NULL)\n\n if (!is.null(theme)) assert_s3_class(theme, \"theme\", call = call)\n # for `QuadLayout`, we use `NULL` to inherit data from parent layout\n # since `QuadLayout` must have data, and won't be waiver()\n # if inherit from the parent layout data, we'll inherit\n # the action data function\n schemes <- default_schemes(\n if (is.null(data)) waiver() else NULL,\n th = theme_no_strip()\n )\n\n # check arguments -----------------------------------\n width <- check_size(width, call = call)\n height <- check_size(height, call = call)\n assert_active(active, call = call)\n\n # Here we use S4 object to override the double dispatch of `+.gg` method\n new(\n class,\n # used by the layout\n data = data, theme = theme,\n schemes = schemes,\n plot_active = update_active(active, new_active(use = TRUE)),\n name = name,\n # used by the main body\n body_schemes = default_schemes(waiver()),\n # following parameters can be controlled by `quad_switch`\n width = width, height = height,\n # following parameters are used internally\n plot = plot, horizontal = horizontal, vertical = vertical\n )\n}\n\n# Used to create the QuadLayout\n#' @include layout-.R\nmethods::setClass(\n \"QuadLayout\",\n contains = \"LayoutProto\",\n list(\n data = \"ANY\", plot = \"ANY\", body_schemes = \"list\", name = \"character\",\n # parameters for main body\n width = \"ANY\", height = \"ANY\",\n # Used to align axis\n horizontal = \"ANY\", vertical = \"ANY\",\n # top, left, bottom, right must be a StackLayout object.\n top = \"ANY\", left = \"ANY\", bottom = \"ANY\", right = \"ANY\",\n # If we regard `QuadLayout` as a plot, and put it into the stack\n # layout, we need following arguments to control it's behavour\n plot_active = \"ANY\"\n ),\n prototype = list(\n # used by QuadLayout\n top = NULL, left = NULL, bottom = NULL, right = NULL\n )\n)\n\n#' @export\nis_layout_discrete.QuadLayout <- function(x, direction, ...) {\n is_discrete_design(slot(x, direction))\n}\n\n#' @export\nis_layout_continuous.QuadLayout <- function(x, direction, ...) {\n is_continuous_design(slot(x, direction))\n}\n"], ["/ggalign/R/layout-heatmap-.R", "#' Create a heatmap\n#'\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' `heatmap_layout` is a specialized version of [`quad_discrete()`], which\n#' simplifies the creation of heatmap plots by integrating essential elements\n#' for a standard heatmap layout, ensuring that the appropriate data mapping and\n#' visualization layers are automatically applied. `ggheatmap` is an alias for\n#' `heatmap_layout`.\n#'\n#' @param data `r rd_layout_data()`. By default, it will try to inherit from\n#' parent layout. [`fortify_matrix()`] will be used to convert data to a\n#' matrix.\n#' @param ... Additional arguments passed to [`fortify_matrix()`].\n#' @inheritParams quad_layout\n#' @param filling A single string of `r oxford_or(c(\"raster\", \"tile\"))` to\n#' indicate the filling style. By default, `waiver()` is used, which means that\n#' if the input matrix has more than 20,000 cells (`nrow * ncol > 20000`),\n#' [`geom_raster()`][ggplot2::geom_raster] will be used for performance\n#' efficiency; for smaller matrices, [`geom_tile()`][ggplot2::geom_tile] will be\n#' used. To customize the filling style, set this to `NULL`.\n#'\n#' For backward compatibility, a single boolean value is acceptable: `TRUE`\n#' means `waiver()`, and `FALSE` means `NULL`.\n#'\n#' By default, the classic heatmap color scheme\n#' [`scale_fill_gradient2(low = \"blue\", high = \"red\")`][ggplot2::scale_fill_gradient2]\n#' is utilized for continuous values.\n#'\n#' You can use the options\n#' `r code_quote(sprintf(\"%s.heatmap_continuous_fill\", pkg_nm()))` or\n#' `r code_quote(sprintf(\"%s.heatmap_discrete_fill\", pkg_nm()))` to modify the\n#' default heatmap body filling color scale. See\n#' [`scale_fill_continuous()`][ggplot2::scale_fill_continuous] or\n#' [`scale_fill_discrete()`][ggplot2::scale_fill_discrete] for details on\n#' option settings.\n#'\n#' @section ggplot2 specification:\n#' The data input will be converted to a matrix using [`fortify_matrix()`], and\n#' the data in the underlying main plot will contain the following columns:\n#'\n#' - `.panel_x` and `.panel_y`: the column and row panel groups.\n#'\n#' - `.x` and `.y`: an integer index of `x` and `y` coordinates\n#'\n#' - `.discrete_x` and `.discrete_y`: a factor of the data labels (only\n#' applicable when `.row_names` and `.column_names` exists).\n#'\n#' - `.row_names` and `.column_names`: A character of the row and column names\n#' of the original matrix (only applicable when names exist).\n#'\n#' - `.row_index` and `.column_index`: the row and column index of the original\n#' matrix.\n#'\n#' - `value`: the actual matrix value.\n#'\n#' @return A `HeatmapLayout` object.\n#' @examples\n#' ggheatmap(1:10)\n#' ggheatmap(letters)\n#' ggheatmap(matrix(rnorm(81), nrow = 9L))\n#' @importFrom ggplot2 aes\n#' @export\nheatmap_layout <- function(data = NULL, mapping = aes(),\n ...,\n width = NA, height = NA, filling = waiver(),\n theme = NULL, active = NULL) {\n UseMethod(\"heatmap_layout\")\n}\n\n#' @usage NULL\n#' @export\n#' @rdname heatmap_layout\nggheatmap <- heatmap_layout\n\n#' @importFrom ggplot2 aes\n#' @importFrom rlang arg_match0\n#' @export\nheatmap_layout.default <- function(data = NULL, mapping = aes(),\n ...,\n width = NA, height = NA, filling = waiver(),\n theme = NULL, active = NULL) {\n # A single boolean value for compatible with `version <= 0.0.4`\n if (isTRUE(filling)) {\n filling <- waiver()\n } else if (isFALSE(filling)) {\n filling <- NULL\n } else if (!is.waive(filling) && !is.null(filling)) {\n filling <- arg_match0(filling, c(\"tile\", \"raster\"))\n }\n data <- data %|w|% NULL\n # we need a matrix to melted into long formated data frame\n data <- fortify_matrix(data = data, ...)\n ans <- new_quad_layout(\n name = \"ggheatmap\",\n data = data,\n mapping = mapping,\n theme = theme, active = active,\n width = width, height = height,\n class = \"HeatmapLayout\"\n )\n # add default mapping\n ans@plot <- ggadd_default(ans@plot, mapping = aes(.data$.x, .data$.y)) +\n ggplot2::labs(x = NULL, y = NULL)\n ans@filling <- filling\n ans\n}\n\n# used to create the heatmap layout\n#' @keywords internal\n#' @include layout-quad-.R\nmethods::setClass(\n \"HeatmapLayout\",\n contains = \"QuadLayout\",\n list(filling = \"ANY\") # parameters for heatmap body\n)\n"], ["/ggalign/R/ggfree.R", "#' Add ggplot to layout without alignment\n#'\n#' @description\n#' `r lifecycle::badge('experimental')`\n#'\n#' The `ggfree()` function allows you to incorporate a ggplot object into your\n#' layout. Unlike `ggalign()`, which aligns every axis value precisely,\n#' `ggfree()` focuses on integrating plots into the layout without enforcing\n#' strict axis alignment.\n#'\n#' @inheritParams ggalign\n#'\n#' @section ggplot2 specification:\n#' `ggalign` initializes a ggplot object. The underlying data is created using\n#' [`fortify_data_frame()`]. Please refer to this method for more details.\n#'\n#' When used in `quad_layout()`/`ggheatmap()`, if the data is inherited from the\n#' `quad_layout()` and the other direction aligns discrete variables, following\n#' columns will be added:\n#'\n#' - `.extra_panel`: Provides the panel information for the column (left or\n#' right annotation) or row (top or bottom annotation).\n#' - `.extra_index`: The index information for the column (left or right\n#' annotation) or row (top or bottom annotation).\n#'\n#' @examples\n#' ggheatmap(matrix(rnorm(56), nrow = 7)) +\n#' anno_top() +\n#' align_dendro() +\n#' ggfree(mtcars, aes(wt, mpg)) +\n#' geom_point()\n#' @export\nggfree <- function(data = waiver(), ..., size = NULL, active = NULL) {\n UseMethod(\"ggfree\", data)\n}\n\n#' @inheritParams ggplot2::ggplot\n#' @importFrom ggplot2 ggplot\n#' @export\n#' @rdname ggfree\nggfree.default <- function(data = waiver(), mapping = aes(), ...,\n size = NULL, active = NULL) {\n data <- fortify_data_frame(data = data, ...)\n new_free_gg(\n plot = ggplot(data = NULL, mapping = mapping),\n data = data,\n size = size,\n active = active\n )\n}\n\n#' @export\nggfree.uneval <- function(data = waiver(), ...) {\n cli_abort(c(\n \"{.arg data} cannot be {.obj_type_friendly {data}}\",\n \"i\" = \"Have you misspelled the {.arg data} argument in {.fn ggalign}\"\n ))\n}\n\n#' @export\nggfree.ggplot <- function(data = waiver(), ..., size = NULL, active = NULL) {\n rlang::check_dots_empty()\n plot <- data\n # In ggplot2, `waiver()` was regard to no data\n data <- plot$data %|w|% NULL\n plot <- gguse_data(plot, waiver())\n new_free_gg(plot, data, size = size, active = active)\n}\n\nnew_free_gg <- function(plot, data, size, active,\n call = caller_call()) {\n assert_active(active, allow_null = TRUE, call = call)\n active <- update_active(active, new_active(use = TRUE))\n new_craftbox(\n FreeGg,\n # new field for FreeGg\n input_data = data,\n # slots for the plot\n plot = plot,\n size = size,\n active = active,\n schemes = default_schemes(data),\n call = call\n )\n}\n\n#' @importFrom ggplot2 ggproto\nFreeGg <- ggproto(\"FreeGg\", Craftsman,\n free_facet = TRUE,\n free_limits = TRUE,\n interact_layout = function(self, layout) {\n layout_data <- layout@data\n if (is.waive(input_data <- self$input_data)) { # inherit from the layout\n data <- layout_data\n self$labels <- vec_names(layout_data)\n\n # for data inherit from the layout, and the design is for discrete\n # variable, we'll integrate the design into the plot data\n self$use_design <- is_stack_layout(layout)\n\n # if the layout data is from the quad-layout, we use the discrete\n # `design`\n self$use_extra_design <- is_stack_layout(layout) &&\n isTRUE(layout@heatmap$quad_matrix)\n } else if (is.function(input_data)) {\n if (is.null(layout_data)) {\n cli_abort(c(\n sprintf(\n \"{.arg data} in %s cannot be a function\",\n object_name(self)\n ),\n i = sprintf(\"no data was found in %s\", self$layout_name)\n ))\n }\n data <- input_data(layout_data)\n } else {\n data <- input_data\n }\n self$data <- ggalign_data_restore(\n fortify_data_frame(data, call = self$call), layout_data\n )\n layout\n },\n build_plot = function(self, plot, design, extra_design = NULL,\n previous_design = NULL) {\n if (is.function(data <- self$data)) {\n data <- NULL\n }\n if (is.null(data)) {\n return(gguse_data(plot, data))\n }\n if (isTRUE(self$use_extra_design) &&\n is_discrete_design(extra_design) &&\n !is.null(.subset2(extra_design, \"nobs\"))) {\n extra_plot_data <- data_frame0(\n .extra_panel = .subset2(extra_design, \"panel\"),\n .extra_index = .subset2(extra_design, \"index\")\n )\n } else {\n extra_plot_data <- NULL\n }\n\n # if inherit from the parent layout\n if (isTRUE(self$use_design) &&\n is_discrete_design(design) &&\n !is.null(.subset2(design, \"nobs\"))) {\n plot_data <- data_frame0(\n .panel = .subset2(design, \"panel\"),\n .index = .subset2(design, \"index\"),\n .names = .subset(self$labels, .subset2(design, \"index\"))\n )\n if (!is.null(extra_plot_data)) {\n plot_data <- cross_join(plot_data, extra_plot_data)\n data <- full_join(data, plot_data,\n by.x = c(\".column_index\", \".row_index\"),\n by.y = c(\".extra_index\", \".index\")\n )\n } else {\n data <- full_join(data, plot_data,\n by.x = \".row_index\", by.y = \".index\"\n )\n }\n } else if (!is.null(extra_plot_data)) {\n data <- full_join(data, extra_plot_data,\n by.x = \".column_index\", by.y = \".extra_index\"\n )\n }\n gguse_data(plot, data)\n },\n summary = function(self, plot) {\n header <- ggproto_parent(Craftsman, self)$summary(plot)\n c(header, \" Add plot without alignment\")\n }\n)\n"], ["/ggalign/R/ggalign.R", "#' Add ggplot by Aligning discrete or continuous variable\n#'\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' `ggalign()` is similar to `ggplot` in that it initializes a `ggplot` data and\n#' `mapping`. `ggalign()` allowing you to provide data in various formats,\n#' including matrices, data frames, or simple vectors. By default, it will\n#' inherit from the layout. If a function, it will apply with the layout matrix.\n#' `ggalign()` focuses on integrating plots into a layout by aligning the axes.\n#'\n#' @param data The following options can be used:\n#' - `NULL`: No data is set.\n#' - [`waiver()`][ggplot2::waiver]: Inherits the data from the layout matrix.\n#' - A `function` (including purrr-like lambda syntax): Applied to the layout\n#' matrix to transform the data before use. To transform the final plot\n#' data, please use [`scheme_data()`].\n#' - A `matrix`, `data.frame`, or atomic vector.\n#' @inheritParams ggplot2::ggplot\n#' @param ... <[dyn-dots][rlang::dyn-dots]> Additional arguments passed to\n#' [`fortify_data_frame()`].\n#' @param size The relative size of the plot, can be specified as a\n#' [`unit()`][grid::unit]. Note that for [`circle_layout()`], all size values\n#' will be interpreted as relative sizes, as this layout type adjusts based on\n#' the available space in the circular arrangement.\n#' @param no_axes `r lifecycle::badge('experimental')` Logical; if `TRUE`,\n#' removes axes elements for the alignment axis using [`theme_no_axes()`]. By\n#' default, will use the option-\n#' `r code_quote(sprintf(\"%s.align_no_axes\", pkg_nm()))`.\n#' @param active A [`active()`] object that defines the context settings when\n#' added to a layout.\n#' @section ggplot2 specification:\n#' `ggalign` initializes a ggplot object. The underlying data is created using\n#' [`fortify_data_frame()`]. Please refer to it for more details.\n#'\n#' When aligning discrete variables, `ggalign()` always applies a default\n#' mapping for the axis of the data index in the layout. Specifically:\n#'\n#' - `aes(y = .data$.y)` is used for the horizontal `stack_layout()` (including\n#' left and right annotations).\n#' - `aes(x = .data$.x)` is used for the vertical `stack_layout()` (including\n#' top and bottom annotations) and `circle_layout()`.\n#'\n#' The following columns will be added to the data frame to align discrete\n#' variables:\n#'\n#' - `.panel`: The panel for the aligned axis. Refers to the `x-axis` for\n#' vertical `stack_layout()` (including top and bottom annotations), and the\n#' `y-axis` for horizontal `stack_layout()` (including left and right\n#' annotations).\n#'\n#' - `.names` ([`vec_names()`][vctrs::vec_names]) and `.index`\n#' ([`vec_size()`][vctrs::vec_size()]/[`NROW()`]): Character names (if\n#' available) and the integer index of the original data.\n#'\n#' - `.x`/`.y` and `.discrete_x`/`.discrete_y`: Integer indices for `x`/`y`\n#' coordinates, and a factor of the data labels (only applicable when names\n#' exist).\n#'\n#' It is recommended to use `.x`/`.y`, or `.discrete_x`/`.discrete_y` as the\n#' `x`/`y` mapping.\n#'\n#' If the data inherits from [`quad_layout()`]/[`ggheatmap()`], additional\n#' columns will be added:\n#'\n#' - `.extra_panel`: Provides the panel information for the column (left or\n#' right annotation) or row (top or bottom annotation).\n#' - `.extra_index`: The index information for the column (left or right\n#' annotation) or row (top or bottom annotation).\n#'\n#' @inheritSection align Discrete Axis Alignment\n#' @examples\n#' ggheatmap(matrix(rnorm(81), nrow = 9)) +\n#' anno_top() +\n#' ggalign() +\n#' geom_point(aes(y = value))\n#'\n#' ggheatmap(matrix(rnorm(81), nrow = 9)) +\n#' anno_top(size = 0.5) +\n#' align_dendro(k = 3L) +\n#' ggalign(data = NULL, size = 0.2) +\n#' geom_tile(aes(y = 1L, fill = .panel))\n#'\n#' @importFrom ggplot2 ggplot aes\n#' @importFrom rlang list2\n#' @export\nggalign <- function(data = waiver(), mapping = aes(), ..., size = NULL,\n no_axes = NULL, active = NULL) {\n if (inherits(data, \"uneval\")) {\n cli_abort(c(\n \"{.arg data} cannot be {.obj_type_friendly {data}}\",\n \"i\" = \"Have you misspelled the {.arg data} argument in {.fn ggalign}\"\n ))\n }\n no_axes <- no_axes %||%\n getOption(sprintf(\"%s.align_no_axes\", pkg_nm()), default = TRUE)\n assert_active(active)\n active <- update_active(active, new_active(use = TRUE))\n new_craftbox(\n AlignGg,\n input_data = allow_lambda(data),\n data_params = list2(...),\n plot = ggplot(mapping = mapping),\n size = size,\n schemes = default_schemes(data, th = theme_no_strip()),\n no_axes = no_axes, active = active\n )\n}\n\n#' @importFrom rlang inject\n#' @importFrom ggplot2 ggproto ggplot\nAlignGg <- ggproto(\"AlignGg\", Craftsman,\n interact_layout = function(self, layout) {\n layout_name <- self$layout_name\n input_data <- self$input_data\n object_name <- object_name(self)\n layout_data <- layout@data\n\n # inherit data from the layout\n if (is.function(input_data)) {\n if (is.null(layout_data)) {\n cli_abort(c(\n sprintf(\n \"{.arg data} in %s cannot be a function\",\n object_name\n ),\n i = sprintf(\"no data was found in %s\", layout_name)\n ))\n }\n data <- input_data(layout_data)\n } else if (is.waive(input_data)) {\n data <- layout_data %|w|% NULL\n # for data inherit from the layout, and the layout data is from\n # the quad-layout, we'll integrate the `extra_design`\n self$use_extra_design <- is_stack_layout(layout) &&\n isTRUE(layout@heatmap$quad_matrix)\n } else {\n data <- input_data\n }\n plot_data <- inject(\n fortify_data_frame(data, !!!self$data_params, call = self$call)\n )\n\n # for discrete design, # we need ensure the nobs is the same\n if (is_discrete_design(design <- layout@design)) {\n if (!is.null(data)) {\n if (is.null(layout_nobs <- design$nobs)) {\n layout_nobs <- NROW(data)\n if (layout_nobs == 0L) {\n cli_abort(\"{.arg data} cannot be empty\",\n call = self$call\n )\n }\n } else if (NROW(data) != layout_nobs) {\n cli_abort(sprintf(\n \"%s (nobs: %d) is not compatible with the %s (nobs: %d)\",\n object_name, NROW(data), layout_name, layout_nobs\n ))\n }\n design[\"nobs\"] <- list(layout_nobs)\n\n # we always add `.index` to align the observations\n # For matrix-like object\n if (!is.data.frame(data) &&\n vec_is(dim(data), integer(), size = 2L)) {\n plot_data$.index <- vec_rep(seq_len(NROW(data)), NCOL(data))\n } else {\n plot_data$.index <- seq_len(NROW(data))\n }\n layout@design <- design\n self$labels <- vec_names(data) %||% vec_names(layout_data)\n # always remove names, we'll add it in `build_plot()`\n plot_data$.names <- NULL\n } else {\n self$labels <- vec_names(layout_data)\n }\n self$add_mapping <- TRUE\n }\n self$data <- ggalign_data_restore(plot_data, layout_data)\n layout\n },\n setup_plot = function(self, plot) {\n direction <- self$direction\n ggadd_default(\n plot,\n mapping = if (isTRUE(self$add_mapping)) {\n switch_direction(\n direction,\n aes(y = .data$.y),\n aes(x = .data$.x)\n )\n },\n theme = if (is.null(self$data)) {\n # remove the title and text of axis vertically with the layout\n theme_no_axes(switch_direction(direction, \"x\", \"y\"))\n }\n ) + switch_direction(\n direction,\n ggplot2::labs(y = NULL),\n ggplot2::labs(x = NULL)\n )\n },\n\n #' @importFrom stats reorder\n build_plot = function(self, plot, design, extra_design = NULL,\n previous_design = NULL) {\n data <- self$data\n\n # if inherit from the parent layout\n if (isTRUE(self$use_extra_design) &&\n is_discrete_design(extra_design) &&\n !is.null(.subset2(extra_design, \"nobs\"))) {\n # if the data is inherit from the `quad_layout()`\n # the data must be a matrix\n extra_plot_data <- data_frame0(\n .extra_panel = .subset2(extra_design, \"panel\"),\n .extra_index = .subset2(extra_design, \"index\")\n )\n } else {\n extra_plot_data <- NULL\n }\n\n if (is_continuous_design(design)) {\n if (!is.null(data) && !is.null(extra_plot_data)) {\n data <- full_join(data, extra_plot_data,\n by.x = \".column_index\", by.y = \".extra_index\"\n )\n }\n return(gguse_data(plot, data))\n } else if (is.null(.subset2(design, \"nobs\"))) {\n cli_abort(c(\n sprintf(\n \"you must initialize %s before drawing %s\",\n self$layout_name, object_name(self)\n ),\n i = \"Or you should use {.fn ggfree}\"\n ), call = self$call)\n }\n direction <- self$direction\n axis <- to_coord_axis(direction)\n panel <- .subset2(design, \"panel\")\n index <- .subset2(design, \"index\")\n coord_name <- paste0(\".\", axis)\n plot_data <- data_frame0(\n .panel = panel,\n .index = index,\n # `data_frame0` will omit `NULL`\n .names = .subset(self$labels, index)\n )\n plot_data[[coord_name]] <- seq_along(index)\n if (!is.null(.subset2(plot_data, \".names\"))) {\n plot_data[[paste0(\".discrete_\", axis)]] <- reorder(\n .subset2(plot_data, \".names\"),\n .subset2(plot_data, coord_name),\n order = FALSE\n )\n }\n\n if (!is.null(extra_plot_data)) {\n plot_data <- cross_join(plot_data, extra_plot_data)\n if (!is.null(data)) {\n plot_data <- full_join(data, plot_data,\n by.x = c(\".column_index\", \".index\"),\n by.y = c(\".extra_index\", \".index\")\n )\n }\n } else if (!is.null(data)) {\n plot_data <- full_join(data, plot_data, by = \".index\")\n }\n gguse_data(plot, ggalign_data_restore(plot_data, data))\n },\n\n # let Craftsman to add schemes and theme acoordingly\n finish_plot = function(self, plot, schemes, theme) {\n direction <- self$direction\n # remove axis titles, text, ticks used for alignment\n if (isTRUE(self$no_axes)) {\n schemes$scheme_theme <- .subset2(schemes, \"scheme_theme\") +\n theme_no_axes(switch_direction(direction, \"y\", \"x\"))\n }\n plot <- plot_add_schemes(plot, schemes)\n if (is_horizontal(direction)) {\n theme <- theme(\n panel.spacing.y = calc_element(\"panel.spacing.y\", theme)\n )\n } else {\n theme <- theme(\n panel.spacing.x = calc_element(\"panel.spacing.x\", theme)\n )\n }\n plot <- plot + theme\n ggremove_margin(plot, direction) + theme_recycle()\n },\n summary = function(self, plot) {\n header <- ggproto_parent(Craftsman, self)$summary(plot)\n c(header, \" Add plot by Aligning discrete or continuous variable\")\n }\n)\n\n#' Create ggplot object with layout panel data\n#'\n#' @description\n#' `r lifecycle::badge(\"deprecated\")`\n#'\n#' This function was deprecated because we realised that it's a special case of\n#' the [`ggalign()`] function. Please use `ggalign(data = NULL)` instead.\n#' @export\n#' @keywords internal\nalign_panel <- function(...) {\n lifecycle::deprecate_stop(\"0.0.5\", \"align_panel()\", \"ggalign(data = NULL)\")\n}\n\n#' @export\n#' @rdname align_panel\nggpanel <- function(...) {\n lifecycle::deprecate_stop(\"0.0.5\", \"ggpanel()\", \"ggalign(data = NULL)\")\n}\n"], ["/ggalign/R/fortify-data-frame-dendrogram.R", "#' @inherit fortify_data_frame.default title description\n#'\n#' @param data A [`hclust`][stats::hclust] or a\n#' [`dendrogram`][stats::as.dendrogram] object.\n#' @param center A boolean value. if `TRUE`, nodes are plotted centered with\n#' respect to all leaves/tips in the branch. Otherwise (default), plot them in\n#' the middle of the direct child nodes.\n#' @param type A string indicates the plot type, `\"rectangle\"` or `\"triangle\"`.\n#' @param leaf_pos The x-coordinates of the leaf node. Must be the same length\n#' of the number of observations in `tree`.\n#' @param leaf_braches Branches of the leaf node. Must be the same length of the\n#' number of observations in `tree`. Usually come from [cutree][stats::cutree].\n#' @param reorder_branches A single boolean value, indicates whether reorder the\n#' provided `leaf_braches` based on the actual index.\n#' @param branch_gap A single numeric value indicates the gap between different\n#' branches.\n#' @param root A length one string or numeric indicates the root branch.\n#' @param priority A string of \"left\" or \"right\". if we draw from `right` to\n#' `left`, the left will override the right, so we take the `\"left\"` as the\n#' priority. If we draw from `left` to `right`, the right will override the\n#' left, so we take the `\"right\"` as priority. This is used by\n#' [`align_dendro()`] to provide support of facet operation in ggplot2.\n#' @param double A single logical value indicating whether horizontal lines\n#' should be doubled when segments span multiple branches. If `TRUE`, the\n#' horizontal lines will be repeated for each branch that the segment spans. If\n#' `FALSE`, only one horizontal line will be drawn. This is used by\n#' [`align_dendro()`] to provide support of facet operation in ggplot2.\n#' @inheritParams fortify_data_frame\n#' @return A `data frame` with the node coordinates:\n#' - `.panel`: Similar with `panel` column, but always give the correct\n#' branch for usage of the ggplot facet.\n#' - `.index`: the original index in the tree for the the node\n#' - `label`: node label text\n#' - `x` and `y`: x-axis and y-axis coordinates for the node\n#' - `branch`: which branch the node is. You can use this column to color\n#' different groups.\n#' - `panel`: which panel the node is, if we split the plot into panel\n#' using [facet_grid][ggplot2::facet_grid], this column will show\n#' which panel the node is from. Note: some nodes may\n#' fall outside panel (between two panels), so there are possible\n#' `NA` values in this column.\n#' - `leaf`: A logical value indicates whether the node is a leaf.\n#' @section ggalign attributes:\n#' `edge`: A `data frame` for edge coordinates:\n#' - `.panel`: Similar with `panel` column, but always give the correct\n#' branch for usage of the ggplot facet.\n#' - `x` and `y`: x-axis and y-axis coordinates for the start node of the edge.\n#' - `xend` and `yend`: the x-axis and y-axis coordinates of the terminal node\n#' for edge.\n#' - `branch`: which branch the edge is. You can use this column to color\n#' different groups.\n#' - `panel1` and `panel2`: The panel1 and panel2 columns have the same\n#' functionality as `panel`, but they are specifically for the `edge` data\n#' and correspond to both nodes of each edge.\n#' @examples\n#' fortify_data_frame(hclust(dist(USArrests), \"ave\"))\n#' @importFrom grid is.unit\n#' @importFrom stats order.dendrogram\n#' @importFrom rlang arg_match0\n#' @family fortify_data_frame\n#' @export\nfortify_data_frame.dendrogram <- function(data, ...,\n priority = \"right\",\n center = FALSE,\n type = \"rectangle\",\n leaf_pos = NULL,\n leaf_braches = NULL,\n reorder_branches = TRUE,\n branch_gap = NULL,\n root = NULL,\n double = TRUE,\n data_arg = NULL, call = NULL) {\n call <- call %||% current_call()\n data_arg <- data_arg %||% \"data\"\n rlang::check_dots_empty(call = call)\n assert_bool(center, call = call)\n assert_bool(reorder_branches, call = call)\n type <- arg_match0(type, c(\"rectangle\", \"triangle\"), error_call = call)\n priority <- arg_match0(priority, c(\"left\", \"right\"), error_call = call)\n N <- stats::nobs(data)\n rectangle <- type == \"rectangle\"\n if (is.null(leaf_pos)) {\n leaf_pos <- seq_len(N)\n } else if (length(leaf_pos) != N) {\n cli_abort(\n \"{.arg leaf_pos} must be of the same length of {.arg tree}\",\n call = call\n )\n }\n\n # if no branches provided, all branch will be regarded as the `root`\n if (is.null(leaf_braches)) {\n root <- root %||% \"root\"\n } else if (anyNA(leaf_braches)) {\n cli_abort(\"`NA` is not allowed in {.arg leaf_braches}\",\n call = call\n )\n } else if (length(leaf_braches) != N) {\n cli_abort(\n \"{.arg leaf_braches} must be of the same length of {.arg tree}\",\n call = call\n )\n } else if (is.character(leaf_braches)) {\n root <- root %||% \"root\"\n } else if (is.factor(leaf_braches)) {\n leaf_braches <- as.character(leaf_braches)\n root <- root %||% \"root\"\n } else if (is.numeric(leaf_braches)) {\n root <- root %||% (min(leaf_braches) - 1L)\n } else {\n cli_abort(\"{.arg leaf_braches} must be a character or numeric\",\n call = call\n )\n }\n\n if (!is.null(leaf_braches) && reorder_branches) {\n leaf_braches <- .subset(leaf_braches, order.dendrogram(data))\n }\n\n # check `branch_gap`\n if (is.numeric(branch_gap)) {\n if (!is_scalar(branch_gap)) {\n cli_abort(\"{.arg branch_gap} must be of length 1\",\n call = call\n )\n }\n } else if (is.null(branch_gap)) {\n branch_gap <- 0\n } else {\n cli_abort(\"{.arg branch_gap} must be numeric value.\",\n call = call\n )\n }\n\n # the root value shouldn't be the same of leaf branches.\n if (!is_scalar(root)) {\n cli_abort(\"{.arg root} must be of length 1\", call = call)\n } else if (anyNA(root)) {\n cli_abort(\"{.arg root} cannot be `NA`\", call = call)\n } else if (any(root == leaf_braches)) {\n cli_abort(\n \"{.arg root} cannot contain value in {.arg leaf_braches}\",\n call = call\n )\n }\n\n # initialize values\n i <- 0L # leaf index\n branch_levels <- NULL\n last_branch <- root\n total_gap <- 0\n dendrogram_data <- function(dend, from_root = TRUE) {\n if (stats::is.leaf(dend)) { # base version\n index <- as.integer(dend) # the column index of the original data\n y <- attr(dend, \"height\") %||% 0\n label <- attr(dend, \"label\") %||% NA\n i <<- i + 1L\n if (is.null(leaf_braches)) {\n branch <- root\n } else {\n branch <- .subset(leaf_braches, i)\n }\n\n x <- .subset(leaf_pos, i) + total_gap\n # for every new branch, we saved the branch for later use, in order\n # to order the branch levels, and we add a gap between two branch\n if (branch != last_branch) {\n branch_levels <<- c(branch_levels, branch)\n x <- x + branch_gap\n total_gap <<- total_gap + branch_gap\n }\n last_branch <<- branch\n\n node <- data_frame0(\n index = index, label = label,\n x = x, y = y, branch = branch,\n leaf = TRUE, panel = branch,\n ggpanel = branch\n )\n list(\n # current node\n node = node, edge = NULL,\n # current node information\n x = x, y = y,\n branch = branch,\n panel = branch,\n ggpanel = branch\n )\n } else if (inherits(dend, \"dendrogram\")) { # recursive version\n # the parent height -------------------------------------\n y <- attr(dend, \"height\")\n\n # for the children nodes ---------------------------------\n data <- list_transpose(\n lapply(dend, dendrogram_data, from_root = FALSE)\n )\n\n # node should be the direct children\n node <- vec_rbind(!!!.subset2(data, \"node\"))\n edge <- vec_rbind(!!!.subset2(data, \"edge\"))\n\n # all coordinate for direct children nodes -------------\n # following should be length 2\n direct_leaves_x <- unlist(\n .subset2(data, \"x\"),\n recursive = FALSE, use.names = FALSE\n )\n direct_leaves_y <- unlist(\n .subset2(data, \"y\"),\n recursive = FALSE, use.names = FALSE\n )\n direct_leaves_branch <- unlist(\n .subset2(data, \"branch\"),\n recursive = FALSE, use.names = FALSE\n )\n direct_leaves_panel <- unlist(\n .subset2(data, \"panel\"),\n recursive = FALSE, use.names = FALSE\n )\n direct_leaves_ggpanel <- unlist(\n .subset2(data, \"ggpanel\"),\n recursive = FALSE, use.names = FALSE\n )\n\n # prepare node data ------------------------------------\n\n # all x coordinate for children nodes --------------------\n # used if center is `TRUE`, we'll calculate the center position\n # among all children nodes\n leaves <- vec_slice(node, .subset2(node, \"leaf\")) # all leaves\n\n # we assign the `panel` for current branch node\n ranges <- split(\n .subset2(leaves, \"x\"),\n .subset2(leaves, \"panel\")\n )\n ranges <- ranges[\n order(vapply(ranges, min, numeric(1L), USE.NAMES = FALSE))\n ]\n full_panel <- names(ranges)\n\n # x coordinate for current branch: the midpoint\n if (center) {\n x <- sum(range(.subset2(leaves, \"x\"))) / 2L\n } else {\n x <- sum(direct_leaves_x) / 2L\n }\n if (is.null(leaf_braches)) { # no branches\n ggpanel <- panel <- branch <- root\n } else {\n # we assign the branch for current branch node\n branch <- unique(direct_leaves_branch)\n # if two children leaves are different, this branch should be\n # `root`, this is often used to color the segments\n if (length(branch) > 1L) branch <- root\n\n # we assign the `panel` for current branch node\n panel <- NA\n for (i in seq_along(ranges)) {\n if (x < min(.subset2(ranges, i))) {\n panel <- NA\n break\n } else if (x <= max(.subset2(ranges, i))) {\n panel <- .subset2(full_panel, i)\n break\n }\n }\n # if the node is between two panels, no panel\n # we choose the priority\n if (is.na(ggpanel <- panel)) {\n # it's not possible for an branch node live outside the\n # all panels - the left or right most. So `i` won't be 1 or\n # length(ranges). we don't need to check the argument\n ggpanel <- switch(priority,\n left = .subset(full_panel, i - 1L),\n right = .subset(full_panel, i)\n )\n }\n }\n\n # there is no node data in dendrogram root\n if (!from_root) {\n node <- vec_rbind(node, data_frame0(\n index = NA, label = NA,\n x = x, y = y, branch = branch, leaf = FALSE,\n panel = panel, ggpanel = ggpanel\n ))\n }\n\n # if it's the `rectangle`\n if (rectangle) {\n # 2 vertical lines\n vertical_lines <- data_frame0(\n x = direct_leaves_x,\n xend = direct_leaves_x,\n y = direct_leaves_y,\n yend = rep_len(y, 2L),\n branch = direct_leaves_branch,\n panel1 = direct_leaves_panel,\n panel2 = direct_leaves_panel,\n ggpanel = direct_leaves_ggpanel\n )\n # 2 horizontal lines\n # if the horizontal lines spanned multiple panels\n # we double the left line and the right line\n added_edge <- vec_rbind(\n vertical_lines,\n # left horizontal line\n make_horizontal(\n c(direct_leaves_x[1L], x),\n panels = c(direct_leaves_panel[1L], panel),\n ggpanels = c(direct_leaves_ggpanel[1L], ggpanel),\n y = y,\n branch = direct_leaves_branch[1L],\n ranges = ranges,\n full_panel = full_panel,\n double = double\n ),\n # right horizontal line\n make_horizontal(\n c(x, direct_leaves_x[2L]),\n panels = c(panel, direct_leaves_panel[2L]),\n ggpanels = c(ggpanel, direct_leaves_ggpanel[2L]),\n y = y,\n branch = direct_leaves_branch[2L],\n ranges = ranges,\n full_panel = full_panel,\n double = double\n )\n )\n } else {\n added_edge <- data_frame0(\n x = rep_len(x, 2L),\n xend = direct_leaves_x,\n y = rep_len(y, 2L),\n yend = direct_leaves_y,\n branch = direct_leaves_branch,\n panel1 = rep_len(panel, 2L),\n panel2 = direct_leaves_panel,\n ggpanel = rep_len(ggpanel, 2L)\n )\n }\n if (is.null(edge)) {\n edge <- added_edge\n } else {\n edge <- vec_rbind(edge, added_edge)\n }\n list(\n node = node, edge = edge,\n x = x, y = y, branch = branch,\n panel = panel, ggpanel = ggpanel\n )\n } else {\n cli_abort(\"Invalid {.cls dendrogram} provided in {.arg {data_arg}}\",\n call = call\n )\n }\n }\n ans <- dendrogram_data(data)\n node <- .subset2(ans, \"node\")\n edge <- .subset2(ans, \"edge\")\n\n # set factor levels for branch and panel ---------------\n panel_levels <- branch_levels\n branch_levels <- c(branch_levels, root)\n node$panel <- factor(.subset2(node, \"panel\"), panel_levels)\n node$branch <- factor(.subset2(node, \"branch\"), branch_levels)\n node$ggpanel <- factor(.subset2(node, \"ggpanel\"), panel_levels)\n if (!is.null(edge)) {\n edge$panel1 <- factor(.subset2(edge, \"panel1\"), panel_levels)\n edge$panel2 <- factor(.subset2(edge, \"panel2\"), panel_levels)\n edge$branch <- factor(.subset2(edge, \"branch\"), branch_levels)\n edge$ggpanel <- factor(.subset2(edge, \"ggpanel\"), panel_levels)\n }\n node <- rename(node, c(ggpanel = \".panel\", index = \".index\"))\n edge <- rename(edge, c(ggpanel = \".panel\"))\n ggalign_data_set(node, edge = edge)\n}\n\n#' @param ... Additional arguments passed to `dendrogram` method.\n#' @export\n#' @rdname fortify_data_frame.dendrogram\nfortify_data_frame.hclust <- function(data, ...) {\n fortify_data_frame.dendrogram(stats::as.dendrogram(data), ...)\n}\n\n#' @param ggpanels Won't be `NA`\n#' @noRd\nmake_horizontal <- function(x, panels, ggpanels, y, branch,\n ranges, full_panel = names(ranges),\n double = TRUE) {\n if (!isTRUE(double) || identical(ggpanels[1L], ggpanels[2L])) {\n # in the same panel\n data_frame0(\n x = x[1L],\n xend = x[2L],\n y = y,\n yend = y,\n branch = branch,\n panel1 = panels[1L],\n panel2 = panels[2L],\n ggpanel = ggpanels[1L]\n )\n } else {\n index <- match(ggpanels, full_panel)\n ending <- index[2L] # right index\n panel0 <- panels[1L]\n ggpanel0 <- ggpanels[1L]\n point0 <- x[1L] # the left point coordinate x\n out <- vector(\"list\", diff(index))\n right_index <- (index[1L] + 1L):ending\n for (i in seq_along(right_index)) {\n i1 <- .subset(right_index, i) # right index\n if (i1 == ending) {\n point1 <- x[2L]\n panel1 <- panels[2L]\n ggpanel1 <- ggpanels[2L]\n } else {\n point1 <- mean(range(.subset2(ranges, i1)))\n ggpanel1 <- panel1 <- .subset(full_panel, i1)\n }\n out[[i]] <- data_frame0(\n x = c(point0, point1),\n xend = c(point1, point0),\n y = y,\n yend = y,\n branch = branch,\n panel1 = c(panel0, panel1),\n panel2 = c(panel1, panel0),\n ggpanel = c(ggpanel0, ggpanel1)\n )\n point0 <- point1\n panel0 <- panel1\n ggpanel0 <- ggpanel1\n }\n vec_rbind(!!!out)\n }\n}\n"], ["/ggalign/R/tune.R", "#' Change the shape of the input object\n#'\n#' @param data An R object.\n#' @param shape Usually `NULL` or a string, specifying the new shape for the\n#' object. Refer to the detailed method for allowed values.\n#' @details\n#' In most cases, [`fortify_matrix()`] or [`fortify_data_frame()`] provide full\n#' support for transforming objects. However, some objects may require two\n#' completely different approaches to be fortified. The `tune` function acts as\n#' a helper to create a new class tailored for these objects.\n#' @eval rd_collect_family(\"tune\", \"`tune` method collections\")\n#' @export\ntune <- function(data, shape = NULL) UseMethod(\"tune\")\n\n#' @inherit tune title\n#' @description\n#' - `new_tune`: Creates a new object by wrapping it in a scalar list with\n#' the specified attributes and class.\n#' - `tune_data`: Retrieves the original input data.\n#'\n#' @param x An R object.\n#' @param ... Additional attributes passed to [`structure()`].\n#' @param class A character vector specifying the class name to be added.\n#' @export\nnew_tune <- function(x, ..., class = character()) {\n structure(list(x), ..., class = c(class, \"ggalign_tune\"))\n}\n\n#' @export\n#' @rdname new_tune\ntune_data <- function(x) .subset2(x, 1L)\n\n#' @export\nprint.ggalign_tune <- function(x, ...) {\n print(tune_data(x))\n invisible(x)\n}\n\n#' @export\nfortify_matrix.ggalign_tune <- function(data, ...) {\n cli_abort(\"No {.fn fortify_matrix} method for {.obj_type_friendly {data}}\")\n}\n\n#' @export\nfortify_data_frame.ggalign_tune <- function(data, ...) {\n cli_abort(\n \"No {.fn fortify_data_frame} method for {.obj_type_friendly {data}}\"\n )\n}\n"], ["/ggalign/R/layout-quad-upset.R", "#' Create an UpSet plot\n#'\n#' @description\n#' `r lifecycle::badge('experimental')`\n#'\n#' `ggupset` is a specialized version of [`quad_discrete()`], which simplifies\n#' the creation of Upset plot.\n#'\n#' @param data Data used to create the UpSet plot. [`fortify_matrix()`] will be\n#' used to convert the data to a matrix. Currently, only\n#' [`fortify_matrix.list_upset`] and [`fortify_matrix.matrix_upset`] are\n#' suitable for creating an UpSet plot.\n#' @param ... Additional arguments passed to [`fortify_matrix()`].\n#' @inheritParams quad_layout\n#' @param direction A string indicating the direction of the UpSet plot,\n#' `\"h\"`(`horizontal`) or `\"v\"`(`vertical`). In a vertical UpSet plot, the\n#' columns of the matrix correspond to the sets, and the rows correspond to the\n#' intersections. By default, the horizontal UpSet plot is used, where the rows\n#' of the matrix correspond to the sets and the columns correspond to the\n#' intersections.\n#' @param point A list of parameters passed to\n#' [`geom_point()`][ggplot2::geom_point()].\n#' @param line A list of parameters passed to\n#' [`geom_line()`][ggplot2::geom_line()].\n#' @param rect A list of parameters passed to\n#' [`geom_rect()`][ggplot2::geom_rect()].\n#'\n#' @inheritSection heatmap_layout ggplot2 specification\n#' @examples\n#' set.seed(123)\n#' lt <- list(\n#' a = sample(letters, 5),\n#' b = sample(letters, 10),\n#' c = sample(letters, 15)\n#' )\n#' ggupset(tune(lt)) +\n#' scale_fill_manual(values = c(\"#F0F0F0\", \"white\"), guide = \"none\") +\n#' scale_color_manual(values = c(\"grey\", \"black\"), guide = \"none\") +\n#' anno_top() +\n#' ggalign(data = function(d) ggalign_attr(d, \"intersection_sizes\")) +\n#' ggplot2::geom_bar(aes(y = .data$value), stat = \"identity\") +\n#' anno_right() +\n#' ggalign(data = function(d) ggalign_attr(d, \"set_sizes\")) +\n#' ggplot2::geom_bar(aes(x = .data$value),\n#' stat = \"identity\",\n#' orientation = \"y\"\n#' )\n#' @importFrom ggplot2 aes\n#' @export\nggupset <- function(data = NULL, mapping = aes(),\n ...,\n direction = \"h\",\n point = NULL, line = NULL, rect = NULL,\n width = NA, height = NA,\n theme = NULL, active = NULL) {\n UseMethod(\"ggupset\")\n}\n\n# Don't allow inherit from the parent layout, since data for upset plot is\n# usually different with others\n#' @export\nggupset.NULL <- function(data, ...) {\n cli_abort(\"{.arg data} must be provided to create upset plot\")\n}\n\n#' @export\nggupset.waiver <- ggupset.NULL\n\n#' @importFrom ggplot2 aes\n#' @export\nggupset.default <- function(data = NULL, mapping = aes(),\n ...,\n direction = \"h\",\n point = NULL, line = NULL, rect = NULL,\n width = NA, height = NA,\n theme = NULL, active = NULL) {\n direction <- check_direction(direction)\n # we need a matrix to melted into long formated data frame\n data <- fortify_matrix(data = data, ...)\n if (is_vertical(direction)) data <- ggalign_data_restore(t(data), data)\n ans <- new_quad_layout(\n name = \"ggupset\",\n data = data,\n mapping = mapping,\n theme = theme,\n active = active\n )\n ans@plot <- ggadd_default(ans@plot, mapping = aes(.data$.x, .data$.y)) +\n ggplot2::labs(x = NULL, y = NULL) +\n upset_rect(direction, rect) +\n upset_point(point) +\n upset_line(direction, line)\n ans\n}\n\nmerge_mapping <- function(x, y) {\n if (is.null(x)) {\n return(y)\n }\n for (i in names(y)) {\n x[[i]] <- .subset2(y, i)\n }\n x\n}\n\nmerge_data_fn <- function(plot_data, user_data) {\n if (is.null(user_data) || is.waive(user_data)) {\n plot_data\n } else if (is.function(user_data <- allow_lambda(user_data))) {\n force(plot_data)\n function(data) user_data(plot_data(data))\n } else {\n user_data\n }\n}\n\nupset_rect <- function(direction, rect) {\n if (is_horizontal(direction)) {\n rect$mapping <- merge_mapping(rect$mapping, aes(\n ymin = .data$.ymin, ymax = .data$.ymax, fill = .data$rect_group\n ))\n rect$data <- merge_data_fn(function(data) {\n column <- c(\n \".y\", \".panel_x\", \".panel_y\",\n \".row_index\", \".row_names\", \".discrete_y\"\n )\n o <- vec_unique(data[vec_set_intersect(column, names(data))])\n o$rect_group <- (.subset2(o, \".y\") %% 2L) == 0L\n o$.ymin <- o$.y - 0.5\n o$.ymax <- o$.y + 0.5\n o\n }, rect$data)\n inject(ggplot2::geom_rect(!!!rect,\n xmin = -Inf, xmax = Inf, inherit.aes = FALSE\n ))\n } else {\n rect$mapping <- merge_mapping(rect$mapping, aes(\n xmin = .data$.xmin, xmax = .data$.xmax,\n fill = .data$rect_group\n ))\n rect$data <- merge_data_fn(function(data) {\n column <- c(\n \".x\", \".panel_x\", \".panel_y\",\n \".column_index\", \".column_names\", \".discrete_x\"\n )\n o <- vec_unique(data[vec_set_intersect(column, names(data))])\n o$rect_group <- (.subset2(o, \".x\") %% 2L) == 0L\n o$.xmin <- o$.x - 0.5\n o$.xmax <- o$.x + 0.5\n o\n }, rect$data)\n inject(ggplot2::geom_rect(!!!rect,\n ymin = -Inf, ymax = Inf, inherit.aes = FALSE\n ))\n }\n}\n\nupset_point <- function(point) {\n point$mapping <- merge_mapping(point$mapping, aes(\n x = .data$.x, y = .data$.y, color = .data$point_group\n ))\n point$data <- merge_data_fn(function(data) {\n data$point_group <- .subset2(data, \"value\")\n data\n }, point$data)\n inject(ggplot2::geom_point(!!!point, inherit.aes = FALSE))\n}\n\nupset_line <- function(direction, line) {\n line$mapping <- merge_mapping(line$mapping, switch_direction(\n direction,\n aes(.data$.x, .data$.y, group = paste(.data$.panel_x, .data$.x)),\n aes(.data$.x, .data$.y, group = paste(.data$.panel_y, .data$.y))\n ))\n line$data <- merge_data_fn(function(data) {\n if (is_horizontal(direction)) {\n dlist <- vec_split(data, data[c(\".panel_x\", \".x\")])\n dlist <- lapply(.subset2(dlist, \"val\"), function(d) {\n o <- vec_slice(d, .subset2(d, \"value\"))\n if (vec_size(o) < 2L) {\n return(NULL)\n }\n vec_slice(o, c(\n which.min(.subset2(o, \".y\")),\n which.max(.subset2(o, \".y\"))\n ))\n })\n vec_rbind(!!!dlist)\n } else {\n dlist <- vec_split(data, data[c(\".panel_y\", \".y\")])\n dlist <- lapply(.subset2(dlist, \"val\"), function(d) {\n o <- vec_slice(d, .subset2(d, \"value\"))\n if (vec_size(o) < 2L) {\n return(NULL)\n }\n vec_slice(o, c(\n which.min(.subset2(o, \".x\")),\n which.max(.subset2(o, \".x\"))\n ))\n })\n vec_rbind(!!!dlist)\n }\n }, line$data)\n inject(ggplot2::geom_line(!!!line, inherit.aes = FALSE))\n}\n"], ["/ggalign/R/craft-align-hclust.R", "#' Reorder or Group observations based on hierarchical clustering\n#'\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' This function aligns observations within the layout according to a\n#' hierarchical clustering tree, enabling reordering or grouping of elements\n#' based on clustering results.\n#'\n#' @param data A matrix-like object. By default, it inherits from the layout\n#' `matrix`.\n#' @inheritParams align\n#' @inheritParams hclust2\n#' @param reorder_dendrogram A single boolean value indicating whether to\n#' reorder the dendrogram based on the means. Alternatively, you can provide a\n#' custom function that accepts an [`hclust`][stats::hclust] object and the data\n#' used to generate the tree, returning either an [`hclust`][stats::hclust] or\n#' [`dendrogram`][stats::as.dendrogram] object. Default is `FALSE`.\n#' @param reorder_group A single boolean value, indicates whether we should do\n#' Hierarchical Clustering between groups, only used when previous groups have\n#' been established. Default: `FALSE`.\n#' @param k An integer scalar indicates the desired number of groups.\n#' @param h A numeric scalar indicates heights where the tree should be cut.\n#' @param cutree A function used to cut the [`hclust`][stats::hclust] tree. It\n#' should accept four arguments: the [`hclust`][stats::hclust] tree object,\n#' `distance` (only applicable when `method` is a string or a function for\n#' performing hierarchical clustering), `k` (the number of clusters), and `h`\n#' (the height at which to cut the tree). By default,\n#' [`cutree()`][stats::cutree()] is used.\n#' @inheritSection align Discrete Axis Alignment\n#' @seealso [`hclust2()`]\n#' @examples\n#' # align_hclust won't add a dendrogram\n#' ggheatmap(matrix(rnorm(81), nrow = 9)) +\n#' anno_top() +\n#' align_hclust(k = 3L)\n#' @export\nalign_hclust <- function(distance = \"euclidean\",\n method = \"complete\",\n use_missing = \"pairwise.complete.obs\",\n reorder_dendrogram = FALSE,\n reorder_group = FALSE,\n k = NULL, h = NULL, cutree = NULL,\n data = NULL, active = NULL) {\n assert_active(active)\n active <- update_active(active, new_active(use = FALSE))\n .align_hclust(\n align = AlignHclust,\n distance = distance,\n method = method,\n use_missing = use_missing,\n reorder_dendrogram = reorder_dendrogram,\n reorder_group = reorder_group,\n k = k, h = h, cutree = cutree, data = data, active = active\n )\n}\n\n.align_hclust <- function(align, ..., plot = NULL,\n distance = \"euclidean\",\n method = \"complete\",\n use_missing = \"pairwise.complete.obs\",\n reorder_dendrogram = FALSE,\n reorder_group = FALSE,\n k = NULL, h = NULL, cutree = NULL,\n data = NULL, schemes = NULL, active = NULL,\n call = caller_call()) {\n reorder_dendrogram <- allow_lambda(reorder_dendrogram)\n if (!rlang::is_bool(reorder_dendrogram) &&\n !is.null(reorder_dendrogram) &&\n !is.function(reorder_dendrogram)) {\n cli_abort(\n \"{.arg reorder_dendrogram} must be a single boolean value or a function\",\n call = call\n )\n }\n assert_number_whole(k, allow_null = TRUE, call = call)\n assert_number_decimal(h, allow_null = TRUE, call = call)\n assert_bool(reorder_group, call = call)\n cutree <- allow_lambda(cutree)\n assert_(cutree, is.function, \"a function\", allow_null = TRUE, call = call)\n if (inherits(method, \"hclust\")) {\n if (vec_size(.subset2(method, \"order\")) == 0L) {\n cli_abort(\"{.cls hclust} defined in {.arg method} cannot be empty\",\n call = call\n )\n }\n } else if (inherits(method, \"dendrogram\")) {\n if (stats::nobs(method) == 0L) {\n cli_abort(\n \"{.cls dendrogram} defined in {.arg method} cannot be empty\",\n call = call\n )\n }\n }\n\n if (isTRUE(reorder_dendrogram)) {\n reorder_dendrogram <- function(tree, data) {\n if (!inherits(tree, \"dendrogram\")) {\n tree <- stats::as.dendrogram(tree)\n }\n reorder(x = tree, wts = rowMeans(data), agglo.FUN = mean)\n }\n } else if (is.function(reorder_dendrogram)) {\n user_reorder <- reorder_dendrogram\n reorder_dendrogram <- function(tree, data) {\n # we ensure, what we input for user is a `hclust` object.\n if (!inherits(tree, \"hclust\")) tree <- stats::as.hclust(tree)\n ans <- user_reorder(tree, data)\n if (!inherits(ans, \"hclust\") &&\n !inherits(ans, \"dendrogram\")) {\n cli_abort(\n \"{.fn reorder_dendrogram} must return a {.cls hclust} or {.cls dendrogram} object\",\n call = call\n )\n }\n ans\n }\n }\n\n align(\n align = align,\n distance = distance, method = method,\n use_missing = use_missing,\n reorder_dendrogram = reorder_dendrogram,\n reorder_group = reorder_group,\n k = k, h = h, cutree = cutree,\n active = active,\n ..., # additional fields to be added, used by align_dendro\n schemes = schemes %||% default_schemes(),\n data = data,\n plot = plot,\n call = call\n )\n}\n\n#' @importFrom ggplot2 ggproto aes\nAlignHclust <- ggproto(\"AlignHclust\", CraftAlign,\n interact_layout = function(self, layout) {\n if (inherits(self$method, \"hclust\") ||\n inherits(self$method, \"dendrogram\")) {\n layout <- ggproto_parent(CraftAlign, self)$interact_layout(layout)\n if (inherits(self$method, \"hclust\")) {\n nobs <- vec_size(.subset2(self$method, \"order\"))\n } else {\n nobs <- stats::nobs(self$method)\n }\n\n if (is.null(layout_nobs <- .subset2(layout@design, \"nobs\"))) {\n layout@design[\"nobs\"] <- list(nobs)\n } else {\n assert_mismatch_nobs(self, layout_nobs, nobs, arg = \"method\")\n }\n } else {\n layout <- ggproto_parent(AlignOrder2, self)$interact_layout(layout)\n }\n\n # initialize the internal parameters\n self$multiple_tree <- FALSE\n self$height <- NULL\n self$panel <- NULL\n layout\n },\n compute = function(self, panel, index) {\n if (!is.null(self$data) && vec_size(self$data) < 2L) {\n cli_abort(c(\n \"Cannot do Hierarchical Clustering\",\n i = \"must have >= 2 observations to cluster\"\n ), call = self$call)\n }\n\n # if the old panel exist, we do sub-clustering\n if (!is.null(panel) && is.null(self$k) && is.null(self$h) &&\n is.null(self$cutree)) {\n # in this way, we prevent sub-clustering\n if (inherits(self$method, \"hclust\") ||\n inherits(self$method, \"dendrogram\")) {\n cli_abort(\n \"{.arg method} cannot be a {.cls hclust} or {.cls dendrogram} when previous layout panel groups exist\",\n call = self$call\n )\n }\n children <- vector(\"list\", nlevels(panel))\n names(children) <- levels(panel)\n labels <- vec_names(self$data)\n\n # we do clustering within each group ---------------\n for (g in levels(panel)) {\n idx <- which(panel == g)\n gdata <- vec_slice(self$data, idx)\n if (vec_size(gdata) == 1L) {\n children[[g]] <- tree_one_node(idx, .subset(labels, idx))\n } else {\n child <- stats::as.dendrogram(hclust2(\n gdata,\n distance = self$distance,\n method = self$method,\n use_missing = self$use_missing\n ))\n # we restore the actual index of the original matrix\n child <- stats::dendrapply(child, function(x) {\n if (stats::is.leaf(x)) {\n ans <- .subset(idx, x)\n attributes(ans) <- attributes(x)\n ans\n } else {\n x\n }\n })\n if (is.function(self$reorder_dendrogram)) {\n child <- self$reorder_dendrogram(child, gdata)\n }\n children[[g]] <- child\n }\n }\n return(children) # can be a list of `dendrogram` or `hclust` or mix\n }\n hclust2(self$data, self$distance, self$method, self$use_missing)\n },\n #' @importFrom stats order.dendrogram\n align = function(self, panel, index) {\n statistics <- self$statistics\n if (!is.null(panel) && is.null(self$k) && is.null(self$h) &&\n is.null(self$cutree)) {\n # reordering the dendrogram ------------------------\n if (nlevels(panel) > 1L && self$reorder_group) {\n parent_levels <- levels(panel)\n parent_data <- t(sapply(parent_levels, function(g) {\n colMeans(vec_slice(self$data, panel == g), na.rm = TRUE)\n }))\n rownames(parent_data) <- parent_levels\n parent <- hclust2(\n parent_data,\n distance = self$distance,\n method = self$method,\n use_missing = self$use_missing\n )\n # reorder parent based on the parent tree\n if (is.function(self$reorder_dendrogram)) {\n parent <- self$reorder_dendrogram(parent, parent_data)\n }\n # we always ensure the parent is a dendrogram\n # since we'll call `merge_dendrogram()` which requires a\n # dendrogram\n parent <- stats::as.dendrogram(parent)\n panel <- factor(panel, parent_levels[order.dendrogram(parent)])\n # we don't cutree, so we won't draw the height line\n # self$draw_params$height <- attr(ans, \"cutoff_height\")\n } else {\n parent <- NULL\n }\n\n # merge children tree ------------------------------\n if (nlevels(panel) == 1L) {\n statistics <- .subset2(statistics, 1L)\n } else if (isTRUE(self$merge_dendro)) {\n # we have a function named merge_dendrogram(), so we use\n # `merge_dendro` as the argument name\n # `merge_dendrogram` will follow the order of the parent\n statistics <- lapply(statistics, stats::as.dendrogram)\n statistics <- merge_dendrogram(parent, statistics)\n } else {\n # if no parent tree, and we havn't merged the tree\n # we must manually reorder the dendrogram\n if (!is.null(parent)) {\n statistics <- .subset(statistics, levels(panel))\n }\n self$multiple_tree <- TRUE\n }\n } else {\n # hclust2() will attach the distance used\n distance <- attr(statistics, \"distance\")\n if (is.function(self$reorder_dendrogram)) {\n statistics <- self$reorder_dendrogram(statistics, self$data)\n }\n if (!is.null(self$k) || !is.null(self$h) || !is.null(self$cutree)) {\n if (is.null(cutree <- self$cutree)) {\n cutree <- function(tree, dist, k, h) {\n if (!is.null(k)) {\n stats::cutree(tree, k = k)\n } else {\n stats::cutree(tree, h = h)\n }\n }\n }\n # we need `hclust` object to cutree\n statistics <- stats::as.hclust(statistics)\n panel <- cutree(statistics, distance, self$k, self$h)\n # For `cutree`, we always respect the height user specified\n # For user defined function, we always calculate\n # height from the number of `panels`\n if (isTRUE(self$plot_cut_height)) {\n self$height <- self$h %||% cutree_k_to_h(\n statistics, vec_unique_count(panel)\n )\n }\n }\n }\n # save the modified `statistics`\n self$statistics <- statistics\n if (self$multiple_tree) {\n index <- unlist(lapply(statistics, order2), FALSE, FALSE)\n } else {\n index <- order2(statistics)\n }\n # reorder panel factor levels to following the dendrogram order\n if (!is.null(panel)) {\n panel <- factor(panel, unique(panel[index]))\n # save panel information, in case of user change it\n self$panel <- panel\n }\n list(panel, index)\n },\n summary_align = function(self, ...) {\n c(TRUE, !is.null(self$k) || !is.null(self$h) || !is.null(self$cutree))\n }\n)\n\n#' Generate Tree Structures with Hierarchical Clustering\n#'\n#' @param matrix A numeric matrix, or data frame.\n#' @param distance A string of distance measure to be used. This must be one of\n#' `\"euclidean\"`, `\"maximum\"`, `\"manhattan\"`, `\"canberra\"`, `\"binary\"` or\n#' `\"minkowski\"`. Correlation coefficient can be also used, including\n#' `\"pearson\"`, `\"spearman\"` or `\"kendall\"`. In this way, `1 - cor` will be used\n#' as the distance. In addition, you can also provide a [`dist`][stats::dist]\n#' object directly or a function return a [`dist`][stats::dist] object. Use\n#' `NULL`, if you don't want to calculate the distance.\n#' @param method A string of the agglomeration method to be used. This should be\n#' (an unambiguous abbreviation of) one of `\"ward.D\"`, `\"ward.D2\"`, `\"single\"`,\n#' `\"complete\"`, `\"average\"` (= UPGMA), `\"mcquitty\"` (= WPGMA), `\"median\"` (=\n#' WPGMC) or `\"centroid\"` (= UPGMC). You can also provide a function which\n#' accepts the calculated distance (or the input matrix if `distance` is `NULL`)\n#' and returns a [`hclust`][stats::hclust] object. Alternative, you can supply\n#' an object which can be coerced to [`hclust`][stats::hclust].\n#' @param use_missing An optional character string giving a method for computing\n#' covariances in the presence of missing values. This must be (an abbreviation\n#' of) one of the strings `\"everything\"`, `\"all.obs\"`, `\"complete.obs\"`,\n#' `\"na.or.complete\"`, or `\"pairwise.complete.obs\"`. Only used when `distance`\n#' is a correlation coefficient string.\n#' @seealso\n#' - [cor()][stats::cor]\n#' - [dist()][stats::dist]\n#' - [hclust()][stats::hclust]\n#' @examples\n#' hclust2(dist(USArrests), method = \"ward.D\")\n#' @return A [hclust][stats::hclust] object.\n#' @importFrom rlang is_string try_fetch\n#' @export\nhclust2 <- function(matrix, distance = \"euclidean\", method = \"complete\",\n use_missing = \"pairwise.complete.obs\") {\n method <- allow_lambda(method)\n if (!is_string(method) && !is.function(method)) {\n ans <- try_fetch(\n stats::as.hclust(method),\n error = function(cnd) {\n cli_abort(paste(\n \"{.arg method} can only be a {.cls string},\",\n \"{.cls function} or an object which can be coerced to\",\n \"{.cls hclust}.\"\n ), parent = cnd)\n }\n )\n return(ans)\n }\n if (is.null(distance)) {\n d <- matrix\n } else {\n d <- make_dist(matrix, distance, use_missing)\n }\n if (is_string(method)) {\n ans <- stats::hclust(d, method = method)\n } else if (is.function(method)) {\n ans <- method(d)\n ans <- try_fetch(\n stats::as.hclust(ans),\n error = function(cnd) {\n cli_abort(paste(\n \"{.arg method} must return an object which\",\n \"can be coerced to {.cls hclust}\"\n ), parent = cnd)\n }\n )\n }\n if (!is.null(distance)) attr(ans, \"distance\") <- d\n ans\n}\n\n#' @importFrom rlang arg_match0\nmake_dist <- function(matrix, distance, use_missing,\n arg = caller_arg(distance), call = caller_call()) {\n distance <- allow_lambda(distance)\n if (is_string(distance)) {\n distance <- arg_match0(distance, c(\n \"euclidean\", \"maximum\", \"manhattan\", \"canberra\",\n \"binary\", \"minkowski\", \"pearson\", \"spearman\", \"kendall\"\n ), arg_nm = arg, error_call = call)\n d <- switch(distance,\n euclidean = ,\n maximum = ,\n manhattan = ,\n canberra = ,\n binary = ,\n minkowski = stats::dist(matrix, method = distance),\n pearson = ,\n spearman = ,\n kendall = stats::as.dist(\n 1 - stats::cor(t(matrix), use = use_missing, method = distance)\n ),\n cli_abort(\"Unsupported {.arg {arg}} specified\", call = call)\n )\n } else if (is.function(distance)) {\n if (!inherits(d <- distance(matrix), \"dist\")) {\n cli_abort(\n \"{.arg {arg}} must return a {.cls dist} object\",\n call = call\n )\n }\n } else if (inherits(distance, \"dist\")) {\n d <- distance\n } else {\n cli_abort(paste(\n \"{.arg {arg}} can only be a {.cls string}, {.cls dist}\",\n \"object, or a {.cls function} return {.cls dist}\"\n ), call = call)\n }\n d\n}\n\ncutree_k_to_h <- function(tree, k) {\n if (is.null(n1 <- nrow(tree$merge)) || n1 < 1) {\n cli_abort(\"invalid {.arg tree} ({.field merge} component)\")\n }\n n <- n1 + 1\n if (is.unsorted(tree$height)) {\n cli_abort(\n \"the 'height' component of 'tree' is not sorted (increasingly)\"\n )\n }\n mean(tree$height[c(n - k, n - k + 1L)])\n}\n"], ["/ggalign/R/attributes.R", "#' Get Data from the Attribute Attached by ggalign\n#'\n#' @description\n#' `ggalign_attr` retrieves supplementary information stored as attributes\n#' during the layout rendering process. These attributes—typically added during\n#' data transformation by functions such as [`fortify_matrix()`] or\n#' [`fortify_data_frame()`]—may contain filtered data, auxiliary metadata, or\n#' other context essential for downstream operations.\n#'\n#' Factor level information, stored as a separate attribute, can be accessed via\n#' `ggalign_lvls`.\n#'\n#' @details\n#' Attributes attached to the data are especially useful when the input data is\n#' transformed in ways that limit access to the complete dataset. For example,\n#' [`fortify_matrix.MAF()`] might filter mutation data while adding attributes\n#' that retain important context, such as the total number of observations, for\n#' detailed or aggregated analyses. Additionally, it stores the levels of\n#' `Variant_Classification` for further usage.\n#'\n#' @param x Data used, typically inherited from the layout `r rd_layout()`.\n#' @param field A string specifying the particular data to retrieve from the\n#' attached attribute. If `NULL`, the entire attached attribute list will be\n#' returned.\n#' @param check A boolean indicating whether to check if the `field` exists. If\n#' `TRUE`, an error will be raised if the specified `field` does not exist.\n#' @return\n#' - `ggalign_attr`: The specified data from the attached supplementary data or\n#' `NULL` if it is unavailable.\n#' - `ggalign_lvls`: The attached supplementary levels or `NULL` if it is\n#' unavailable.\n#'\n#' @export\nggalign_attr <- function(x, field = NULL, check = TRUE) {\n assert_string(field, allow_empty = FALSE, allow_null = TRUE)\n if (is.null(x <- ggalign_attr_get(x)) || is.null(field)) {\n return(x)\n }\n if (isTRUE(check) && !rlang::has_name(x, field)) {\n cli_abort(\"Cannot find {field} in {.arg x}\")\n }\n .subset2(x, field)\n}\n\n#' @export\n#' @rdname ggalign_attr\nggalign_lvls <- function(x) ggalign_lvls_get(x)\n\n#' Attach supplementary data and levels for ggalign\n#'\n#' @param .data Input data for the layout.\n#' @param ... <[dyn-dots][rlang::dyn-dots]> A list of data to be attached.\n#' @param .lvls A character vector representing the attached levels.\n#' @note Used by developers in [`fortify_matrix()`], [`fortify_data_frame()`],\n#' and other related methods.\n#' @seealso [`ggalign_attr()`]/[`ggalign_lvls()`]\n#' @importFrom rlang list2\n#' @export\nggalign_data_set <- function(.data, ..., .lvls = NULL) {\n if (...length() > 0L) {\n .data <- ggalign_attr_set(.data, list2(...))\n }\n if (!is.null(.lvls)) {\n .data <- ggalign_lvls_set(.data, .lvls)\n }\n # to prevent the print of attributes\n if (!is.null(ggalign_attr_get(.data)) ||\n !is.null(ggalign_lvls_get(.data))) {\n .data <- add_class(.data, \"ggalign_data\")\n }\n .data\n}\n\n#' @export\nprint.ggalign_data <- function(x, ...) {\n print(\n remove_class(\n ggalign_lvls_remove(ggalign_attr_remove(x)),\n \"ggalign_data\"\n )\n )\n invisible(x)\n}\n\nggalign_attr_set <- function(x, values) {\n attr(x, \".__ggalign_attr__\") <- values\n x\n}\n\nggalign_attr_get <- function(x) attr(x, \".__ggalign_attr__\", exact = TRUE)\n\nggalign_attr_remove <- function(x) ggalign_attr_set(x, NULL)\n\nggalign_lvls_set <- function(x, lvls) {\n attr(x, \".__ggalign_levels__\") <- lvls\n x\n}\n\nggalign_lvls_get <- function(x) attr(x, \".__ggalign_levels__\", exact = TRUE)\n\nggalign_lvls_remove <- function(x) ggalign_lvls_set(x, NULL)\n\n# we keep a special attribute across all data\n# this is used to pass additional annotation informations\nggalign_data_restore <- function(data, original) {\n if (is.null(data) || is.waive(data)) return(data) # styler: off\n if (is.null(ggalign_attr_get(data)) && # no attached attribute\n # the original has attached attribute\n !is.null(value <- ggalign_attr_get(original))) {\n data <- ggalign_attr_set(data, value)\n }\n\n if (is.null(ggalign_lvls_get(data)) && # no attached levels\n # the original has attached levels\n !is.null(value <- ggalign_lvls_get(original))) {\n data <- ggalign_lvls_set(data, value)\n }\n # to prevent the print of attributes\n if (!is.null(ggalign_attr_get(data)) ||\n !is.null(ggalign_lvls_get(data))) {\n data <- add_class(data, \"ggalign_data\")\n }\n data\n}\n"], ["/ggalign/R/craft-cross-.R", "cross <- function(cross = NULL, data = waiver(),\n data_params = list(), ...,\n inherit_index = NULL,\n inherit_panel = NULL,\n inherit_nobs = NULL,\n plot = NULL, active = NULL, size = NULL, schemes = NULL,\n data_arg = caller_arg(data),\n call = caller_call()) {\n if (override_call(call)) {\n call <- current_call()\n }\n new_craftbox(\n craftsman = cross %||% CraftCross,\n data = allow_lambda(data), data_params = data_params,\n ...,\n inherit_nobs = inherit_nobs,\n inherit_panel = inherit_panel,\n inherit_index = inherit_index,\n plot = plot, active = active, size = size, schemes = schemes,\n data_arg = data_arg, call = call\n )\n}\n\n#' @importFrom ggplot2 ggproto ggproto_parent\n#' @include craftbox-.R\nCraftCross <- ggproto(\n \"CraftCross\", Craftsman,\n free_facet = TRUE,\n free_limits = TRUE,\n data_params = NULL,\n inherit_nobs = NULL,\n inherit_panel = NULL,\n inherit_index = NULL,\n interact_layout = function(self, layout) {\n # 1. check layout is `*_cross()`\n # 2. add `cross_points`\n # 3. add `odesign`\n # 4. define `labels`, we'll rename the `labels` to `labels0`\n layout <- ggproto_parent(CrossGg, self)$interact_layout(layout)\n\n # will define `labels0`\n self$labels0 <- self$labels\n\n # check the previous (between two `break_points`) define has been\n # initialized\n if (length(layout@break_points) &&\n is.null(.subset2(layout@design, \"nobs\"))) {\n cli_abort(sprintf(\n \"layout {.field nobs} for %s must be initialized before adding %s\",\n self$layout_name, object_name(self)\n ))\n }\n\n # setup data\n layout_data <- layout@data\n design <- layout@design\n\n if (is.waive(input_data <- self$data)) { # inherit from the layout\n data <- layout_data\n # `data` is NULL, `inherit_nobs` can be `TRUE` or `FALSE`, we by\n # default regard `inherit_nobs` as `TRUE`\n if (is.null(data) && isFALSE(self$inherit_nobs)) {\n design[\"nobs\"] <- list(NULL)\n }\n\n # `data` is not `NULL`, the `nobs` will always be the same with\n # previous design, nothing to do\n } else {\n if (is.function(input_data)) {\n if (is.null(layout_data)) {\n cli_abort(c(\n sprintf(\n \"{.arg data} in %s cannot be a function\",\n object_name(self)\n ),\n i = sprintf(\"no data was found in %s\", self$layout_name)\n ))\n }\n data <- input_data(layout_data)\n } else {\n data <- input_data\n }\n data <- inject(\n fortify_matrix(\n data, !!!self$data_params,\n data_arg = self$data_arg,\n call = self$call\n )\n ) %|w|% NULL\n if (isTRUE(self$inherit_nobs)) { # we require inherit nobs\n # we check if the data match original data dimention\n if (!is.null(data) &&\n !is.null(.subset2(design, \"nobs\")) &&\n NROW(data) != .subset2(design, \"nobs\")) {\n cli_abort(c(\n sprintf(\n \"%s (nobs: %d) is not compatible with the %s (nobs: %d)\",\n object_name(self), NROW(data), layout_name, layout_nobs\n ),\n i = \"try to set {.code inherit_nobs = FALSE}\"\n ))\n }\n } else { # for `FALSE` and `NULL`\n if (is.null(data)) {\n design[\"nobs\"] <- list(NULL)\n } else {\n if (NROW(data) == 0L) {\n cli_abort(\"{.arg data} cannot be empty\",\n call = self$call\n )\n }\n design[\"nobs\"] <- list(NROW(data))\n }\n }\n }\n\n # we keep the names from the layout data for usage\n self$labels <- vec_names(data)\n\n # determine if we should inherit panel\n # by default, `inherit_panel = FALSE`\n if (isTRUE(self$inherit_panel)) {\n if (is.null(self$labels0)) {\n cli_abort(c(\n \"Cannot inherit panel from the layout\",\n i = \"No labels found in the layout data\"\n ))\n }\n if (is.null(self$labels)) {\n cli_abort(c(\n \"Cannot inherit panel from the layout\",\n i = \"No labels found in the current {.arg data}\"\n ))\n }\n if (!all(self$labels %in% self$labels0)) {\n cli_abort(c(\n \"Cannot inherit panel from the layout\",\n i = \"Some labels in the current data are not found in the previous layout data\"\n ))\n }\n if (!is.null(panel <- .subset2(design, \"panel\"))) {\n design[\"panel\"] <- list(\n droplevels(panel[match(self$labels, self$labels0)])\n )\n }\n } else {\n design[\"panel\"] <- list(NULL)\n }\n\n # determine if we should inherit panel\n # by default, `inherit_index = FALSE`\n if (isTRUE(self$inherit_index)) {\n if (is.null(self$labels0)) {\n cli_abort(c(\n \"Cannot inherit ordering index from the layout\",\n i = \"No labels found in the previous layout data\"\n ))\n }\n\n if (is.null(self$labels)) {\n cli_abort(c(\n \"Cannot inherit ordering index from the layout\",\n i = \"No labels found in the current {.arg data}\"\n ))\n }\n\n if (!all(self$labels %in% self$labels0)) {\n cli_abort(c(\n \"Cannot inherit ordering index from the layout\",\n i = \"Some labels in the current data are not found in the previous layout data\"\n ))\n }\n\n if (!is.null(index <- .subset2(design, \"index\"))) {\n new_index <- order(match(\n self$labels,\n vec_slice(self$labels0, index)\n ))\n\n # we always make the index following the panel\n if (!is.null(panel <- .subset2(design, \"panel\"))) {\n new_index <- reorder_index(panel, new_index)\n }\n design[\"index\"] <- list(new_index)\n }\n } else {\n design[\"index\"] <- list(NULL)\n }\n\n # reset layout data\n layout@data <- data # don't restore the attribute\n\n # update the design\n layout@design <- design\n\n # udpate break_points\n layout@break_points <- c(layout@break_points, length(layout@plot_list))\n layout\n }\n)\n"], ["/ggalign/R/layout-chain-stack-cross.R", "#' Arrange plots crosswise horizontally or vertically\n#'\n#' @description\n#' `r lifecycle::badge('experimental')`\n#'\n#' The `stack_cross` function is derived from [`stack_discrete()`] and allows\n#' for different layout ordering indices within a single layout.\n#'\n#' Two aliases are provided for convenience:\n#' - `stack_crossv`: A special case of `stack_cross` that sets\n#' `direction = \"v\"` for vertical alignment.\n#' - `stack_crossh`: A special case of `stack_cross` that sets\n#' `direction = \"h\"` for horizontal alignment.\n#'\n#' @param data `r rd_layout_data()`, [`fortify_matrix()`] will be used to\n#' convert the data to a matrix.\n#' @param ... Additional arguments passed to [`fortify_matrix()`].\n#' @inheritParams stack_layout\n#' @seealso [`ggcross()`]\n#' @export\nstack_cross <- function(direction, data = NULL, ...,\n theme = NULL, sizes = NA) {\n UseMethod(\"stack_cross\", data)\n}\n\n#' @export\n#' @rdname stack_cross\nstack_crossv <- function(data = NULL, ...) {\n stack_cross(data = data, direction = \"v\", ...)\n}\n\n#' @export\n#' @rdname stack_cross\nstack_crossh <- function(data = NULL, ...) {\n stack_cross(data = data, direction = \"h\", ...)\n}\n\n#' @include layout-chain-stack-.R\nmethods::setClass(\n \"StackCross\",\n contains = \"StackLayout\",\n # A list of old design\n list(odesign = \"list\", cross_points = \"integer\", break_points = \"integer\"),\n prototype = list(\n odesign = list(),\n cross_points = integer(),\n break_points = integer()\n )\n)\n\n#' @export\nstack_cross.default <- function(direction, data = NULL, ...) {\n ans <- stack_discrete(data = data, direction = direction, ...)\n ans <- methods::as(ans, \"StackCross\")\n ans@name <- \"stack_cross\"\n ans\n}\n\n#' @importFrom grid unit.c\n#' @importFrom rlang is_empty is_string\nresolve_stack_layout.StackCross <- function(stack, schemes, theme,\n extra_design) {\n # check if we should initialize the layout observations\n layout_design <- stack@design\n if (is_discrete_design(layout_design) &&\n is.null(.subset2(layout_design, \"nobs\")) &&\n any(vapply(plot_list, is_cross_plot, logical(1L), USE.NAMES = FALSE))) {\n cli_abort(sprintf(\n \"You must initialize the layout observations to plot the %s\",\n object_name(stack)\n ))\n }\n plot_list <- stack@plot_list\n\n direction <- stack@direction\n position <- .subset2(stack@heatmap, \"position\")\n plot_list <- vec_chop(\n plot_list,\n sizes = diff(c(0L, stack@cross_points, length(plot_list)))\n )\n design_list <- c(stack@odesign, list(layout_design))\n\n # build the stack\n composer <- stack_composer(direction)\n\n # for `free_spaces`, if we have applied it in the whole stack layout we\n # shouln't use it for a single plot. Otherwise, the guide legends collected\n # by the layout will overlap with the axis of the plot in the layout.\n #\n # this occurs in the annotation stack (`position` is not `NULL`).\n stack_spaces <- .subset2(.subset2(schemes, \"scheme_align\"), \"free_spaces\")\n if (is_string(stack_spaces) && !is.null(position)) {\n released_spaces <- stack_spaces\n } else {\n released_spaces <- NULL\n }\n previous_design <- NULL\n for (i in seq_along(plot_list)) {\n plots <- .subset2(plot_list, i)\n\n # prepare design for current group\n design <- .subset2(design_list, i)\n design <- setup_design(design)\n\n if (is_empty(plots)) {\n previous_design <- design\n next\n }\n\n # we remove the plot without actual plot area\n keep <- vapply(plots, function(plot) {\n # we remove objects without plot area\n # Now, only `CraftBox` will contain `NULL`\n !is_craftbox(plot) || !is.null(plot@plot)\n }, logical(1L), USE.NAMES = FALSE)\n plots <- .subset(plots, keep)\n\n if (is_empty(plots)) {\n previous_design <- design\n next\n }\n\n # we reorder the plots based on the `order` slot\n plot_order <- vapply(plots, function(plot) {\n # always keep cross() in the start\n if (is_cross_plot(plot)) {\n 1L\n } else if (is_craftbox(plot)) {\n .subset2(plot@active, \"order\")\n } else {\n .subset2(plot@plot_active, \"order\")\n }\n }, integer(1L), USE.NAMES = FALSE)\n plots <- .subset(plots, make_order(plot_order))\n composer <- stack_composer_add(\n plots,\n stack = stack,\n composer,\n schemes = schemes,\n theme = theme,\n design = design,\n extra_design = extra_design,\n direction = direction,\n position = position,\n released_spaces = released_spaces,\n previous_design = previous_design\n )\n previous_design <- design\n }\n composer\n}\n"], ["/ggalign/R/pair-links.R", "#' Helper function to create pairs of observation groups\n#'\n#' @description\n#' [`ggmark()`] and [`cross_link()`] allow users to add links between\n#' observations. These functions help define the linked observations. The\n#' selected pairs will either be linked together, or each group in the pair will\n#' be linked separately to the same plot area.\n#'\n#' - `pair_links`: Helper function to create pairs of observation groups.\n#' - `range_link`: Helper function to create a range of observations.\n#'\n#' @param ... <[dyn-dots][rlang::dyn-dots]> A list of formulas, where each side\n#' of the formula should be an `integer` or `character` index of the original\n#' data, or a `range_link()` object defining the linked observations. Use\n#' `NULL` to indicate no link on that side. You can also combine these by\n#' wrapping them into a single `list()`. If only the left-hand side of the\n#' formula exists, you can input it directly. For integer indices, wrap them\n#' with [`I()`] to use the ordering from the layout. You can also use\n#' [`waiver()`][ggplot2::waiver()] to inherit values from the other group.\n#' @param .handle_missing A string of `r oxford_or(c(\"error\", \"remove\"))`\n#' indicates the action for handling missing observations.\n#' @param .reorder A string of `r oxford_or(c(\"hand1\", \"hand2\"))` indicating\n#' whether to reorder the input links to follow the specified layout ordering.\n#' @examples\n#' x <- pair_links(\n#' # group on the left hand only\n#' c(\"a\", \"b\"),\n#' # normally, integer index will be interpreted as the index of the\n#' # origianl data\n#' 1:2,\n#' # wrapped with `I()` indicate` the integer index is ordering of the\n#' # layout\n#' I(1:2),\n#' range_link(1, 6),\n#' range_link(\"a\", \"b\"),\n#' # group on the right hand only\n#' ~ 1:2,\n#' ~ c(\"a\", \"b\"),\n#' ~ range_link(1, 6),\n#' # group on the both side\n#' range_link(1, 6) ~ c(\"a\", \"b\"),\n#' # waiver() indicates the right hand is the same of the left hand\n#' range_link(1, 6) ~ waiver(),\n#' # the same for the left hand\n#' waiver() ~ 1:2,\n#' ~NULL # an empty link\n#' )\n#' x\n#'\n#' # we can modify it as usual list\n#' x[[1]] <- NULL # remove the first link\n#' x$a <- ~LETTERS\n#' x\n#'\n#' # modify with a list\n#' x[1:2] <- list(~ c(\"a\", \"b\"), ~ range_link(\"a\", \"b\"))\n#' x\n#' @export\npair_links <- function(..., .handle_missing = \"error\", .reorder = NULL) {\n .handle_missing <- arg_match0(.handle_missing, c(\"error\", \"remove\"))\n if (!is.null(.reorder)) {\n .reorder <- arg_match0(.reorder, c(\"hand1\", \"hand2\"))\n }\n pairs <- rlang::dots_list(..., .ignore_empty = \"all\", .named = NULL)\n new_pair_links(\n lapply(pairs, as_pair_link, x_arg = \"...\", call = current_call()),\n handle_missing = .handle_missing, reorder = .reorder\n )\n}\n\nnew_pair_links <- function(x = list(), ..., class = character()) {\n new_vctr(x, ..., class = c(class, \"ggalign_pair_links\"))\n}\n\n#' @export\nobj_print_header.ggalign_pair_links <- function(x, ...) {\n cat(\"<\", vec_ptype_full(x), \">\", \"\\n\", sep = \"\")\n cat(\n sprintf(\n \"A total of %d pair%s of link groups\",\n vec_size(x), if (vec_size(x) > 1L) \"s\" else \"\"\n ),\n \"\\n\",\n sep = \"\"\n )\n invisible(x)\n}\n\n#' @export\nobj_print_data.ggalign_pair_links <- function(x, ...) {\n if (vec_size(x) > 0L) {\n hand1 <- vapply(x, function(hand) {\n deparse_link(hand, ..., hand = \"hand1\")\n }, character(1L), USE.NAMES = FALSE)\n hand2 <- vapply(x, function(hand) {\n deparse_link(hand, ..., hand = \"hand2\")\n }, character(1L), USE.NAMES = FALSE)\n nms <- c(\"\", paste0(names_or_index(x), \": \"))\n nms <- format(nms, justify = \"right\")\n empty <- character(vec_size(hand2))\n empty[hand1 == \"\" & hand2 == \"\"] <- \" \"\n empty <- format(c(\"\", empty), justify = \"left\")\n hand1 <- format(c(\"hand1\", hand1), justify = \"right\")\n hand2 <- format(c(\"hand2\", hand2), justify = \"left\")\n cat(\"\\n\")\n cat(paste0(\" \", nms, hand1, \" ~ \", hand2, empty), sep = \"\\n\")\n cat(\"\\n\")\n }\n invisible(x)\n}\n\n#' @export\nobj_print_footer.ggalign_pair_links <- function(x, ...) {\n NextMethod()\n # `lengths`: will call `length.ggalign_pair_link()` method\n n <- sum(lengths(x, use.names = FALSE))\n cat(\n sprintf(\n \"A total of %d link group%s\", n,\n if (n > 1L) \"s\" else \"\"\n ),\n \"\\n\",\n sep = \"\"\n )\n invisible(x)\n}\n\n#' @export\n`[<-.ggalign_pair_links` <- function(x, i, value) {\n value <- lapply(value, as_pair_link, x_arg = \"value\", call = current_call())\n NextMethod()\n}\n\n#' @export\n`[[<-.ggalign_pair_links` <- function(x, i, value) {\n # let `NULL` to remove the link\n if (!is.null(value)) value <- as_pair_link(value)\n NextMethod()\n}\n\n#' @export\n`$<-.ggalign_pair_links` <- function(x, i, value) {\n # let `NULL` to remove the link\n if (!is.null(value)) value <- as_pair_link(value)\n NextMethod()\n}\n\n#' @export\nvec_ptype2.ggalign_pair_links.list <- function(x, y, ...) {\n x\n}\n\n#' @export\nvec_ptype2.list.ggalign_pair_links <- function(x, y, ...) {\n y\n}\n\n#' @export\nvec_cast.ggalign_pair_links.list <- function(x, to, ...,\n x_arg = caller_arg(x),\n to_arg = \"\",\n call = caller_env()) {\n new_pair_links(lapply(x, as_pair_link, x_arg = x_arg, call = call))\n}\n\n#########################################################\n#' @param point1,point2 A single integer or character index, defining the lower\n#' and higher bounds of the range. For integer indices, wrap them with [`I()`]\n#' to indicate the ordered index by the layout.\n#' @export\n#' @rdname pair_links\nrange_link <- function(point1, point2) {\n if (!is_scalar(point1) ||\n (!is.character(point1) && !is.numeric(point1))) {\n cli_abort(\"{.arg point1} must be a single numeric or character index\")\n }\n if (!is_scalar(point2) ||\n (!is.character(point2) && !is.numeric(point2))) {\n cli_abort(\"{.arg point2} must be a single numeric or character index\")\n }\n point1 <- as_obs_link(point1)\n point2 <- as_obs_link(point2)\n structure(list(point1 = point1, point2 = point2),\n class = \"ggalign_range_link\"\n )\n}\n\nis_range_link <- function(x) inherits(x, \"ggalign_range_link\")\n\n########################################################\nnew_pair_link <- function(hand1 = NULL, hand2 = NULL,\n ..., class = character()) {\n structure(\n .Data = list(hand1 = hand1, hand2 = hand2),\n ...,\n class = c(class, \"ggalign_pair_link\")\n )\n}\n\n#' @export\nvec_proxy.ggalign_pair_link <- function(x, ...) x\n\n#' @export\nprint.ggalign_pair_link <- function(x, ...) obj_print(x, ...)\n\n#' @export\nobj_print_header.ggalign_pair_link <- function(x, ...) {\n cat(sprintf(\"<%s>\", vec_ptype_full(x)), \"\\n\", sep = \"\")\n invisible(x)\n}\n\n#' @export\nobj_print_data.ggalign_pair_link <- function(x, ...) {\n if (length(x) > 0L) {\n cat(c(\n sprintf(\" hand1: %s\", deparse_link(.subset2(x, \"hand1\"), ...)),\n sprintf(\" hand2: %s\", deparse_link(.subset2(x, \"hand2\"), ...))\n ), sep = \"\\n\")\n }\n invisible(x)\n}\n\n#' @param x A `ggalign_pair_link` object.\n#' @noRd\n#' @export\nlength.ggalign_pair_link <- function(x) {\n sum(!vapply(x, is.null, logical(1L), USE.NAMES = FALSE))\n}\n\n##################################################\n#' @export\nvec_ptype2.ggalign_pair_link.ggalign_pair_link <- function(x, y, ...) {\n x\n}\n\n#' @export\nvec_ptype2.ggalign_pair_link.NULL <- function(x, y, ...) {\n x\n}\n\n#' @export\nvec_ptype2.NULL.ggalign_pair_link <- function(x, y, ...) {\n y\n}\n\n#' @export\nvec_ptype2.ggalign_pair_link.numeric <- function(x, y, ...) {\n x\n}\n\n#' @export\nvec_ptype2.numeric.ggalign_pair_link <- function(x, y, ...) {\n y\n}\n\n#' @export\nvec_ptype2.ggalign_pair_link.integer <- function(x, y, ...) {\n x\n}\n\n#' @export\nvec_ptype2.integer.ggalign_pair_link <- function(x, y, ...) {\n y\n}\n\n#' @export\nvec_ptype2.ggalign_pair_link.double <- function(x, y, ...) {\n x\n}\n\n#' @export\nvec_ptype2.double.ggalign_pair_link <- function(x, y, ...) {\n y\n}\n\n#' @export\nvec_ptype2.ggalign_pair_link.character <- function(x, y, ...) {\n x\n}\n\n#' @export\nvec_ptype2.character.ggalign_pair_link <- function(x, y, ...) {\n y\n}\n\n#' @export\nvec_ptype2.ggalign_pair_link.formula <- function(x, y, ...) {\n x\n}\n\n#' @export\nvec_ptype2.formula.ggalign_pair_link <- function(x, y, ...) {\n y\n}\n\n#' @export\nvec_ptype2.ggalign_pair_link.waiver <- function(x, y, ...) {\n x\n}\n\n#' @export\nvec_ptype2.waiver.ggalign_pair_link <- function(x, y, ...) {\n y\n}\n\n#' @export\nvec_ptype2.ggalign_pair_link.ggalign_range_link <- function(x, y, ...) {\n x\n}\n\n#' @export\nvec_ptype2.ggalign_range_link.ggalign_pair_link <- function(x, y, ...) {\n y\n}\n\n#' @export\nvec_ptype2.ggalign_pair_link.AsIs <- function(x, y, ...) {\n vec_ptype2(x, remove_class(y, \"AsIs\"), ...)\n}\n\n#' @export\nvec_ptype2.AsIs.ggalign_pair_link <- function(x, y, ...) {\n vec_ptype2(remove_class(x, \"AsIs\"), y, ...)\n}\n\n#' @export\nvec_ptype2.ggalign_pair_link.list <- function(x, y, ...) {\n x\n}\n\n#' @export\nvec_ptype2.list.ggalign_pair_link <- function(x, y, ...) {\n y\n}\n\n#############################################################\n#' @export\nvec_cast.ggalign_pair_link.numeric <- function(x, to, ...,\n x_arg = caller_arg(x),\n to_arg = \"\",\n call = caller_env()) {\n new_pair_link(as_obs_link(x, arg = x_arg, call = call))\n}\n\n#' @export\nvec_cast.ggalign_pair_link.double <- vec_cast.ggalign_pair_link.numeric\n\n#' @export\nvec_cast.ggalign_pair_link.integer <- vec_cast.ggalign_pair_link.numeric\n\n#' @export\nvec_cast.ggalign_pair_link.character <- vec_cast.ggalign_pair_link.numeric\n\n#' @export\nvec_cast.ggalign_pair_link.ggalign_range_link <-\n vec_cast.ggalign_pair_link.integer\n\n#' @export\nvec_cast.ggalign_pair_link.list <- vec_cast.ggalign_pair_link.numeric\n\n#' @export\nvec_cast.ggalign_pair_link.AsIs <- function(x, to, ...,\n x_arg = caller_arg(x),\n to_arg = \"\",\n call = caller_env()) {\n I(vec_cast(\n remove_class(x, \"AsIs\"),\n to = to, ...,\n x_arg = x_arg, call = call\n ))\n}\n\n#' @export\nvec_cast.ggalign_pair_link.formula <- function(x, to, ...,\n x_arg = caller_arg(x),\n to_arg = \"\",\n call = caller_env()) {\n hand1 <- rlang::eval_tidy(rlang::f_lhs(x), env = rlang::f_env(x))\n hand1 <- as_obs_link(hand1, arg = x_arg, call = call)\n hand2 <- rlang::eval_tidy(rlang::f_rhs(x), env = rlang::f_env(x))\n hand2 <- as_obs_link(hand2, arg = x_arg, call = call)\n new_pair_link(hand1, hand2)\n}\n\nas_pair_link <- function(x, ...) {\n if (is.null(x)) { # vec_cast() cannot convert `NULL`\n new_pair_link()\n } else {\n vec_cast(x, to = new_pair_link(), ...)\n }\n}\n\n########################################################\nas_obs_link <- function(x, ..., arg = caller_arg(x), call = caller_env()) {\n UseMethod(\"as_obs_link\")\n}\n\n#' @export\nas_obs_link.NULL <- function(x, ...) x\n\n#' @export\nas_obs_link.AsIs <- function(x, ...) {\n I(as_obs_link(remove_class(x, \"AsIs\"), ...))\n}\n\n#' @export\nas_obs_link.numeric <- function(x, ..., arg = caller_arg(x),\n call = caller_env()) {\n vec_cast(x, integer(), x_arg = arg, call = call)\n}\n\n#' @export\nas_obs_link.integer <- as_obs_link.NULL\n\n#' @export\nas_obs_link.double <- as_obs_link.numeric\n\n#' @export\nas_obs_link.character <- function(x, ..., arg = caller_arg(x),\n call = caller_env()) {\n if (any(x == \"\")) {\n cli_abort(\"empty string is not allowed\", call = call)\n }\n x\n}\n\n#' @export\nas_obs_link.waiver <- as_obs_link.NULL\n\n#' @export\nas_obs_link.list <- function(x, ..., arg = caller_arg(x),\n call = caller_env()) {\n x <- x[!vapply(x, is.null, logical(1L), USE.NAMES = FALSE)]\n if (is_empty(x)) return(NULL) # styler: off\n lapply(x, as_obs_link, arg = arg, call = call)\n}\n\n#' @export\nas_obs_link.ggalign_range_link <- as_obs_link.NULL\n\n#' @export\nas_obs_link.default <- function(x, ..., arg = caller_arg(x),\n call = caller_env()) {\n stop_incompatible_cast(\n x, new_pair_link(),\n x_arg = arg, to_arg = \"\",\n call = call\n )\n}\n\n#' @export\nprint.ggalign_range_link <- function(x, ...) {\n cat(deparse_link(x))\n invisible(x)\n}\n\n###########################################################\n#' @return A single string\n#' @noRd\ndeparse_link <- function(x, ...) deparse_link2(x, ...) %||% \"\"\n\n#' @return A single string or `NULL`\n#' @noRd\ndeparse_link2 <- function(x, ...) UseMethod(\"deparse_link2\")\n\n# Basic object\n#' @export\ndeparse_link2.integer <- function(x, trunc = 3L, head = trunc - 1L,\n tail = 1L, ...) {\n l <- length(x)\n ans <- paste(\n deparse(x, control = c(\"keepNA\", \"niceNames\", \"showAttributes\")),\n collapse = \" \"\n )\n if (l > trunc && startsWith(ans, \"c\")) {\n ans <- sprintf(\"c(%s)\", paste(c(\n x[seq_len(head)], \"...\", x[seq.int(l - tail + 1L, l)]\n ), collapse = \", \"))\n }\n ans\n}\n\n#' @export\ndeparse_link2.character <- function(x, trunc = 3L, head = trunc - 1L,\n tail = 1L, ...) {\n l <- length(x)\n if (l <= trunc) {\n ans <- paste(deparse(x), collapse = \" \")\n } else {\n ans <- sprintf(\"c(%s)\", paste(c(\n x[seq_len(head)], \"...\", x[seq.int(l - tail + 1L, l)]\n ), collapse = \", \"))\n }\n ans\n}\n\n#' @export\ndeparse_link2.waiver <- function(x, ...) \"waiver()\"\n\n#' @export\ndeparse_link2.NULL <- function(x, ...) NULL\n\n# To allow `I()` to be used to the whole formula, we must define the method for\n# this, though `ggalign_pair_link` shouldn't be considered as an observation\n#' @export\ndeparse_link2.ggalign_pair_link <- function(x, ..., hand) {\n deparse_link2(.subset2(x, hand), ...)\n}\n\n#' @export\ndeparse_link2.AsIs <- function(x, ...) {\n ans <- deparse_link2(remove_class(x, \"AsIs\"), ...)\n if (!is.null(ans)) ans <- sprintf(\"I(%s)\", ans)\n ans\n}\n\n# Recurse version\n#' @export\ndeparse_link2.ggalign_range_link <- function(x, ...) {\n sprintf(\n \"range_link(%s, %s)\",\n deparse_link(.subset2(x, \"point1\"), ...),\n deparse_link(.subset2(x, \"point2\"), ...)\n )\n}\n\n#' @export\ndeparse_link2.list <- function(x, trunc = 3L, head = trunc - 1L,\n tail = 1L, ...) {\n l <- length(x)\n if (l <= trunc) {\n ans <- vapply(x, deparse_link, character(1L), ...,\n trunc = trunc, head = head, tail = tail,\n USE.NAMES = FALSE\n )\n } else {\n ans <- c(\n vapply(x[seq_len(head)],\n deparse_link, character(1L), ...,\n trunc = trunc, head = head, tail = tail,\n USE.NAMES = FALSE\n ),\n \"...\",\n vapply(x[seq.int(l - tail + 1L, l)],\n deparse_link, character(1L), ...,\n trunc = trunc, head = head, tail = tail,\n USE.NAMES = FALSE\n )\n )\n }\n sprintf(\"list(%s)\", paste(ans, collapse = \", \"))\n}\n\n###################################################\nmake_links_data <- function(links, design1, design2,\n labels1, labels2) {\n link_index_list <- lapply(\n links, make_pair_link_index,\n design1 = design1, design2 = design2,\n labels1 = labels1, labels2 = labels2,\n handle_missing = attr(links, \"handle_missing\")\n )\n names(link_index_list) <- names_or_index(links)\n if (!is.null(reorder <- attr(links, \"reorder\"))) {\n index <- vapply(link_index_list, function(link_index) {\n if (is.null(link_index) ||\n is.null(index <- .subset2(link_index, reorder))) {\n NA_integer_\n } else {\n vec_slice(index, 1L)\n }\n }, integer(1L), USE.NAMES = FALSE)\n link_index_list <- link_index_list[order(index)]\n }\n link_index_list\n}\n\nmake_pair_link_index <- function(pair_link, design1, design2,\n labels1, labels2, handle_missing) {\n input1 <- .subset2(pair_link, 1L)\n input2 <- .subset2(pair_link, 2L)\n\n # make the data\n hand1 <- make_link_index(input1,\n design = design1, labels = labels1,\n other = input2, data_index = !inherits(pair_link, \"AsIs\"),\n handle_missing = handle_missing\n )\n hand2 <- make_link_index(input2,\n design = design2, labels = labels2,\n other = input1, data_index = !inherits(pair_link, \"AsIs\"),\n handle_missing = handle_missing\n )\n if (is.null(hand1) && is.null(hand2)) {\n return(NULL)\n }\n list(hand1 = hand1, hand2 = hand2)\n}\n\nmake_link_index <- function(link, design, labels, other, data_index,\n handle_missing, arg = caller_arg(link),\n call = caller_call()) {\n link <- link_to_location(\n link,\n n = .subset2(design, \"nobs\"),\n labels = labels,\n index = .subset2(design, \"index\"),\n other = other,\n data_index = data_index,\n handle_missing = handle_missing,\n arg = arg, call = call\n )\n if (is_empty(link)) {\n return(NULL)\n }\n # always use integer, otherwise, will cause error when drawing\n # due to loss of precision, I don't know why, it should be integer already?\n vec_unique(vec_cast(link, integer()))\n}\n\nlink_to_location <- function(x, ...) UseMethod(\"link_to_location\")\n\n#' @export\nlink_to_location.AsIs <- function(x, ..., data_index) {\n link_to_location(remove_class(x, \"AsIs\"), ..., data_index = FALSE)\n}\n\n#' @export\nlink_to_location.character <- function(x, ..., n, labels, index, handle_missing,\n arg = caller_arg(x),\n call = caller_call()) {\n if (identical(handle_missing, \"remove\") && !is.null(labels)) {\n x <- x[x %in% labels]\n }\n ans <- vec_as_location(x, n = n, names = labels, arg = arg, call = call)\n match(ans, index) # character always match the original data\n}\n\n#' @export\nlink_to_location.integer <- function(x, ..., n, index, data_index,\n handle_missing, arg = caller_arg(x),\n call = caller_call()) {\n ans <- num_as_location(x,\n n = n,\n arg = arg, call = call,\n negative = \"error\",\n zero = \"error\",\n oob = handle_missing\n )\n # integer index by default match the original data\n if (isTRUE(data_index)) match(ans, index) else ans\n}\n\n#' @export\nlink_to_location.ggalign_range_link <- function(x, ..., arg = caller_arg(x),\n call = caller_call()) {\n point1 <- link_to_location(\n .subset2(x, \"point1\"),\n ...,\n arg = \"point1\",\n call = quote(range_link())\n )\n point2 <- link_to_location(\n .subset2(x, \"point2\"),\n ...,\n arg = \"point2\",\n call = quote(range_link())\n )\n point1:point2\n}\n\n#' @export\nlink_to_location.list <- function(x, ...) {\n unlist(lapply(x, link_to_location, ...), FALSE, FALSE)\n}\n\n#' @export\nlink_to_location.waiver <- function(x, ..., other) {\n link_to_location(other %|w|% NULL, ...)\n}\n\n#' @export\nlink_to_location.NULL <- function(x, ...) NULL\n"], ["/ggalign/R/layout-chain-circle-genomic.R", "#' Create a Circular Layout for Genomic Data\n#'\n#' `circle_genomic()` constructs a circular layout specifically for genomic\n#' data. It is a specialized variant of `circle_continuous()` that applies\n#' default axis limits and coerces the first column of each plot’s data to use\n#' chromosome (`seqname`) identifiers—matching those in the layout data—as\n#' factor levels.\n#'\n#' @param data The input data, which can be:\n#' - A `character` string (\"hg19\" or \"hg38\") to load a predefined cytoband\n#' reference.\n#' - A `data.frame` with at least three columns: `chromosome`, `start`, and\n#' `end` positions.\n#' - A genomic object convertible via `fortify_data_frame()`.\n#' @param ... Additional arguments passed to specific methods or\n#' `fortify_data_frame()`.\n#' @inheritParams circle_continuous\n#' @return A `circle_layout` object representing the genomic layout.\n#' @export\ncircle_genomic <- function(data, ..., radial = NULL,\n direction = \"outward\",\n sector_spacing = NULL,\n theme = NULL) {\n UseMethod(\"circle_genomic\")\n}\n\n#' @export\ncircle_genomic.NULL <- function(data, ...) {\n cli_abort(\"{.arg data} must be provided to initialize `circle_genomic()`\")\n}\n\n#' @export\ncircle_genomic.waiver <- circle_genomic.NULL\n\n#' @export\ncircle_genomic.character <- function(data, ...) {\n data <- arg_match0(data, c(\"hg19\", \"hg38\"))\n data <- readRDS(\n pkg_extdata(\n switch(data,\n hg19 = \"ref_cytoband_hg19.rds\",\n hg38 = \"ref_cytoband_hg38.rds\"\n ),\n mustWork = TRUE\n )\n )\n circle_genomic(data, ...)\n}\n\n#' @export\n#' @keywords internal\ncircle_genomic.data.frame <- function(data, ..., radial = NULL,\n direction = \"outward\",\n sector_spacing = NULL,\n theme = NULL) {\n rlang::check_dots_empty()\n if (ncol(data) < 3L) {\n cli_abort(\"{.arg data} must have at least 3 columns: chromosome, start, and end\")\n }\n if (anyNA(data[[1L]]) || anyNA(data[[2L]]) || anyNA(data[[3L]])) {\n cli_abort(\"Columns 1, 2, and 3 of {.arg data} must not contain missing values\")\n }\n if (!is.numeric(data[[2L]]) || !is.numeric(data[[3L]])) {\n cli_abort(\"Columns 2 and 3 of {.arg data} must be numeric (start and end positions)\")\n }\n if (any(data[[2L]] > data[[3L]])) {\n cli_abort(\"Column 2 (start) must not be greater than column 3 (end) in any row of {.arg data}\")\n }\n data[[1L]] <- as.factor(data[[1L]])\n # seqnames, start, end\n # Special considerations for `data.table`, we cannot use `data[1:2]`\n groups <- vec_split(\n data.frame(start = data[[2L]], end = data[[3L]]),\n data[[1L]]\n )\n ranges <- lapply(\n .subset2(groups, \"val\"),\n function(d) genomic_range(.subset2(d, 1L), .subset2(d, 2L))\n )\n lvls <- levels(data[[1L]])\n names(ranges) <- .subset2(groups, \"key\")\n ranges <- ranges[lvls]\n limits <- continuous_limits(!!!ranges)\n ranges <- vec_rbind(!!!ranges, .names_to = \"seqnames\")\n ranges$seqnames <- factor(ranges$seqnames, levels = lvls)\n new_circle_layout(\n data = ggalign_data_set(data, seqnames = lvls, ranges = ranges),\n design = limits,\n radial = radial, direction = direction,\n sector_spacing = sector_spacing,\n schemes = default_schemes(data), theme = theme,\n name = \"circle_genomic\"\n )\n}\n\n#' @export\ncircle_genomic.default <- function(data, ..., radial = NULL,\n direction = \"outward\",\n sector_spacing = NULL,\n theme = NULL) {\n data <- fortify_data_frame(data = data, ...)\n circle_genomic(data,\n radial = radial, direction = direction,\n sector_spacing = sector_spacing, theme = theme\n )\n}\n\ngenomic_range <- function(start, end) {\n if (length(start) == 1) return(c(start = start, end = end)) # styler: off\n ordering <- order(start)\n s <- start[ordering[1L]]\n e <- end[ordering[1L]]\n for (i in ordering[-1L]) {\n if (start[ordering[i]] - e > 1) {\n cli_abort(\"Input genomic ranges cannot contain intervals\")\n }\n e <- end[ordering[i]]\n }\n c(start = s, end = e)\n}\n\n#' @export\nchain_decorate.CircleLayout <- function(layout, plot) {\n if (!identical(layout@name, \"circle_genomic\")) {\n return(plot)\n }\n if (is.data.frame(data <- plot$data)) {\n data[[1L]] <- factor(\n data[[1L]],\n levels = ggalign_attr(layout@data, \"seqnames\")\n )\n missing <- is.na(data[[1L]])\n if (any(missing)) {\n cli_warn(\"Removing {.val {sum(missing)}} rows contain missing {.field seqnames}\")\n data <- vec_slice(data, !missing)\n }\n plot$data <- data\n }\n plot\n}\n"], ["/ggalign/R/craft-align-order2.R", "#' Reorders layout observations based on specific statistics.\n#'\n#' @details\n#' `r lifecycle::badge('experimental')`\n#'\n#' The `align_order2()` function differs from `align_order()` in that the\n#' `weights` argument in `align_order()` must return atomic weights for each\n#' observation. In contrast, the `stat` argument in `align_order2()` can\n#' return more complex structures, such as [hclust][stats::hclust] or\n#' [dendrogram][stats::as.dendrogram], among others.\n#'\n#' Typically, you can achieve the functionality of `align_order2()` using\n#' `align_order()` by manually extracting the ordering information from\n#' the statistic.\n#'\n#' @param stat A statistical function which accepts a data and returns the\n#' statistic, which we'll call [`order2()`] to extract the ordering information.\n#' @param ... <[dyn-dots][rlang::dyn-dots]> Additional arguments passed to\n#' function provided in `stat` argument.\n#' @param data A `matrix`, `data frame`, or atomic vector used as the input for\n#' the `stat` function. Alternatively, you can specify a `function` (including\n#' purrr-like lambda syntax) that will be applied to the layout matrix,\n#' transforming it as necessary for statistic calculations. By default, it will\n#' inherit from the layout matrix.\n#' @inheritParams align_order\n#' @inheritSection align Discrete Axis Alignment\n#' @examples\n#' ggheatmap(matrix(rnorm(81), nrow = 9)) +\n#' anno_left() +\n#' align_order2(hclust2)\n#' @seealso [order2()]\n#' @importFrom ggplot2 waiver\n#' @importFrom rlang list2\n#' @export\nalign_order2 <- function(stat, ..., reverse = FALSE,\n strict = TRUE, data = NULL,\n active = NULL) {\n stat <- rlang::as_function(stat)\n assert_bool(strict)\n assert_bool(reverse)\n assert_active(active)\n active <- update_active(active, new_active(use = FALSE))\n align(\n align = AlignOrder2,\n stat = stat,\n params = list2(...),\n reverse = reverse,\n strict = strict,\n active = active,\n data = data\n )\n}\n\n#' @importFrom ggplot2 ggproto\n#' @importFrom rlang inject\nAlignOrder2 <- ggproto(\"AlignOrder2\", CraftAlign,\n interact_layout = function(self, layout) {\n layout <- ggproto_parent(CraftAlign, self)$interact_layout(layout)\n layout_data <- layout@data\n if (is.null(input_data <- self$input_data) ||\n is.waive(input_data)) { # inherit from the layout\n if (is.null(data <- layout_data)) {\n cli_abort(c(\n sprintf(\n \"you must provide {.arg data} in %s\",\n object_name(self)\n ),\n i = sprintf(\"no data was found in %s\", self$layout_name)\n ))\n }\n } else if (is.function(input_data)) {\n if (is.null(layout_data)) {\n cli_abort(c(\n sprintf(\n \"{.arg data} in %s cannot be a function\",\n object_name(self)\n ),\n i = sprintf(\"no data was found in %s\", self$layout_name)\n ))\n }\n data <- input_data(layout_data)\n } else {\n data <- input_data\n }\n\n design <- layout@design\n layout_nobs <- .subset2(design, \"nobs\")\n\n # we always regard rows as the observations\n if (is.null(layout_nobs)) {\n layout_nobs <- vec_size(data)\n if (layout_nobs == 0L) {\n cli_abort(\"{.arg data} cannot be empty\", call = self$call)\n }\n design[\"nobs\"] <- list(layout_nobs)\n layout@design <- design\n } else if (vec_size(data) != layout_nobs) {\n cli_abort(sprintf(\n \"%s (nobs: %d) is not compatible with the %s (nobs: %d)\",\n object_name, vec_size(data), layout_name, layout_nobs\n ))\n }\n\n # save the labels\n self$labels <- vec_names(data) %||% vec_names(layout_data)\n self$data <- ggalign_data_restore(data, layout_data)\n layout\n },\n compute = function(self, panel, index) {\n inject(self$stat(self$data, !!!self$params))\n },\n align = function(self, panel, index) {\n index <- vec_cast(\n order2(self$statistics), integer(),\n x_arg = \"stat\", call = self$call\n )\n assert_mismatch_nobs(\n self, vec_size(self$data), vec_size(index),\n arg = \"stat\"\n )\n if (self$reverse) index <- rev(index)\n assert_reorder(self, panel, index, self$strict)\n list(panel, index)\n },\n summary_align = function(self) c(TRUE, FALSE)\n)\n\n#' Ordering Permutation\n#'\n#' `order2` returns a permutation which rearranges its first argument into\n#' ascending order.\n#' @param x Any objects can be extracting ordering.\n#' @return An integer vector unless any of the inputs has `2^31` or more\n#' elements, when it is a double vector.\n#' @examples\n#' order2(hclust2(matrix(rnorm(100L), nrow = 10L)))\n#' @export\norder2 <- function(x) UseMethod(\"order2\")\n\n#' @export\n#' @rdname order2\norder2.hclust <- function(x) x$order\n\n#' @importFrom stats order.dendrogram\n#' @export\n#' @rdname order2\norder2.dendrogram <- function(x) order.dendrogram(x)\n\n#' @export\n#' @rdname order2\norder2.ser_permutation_vector <- function(x) {\n rlang::check_installed(\n \"seriation\", \"to extract order from `ser_permutation_vector`\"\n )\n getExportedValue(\"seriation\", \"get_order\")(x)\n}\n\n#' @export\n#' @rdname order2\norder2.ser_permutation <- function(x) {\n rlang::check_installed(\n \"seriation\", \"to extract order from `ser_permutation`\"\n )\n getExportedValue(\"seriation\", \"get_order\")(x)\n}\n\n#' @export\n#' @rdname order2\norder2.phylo <- function(x) {\n second <- x$edge[, 2L, drop = TRUE]\n second[second <= length(x$tip.label)]\n}\n"], ["/ggalign/R/craft-align-dendrogram.R", "#' Plot dendrogram tree\n#'\n#' @param ... <[dyn-dots][rlang::dyn-dots]> Additional arguments passed to\n#' [`geom_segment()`][ggplot2::geom_segment].\n#' @param plot_dendrogram A boolean value indicates whether plot the dendrogram\n#' tree.\n#' @param plot_cut_height A boolean value indicates whether plot the cut height.\n#' @section ggplot2 specification:\n#' `align_dendro` initializes a ggplot `data` and `mapping`.\n#'\n#' The internal `ggplot` object will always use a default mapping of\n#' `aes(x = .data$x, y = .data$y)`.\n#'\n#' The default ggplot data is the `node` coordinates with `edge` data attached\n#' in [`ggalign`][ggalign_attr()] attribute, in addition, a\n#' [`geom_segment`][ggplot2::geom_segment] layer with a data frame of the `edge`\n#' coordinates will be added when `plot_dendrogram = TRUE`.\n#'\n#' See [`fortify_data_frame.dendrogram()`] for details.\n#' @param merge_dendrogram A single boolean value, indicates whether we should\n#' merge multiple dendrograms, only used when previous groups have been\n#' established. Default: `FALSE`.\n#' @inheritParams align_hclust\n#' @inheritParams fortify_data_frame.dendrogram\n#' @inheritParams ggalign\n#' @inheritSection align Discrete Axis Alignment\n#' @examples\n#' # align_dendro will always add a plot area\n#' ggheatmap(matrix(rnorm(81), nrow = 9)) +\n#' anno_top() +\n#' align_dendro()\n#' ggheatmap(matrix(rnorm(81), nrow = 9)) +\n#' anno_top() +\n#' align_dendro(k = 3L)\n#'\n#' @importFrom ggplot2 aes\n#' @importFrom rlang list2\n#' @export\nalign_dendro <- function(mapping = aes(), ...,\n distance = \"euclidean\",\n method = \"complete\",\n use_missing = \"pairwise.complete.obs\",\n reorder_dendrogram = FALSE,\n merge_dendrogram = FALSE,\n reorder_group = FALSE,\n k = NULL, h = NULL, cutree = NULL,\n plot_dendrogram = TRUE,\n plot_cut_height = NULL, root = NULL,\n center = FALSE, type = \"rectangle\",\n size = NULL, data = NULL,\n no_axes = NULL, active = NULL) {\n assert_bool(plot_cut_height, allow_null = TRUE)\n assert_bool(merge_dendrogram)\n\n # setup the default value for `plot_cut_height`\n plot_cut_height <- plot_cut_height %||% (\n # we by default don't draw the height of the user-provided cutree\n # since function like `dynamicTreeCut` will merge tree\n (!is.null(k) || !is.null(h)) && is.null(cutree)\n )\n plot <- ggplot(mapping = mapping)\n if (plot_dendrogram) {\n plot <- plot + ggplot2::geom_segment(\n mapping = aes(\n x = .data$x, y = .data$y,\n xend = .data$xend, yend = .data$yend\n ),\n ...,\n stat = \"identity\",\n data = function(data) ggalign_attr(data, \"edge\")\n )\n }\n assert_active(active)\n active <- update_active(active, new_active(use = TRUE))\n .align_hclust(\n align = AlignDendro,\n distance = distance,\n method = method,\n use_missing = use_missing,\n merge_dendro = merge_dendrogram,\n plot_cut_height = plot_cut_height,\n type = type, root = root, center = center,\n reorder_dendrogram = reorder_dendrogram,\n reorder_group = reorder_group,\n schemes = default_schemes(th = theme_no_strip()),\n k = k, h = h, cutree = cutree, data = data, active = active,\n size = size, no_axes = no_axes, plot = plot\n )\n}\n\n#' @importFrom ggplot2 aes ggplot\n#' @importFrom rlang inject\n#' @include craft-align-hclust.R\nAlignDendro <- ggproto(\"AlignDendro\", AlignHclust,\n setup_plot = function(self, plot) {\n ggadd_default(plot, aes(x = .data$x, y = .data$y)) + switch_direction(\n self$direction,\n ggplot2::labs(x = \"height\"),\n ggplot2::labs(y = \"height\")\n )\n },\n build_plot = function(self, plot, design, extra_design = NULL,\n previous_design = NULL) {\n plot_cut_height <- self$plot_cut_height\n center <- self$center\n type <- self$type\n root <- self$root\n panel <- .subset2(design, \"panel\")\n index <- .subset2(design, \"index\")\n\n statistics <- .subset2(self, \"statistics\")\n direction <- self$direction\n priority <- switch_direction(direction, \"left\", \"right\")\n dendrogram_panel <- self$panel[index]\n if (!is.null(dendrogram_panel) &&\n # we allow to change the panel level name, but we prevent\n # from changing the underlying factor level (the underlying\n # ordering)\n !all(as.integer(dendrogram_panel) == as.integer(panel))) {\n cli_abort(\"you cannot do sub-splitting in dendrogram groups\")\n }\n\n if (self$multiple_tree) {\n branches <- levels(panel)\n data <- vector(\"list\", length(statistics))\n start <- 0L\n for (i in seq_along(data)) {\n tree <- .subset2(statistics, i)\n n <- stats::nobs(tree)\n end <- start + n\n data[[i]] <- fortify_data_frame(\n tree,\n priority = priority,\n center = center,\n type = type,\n leaf_pos = seq(start + 1L, end),\n leaf_braches = rep_len(.subset(branches, i), n),\n reorder_branches = FALSE,\n root = root,\n double = TRUE,\n call = self$call\n )\n start <- end\n }\n data <- lapply(\n list(\n node = data,\n edge = lapply(data, ggalign_attr, \"edge\")\n ),\n function(dat) {\n ans <- vec_rbind(!!!dat, .names_to = \"parent\")\n ans$.panel <- factor(.subset2(ans, \".panel\"), branches)\n ans\n }\n )\n edge <- .subset2(data, \"edge\")\n node <- .subset2(data, \"node\")\n } else {\n if (nlevels(panel) > 1L && type == \"triangle\" && self$in_linear) {\n cli_warn(c(paste(\n \"{.arg type} of {.arg triangle}\",\n \"is not well support for facet dendrogram\"\n ), i = \"will use {.filed rectangle} dendrogram instead\"))\n type <- \"rectangle\"\n }\n data <- fortify_data_frame(\n statistics,\n priority = priority,\n center = center,\n type = type,\n leaf_braches = as.character(panel),\n # panel has been reordered by the dendrogram index\n reorder_branches = FALSE,\n root = root,\n double = TRUE,\n call = self$call\n )\n edge <- ggalign_attr(data, \"edge\")\n node <- data\n }\n\n # add names\n if (!is.null(self$labels)) {\n node$.names <- .subset(self$labels, .subset2(node, \".index\"))\n }\n if (is_horizontal(direction)) {\n edge <- rename(\n edge,\n c(x = \"y\", xend = \"yend\", y = \"x\", yend = \"xend\")\n )\n node <- rename(node, c(x = \"y\", y = \"x\"))\n }\n\n # we do some tricks, since ggplot2 won't remove the attributes\n # we attach the `edge` data\n plot <- gguse_data(plot, ggalign_data_set(node, edge = edge))\n\n if (plot_cut_height && !is.null(height <- .subset2(self, \"height\"))) {\n plot <- plot +\n switch_direction(\n direction,\n ggplot2::geom_vline(\n xintercept = height, linetype = \"dashed\"\n ),\n ggplot2::geom_hline(\n yintercept = height, linetype = \"dashed\"\n )\n )\n }\n position <- .subset2(self, \"position\")\n if (!self$in_linear || # for circular layout\n # for bottom annotation, reverse y-axis\n (!is.null(position) && position == \"bottom\")) {\n plot <- reverse_continuous_axis(plot, \"y\")\n } else if (!is.null(position) && position == \"left\") {\n # for left annotation, reverse x-axis\n plot <- reverse_continuous_axis(plot, \"x\")\n }\n\n # always turn off clip, this is what dendrogram dependends on\n old_coord <- plot$coordinates\n if (!identical(old_coord$clip, \"off\")) {\n # to prevent from changing the input of user.\n plot$coordinates <- ggproto(NULL, old_coord, clip = \"off\")\n }\n plot\n }\n)\n\ntree_one_node <- function(index, label) {\n structure(\n index,\n class = \"dendrogram\",\n leaf = TRUE,\n height = 0,\n label = label,\n members = 1L\n )\n}\n\n# this function won't set the right `midpoint`, but `dendrogram_data` function\n# won't use it, so, it has no hurt to use.\nmerge_dendrogram <- function(parent, children) {\n if (is.null(parent)) { # if no parent, call the merge function from `stats`\n return(Reduce(function(x, y) {\n merge(x, y, adjust = \"none\")\n }, children))\n }\n children_heights <- vapply(\n children, attr, numeric(1L), \"height\",\n USE.NAMES = FALSE\n )\n parent_branch_heights <- tree_branch_heights(parent)\n cutoff_height <- max(children_heights) + min(parent_branch_heights) * 0.5\n .merge_dendrogram <- function(dend) {\n if (stats::is.leaf(dend)) { # base version, leaf should be the index\n .subset2(children, dend)\n } else { # for a branch, we should update the members, height\n attrs <- attributes(dend)\n # we recursively run for each node of current branch\n dend <- lapply(dend, .merge_dendrogram)\n heights <- vapply(dend, attr, numeric(1L), \"height\",\n USE.NAMES = FALSE\n )\n n_members <- vapply(dend, attr, integer(1L), \"members\",\n USE.NAMES = FALSE\n )\n # we update height and members\n attrs$height <- .subset2(attrs, \"height\") + max(heights)\n attrs$members <- sum(n_members)\n attributes(dend) <- attrs\n dend\n }\n }\n ans <- .merge_dendrogram(parent)\n attr(ans, \"cutoff_height\") <- cutoff_height\n ans\n}\n\n#' @importFrom stats reorder\nreorder_dendrogram <- function(dend, wts) {\n if (inherits(dend, \"hclust\")) dend <- stats::as.dendrogram(dend)\n reorder(x = dend, wts = wts, agglo.FUN = mean)\n}\n\ntree_branch_heights <- function(dend) {\n if (stats::is.leaf(dend)) {\n return(NULL)\n } else {\n c(\n attr(dend, \"height\"),\n unlist(lapply(dend, tree_branch_heights), FALSE, FALSE)\n )\n }\n}\n"], ["/ggalign/R/alignpatch-patch.R", "#' Convert Object into a Grob\n#'\n#' The `patch()` function is used by [`ggwrap()`] and [inset()] to convert\n#' objects into a [`grob`][grid::grob].\n#'\n#' @param x An object to be converted into a [`grob`][grid::grob].\n#' @param ... Additional arguments passed to specific methods.\n#' @return A [`grob`][grid::grob] object.\n#' @eval rd_collect_family(\"patch\", \"`patch` method collections\")\n#' @export\n#' @keywords internal\npatch <- function(x, ...) {\n UseMethod(\"patch\")\n}\n\n# Following methods much are copied from `cowplot` or `ggplotify`\n#' @export\npatch.default <- function(x, ...) {\n cli_abort(\"Cannot make grob from {.obj_type_friendly {x}}\")\n}\n\n#' @inherit patch title description return\n#' @inheritParams patch\n#' @param ... Not used currently.\n#' @family patch\n#' @export\npatch.grob <- function(x, ...) {\n rlang::check_dots_empty()\n x\n}\n\n#' @importFrom grid gTree\n#' @export\n#' @rdname patch.grob\npatch.gList <- function(x, ...) {\n rlang::check_dots_empty()\n # gLists need to be wrapped in a gTree\n gTree(children = x)\n}\n\n#' @importFrom ggplot2 ggplotGrob\n#' @inherit patch.grob\n#' @seealso [ggplot][ggplot2::ggplot]\n#' @family patch\n#' @export\npatch.ggplot <- function(x, ...) {\n ggplotGrob(x, ...)\n}\n\n#' @inherit patch.grob\n#' @seealso\n#' - [`patch_titles()`]\n#' - [`inset()`]\n#' - [`ggwrap()`]\n#' @family patch\n#' @export\npatch.patch_ggplot <- function(x, ...) {\n ggalignGrob(x, ...)\n}\n\n#' @inherit patch.grob\n#' @seealso [`alignpatches`][align_plots]\n#' @family patch\n#' @export\npatch.alignpatches <- function(x, ...) {\n ggalignGrob(x, ...)\n}\n\n#' @inherit patch.grob\n#' @seealso [`patchwork`][patchwork::patchworkGrob]\n#' @family patch\n#' @export\npatch.patchwork <- function(x, ...) {\n rlang::check_installed(\"patchwork\", \"to make grob from patchwork\")\n patchwork::patchworkGrob(x, ...)\n}\n\n#' @inherit patch.grob\n#' @seealso [`patch`][patchwork::patchGrob]\n#' @family patch\n#' @export\npatch.patch <- function(x, ...) {\n rlang::check_installed(\"patchwork\", \"to make grob from patch\")\n patchwork::patchGrob(x, ...)\n}\n\n#' @inherit patch.grob\n#' @param ... Graphical Parameters passed on to [par()][graphics::par].\n#' @inheritParams gridGraphics::echoGrob\n#' @seealso [`plot()`]\n#' @family patch\n#' @export\npatch.formula <- function(x, ..., device = NULL, name = NULL) {\n rlang::check_installed(\"gridGraphics\", \"to make grob from base plot\")\n gp <- graphics::par(..., no.readonly = TRUE)\n gridGraphics::echoGrob(\n function() {\n old_gp <- graphics::par(no.readonly = TRUE)\n graphics::par(gp)\n on.exit(try(graphics::par(old_gp)))\n suppressMessages(eval(x[[2]], attr(x, \".Environment\")))\n invisible(NULL)\n },\n name = name,\n device = device %||% offscreen\n )\n}\n\n#' @export\n#' @rdname patch.formula\npatch.function <- function(x, ..., device = NULL, name = NULL) {\n rlang::check_installed(\"gridGraphics\", \"to make grob from base plot\")\n gp <- graphics::par(..., no.readonly = TRUE)\n gridGraphics::echoGrob(\n function() {\n old_gp <- graphics::par(no.readonly = TRUE)\n graphics::par(gp)\n on.exit(try(graphics::par(old_gp)))\n suppressMessages(x())\n invisible(NULL)\n },\n name = name,\n device = device %||% offscreen\n )\n}\n\n#' @inherit patch.grob\n#' @inheritParams gridGraphics::echoGrob\n#' @seealso [`recordPlot()`][grDevices::recordPlot]\n#' @family patch\n#' @export\npatch.recordedplot <- function(x, ..., device = NULL) {\n rlang::check_installed(\"gridGraphics\", \"to make grob from recordedplot\")\n rlang::check_dots_empty()\n gridGraphics::echoGrob(x, device = device %||% offscreen)\n}\n\noffscreen <- function(width, height) {\n if (requireNamespace(\"ragg\", quietly = TRUE)) {\n ragg::agg_capture(width = width, height = height, units = \"in\")\n grDevices::dev.control(\"enable\")\n } else {\n grDevices::pdf(NULL, width = width, height = height)\n grDevices::dev.control(\"enable\")\n }\n}\n\n#' @inherit patch.grob\n#' @inheritDotParams grid::grid.grabExpr -expr -device\n#' @inheritParams grid::grid.grabExpr\n#' @seealso [`trellis`][lattice::trellis.object]\n#' @family patch\n#' @export\npatch.trellis <- function(x, ..., device = NULL) {\n grid::grid.grabExpr(expr = print(x), ..., device = device %||% offscreen)\n}\n\n#' @inherit patch.grob\n#' @param ... Additional arguments passed to [draw()][ComplexHeatmap::draw].\n#' @inheritParams grid::grid.grabExpr\n#' @seealso\n#' - [`Heatmap()`][ComplexHeatmap::Heatmap]\n#' - [`HeatmapAnnotation()`][ComplexHeatmap::HeatmapAnnotation]\n#' @family patch\n#' @export\npatch.Heatmap <- function(x, ..., device = NULL) {\n rlang::check_installed(\n \"ComplexHeatmap\",\n sprintf(\"to make grob from %s plot\", obj_type_friendly(x))\n )\n draw <- getExportedValue(\"ComplexHeatmap\", \"draw\")\n grid::grid.grabExpr(\n expr = draw(object = x, ...),\n device = device %||% offscreen\n )\n}\n\n#' @export\n#' @rdname patch.Heatmap\npatch.HeatmapList <- patch.Heatmap\n\n#' @export\n#' @rdname patch.Heatmap\npatch.HeatmapAnnotation <- patch.HeatmapList\n\n#' @inherit patch.grob\n#' @seealso [`pheatmap()`][pheatmap::pheatmap]\n#' @family patch\n#' @export\npatch.pheatmap <- function(x, ...) {\n rlang::check_dots_empty()\n .subset2(x, \"gtable\")\n}\n"], ["/ggalign/R/craft-cross-none.R", "#' Reset layout ordering and panel group\n#'\n#' @param data The dataset to use for the layout. By default,\n#' [`fortify_matrix()`] will convert the data to a matrix. This argument\n#' allows you to change the layout data. If not specified, the original data\n#' will be used.\n#' @param ... <[dyn-dots][rlang::dyn-dots]> Additional arguments passed to\n#' [`fortify_matrix()`].\n#' @param inherit_index A boolean value indicating whether to inherit the\n#' ordering index. If `TRUE`, will match the layout ordering index with the\n#' data names.\n#' @param inherit_panel A boolean value indicating whether to inherit the\n#' panel group. If `TRUE`, will match the layout panel with the data names.\n#' @param inherit_nobs A boolean value indicating whether to inherit the\n#' number of observations (nobs). If `TRUE`, the `data` input must be\n#' compatible with the layout data.\n#' @export\ncross_none <- function(data = waiver(), ...,\n inherit_index = NULL,\n inherit_panel = NULL,\n inherit_nobs = NULL) {\n cross(CrossNone,\n data = data, data_params = list2(...), plot = NULL,\n active = new_active(use = FALSE),\n schemes = default_schemes(),\n inherit_index = inherit_index,\n inherit_panel = inherit_panel,\n inherit_nobs = inherit_nobs\n )\n}\n\n#' @importFrom ggplot2 ggproto ggproto_parent\n#' @include craft-cross-.R\nCrossNone <- ggproto(\"CrossNone\", CraftCross)\n"], ["/ggalign/R/craft-align-.R", "#' Create a New `CraftBox` Object with `CraftAlign` craftsman\n#'\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' An `CraftAlign` object interacts with the `Layout` object to reorder or split\n#' observations and, in some cases, add plot components to the `Layout`.\n#'\n#' @param align An `CraftAlign` object.\n#' @param ... Additional fields passed to the `align` object.\n#' @param plot A ggplot object.\n#' @inheritParams ggalign\n#' @param schemes Options for `schemes`:\n#' - `NULL`: Used when `align` do not add a plot.\n#' - [`waiver()`][ggplot2::waiver]: Try to infer `schemes` based on `data`.\n#' @param call The `call` used to construct the `align` object, for\n#' reporting messages.\n#'\n#' @section Discrete Axis Alignment:\n#' It is important to note that we consider rows as observations, meaning\n#' `vec_size(data)`/`NROW(data)` must match the number of observations along the\n#' axis used for alignment (x-axis for a vertical stack layout, y-axis for a\n#' horizontal stack layout).\n#'\n#' @return A new `CraftBox` object.\n#' @examples\n#' align_dendro()\n#' @importFrom rlang caller_call current_call\n#' @importFrom ggplot2 ggproto\n#' @export\n#' @keywords internal\nalign <- function(align, data = NULL, ..., plot = NULL,\n size = NULL, schemes = NULL, no_axes = NULL,\n active = NULL, call = caller_call()) {\n if (override_call(call)) {\n call <- current_call()\n }\n\n # check arguments ---------------------------------------------\n data <- allow_lambda(data)\n no_axes <- no_axes %||%\n getOption(sprintf(\"%s.align_no_axes\", pkg_nm()), default = TRUE)\n schemes <- schemes %|w|% default_schemes(data)\n\n new_craftbox(\n craftsman = align,\n\n # additional field for `align` object\n no_axes = no_axes,\n ...,\n\n # Following fields will be initialzed when added into the layout\n # and will be saved and accessed across the plot rendering process\n direction = NULL,\n position = NULL,\n data = NULL, # Used to save the modified `input_data`\n statistics = NULL, # `$compute` method\n labels = NULL, # the original `vec_names()` of the `input_data`\n\n # the input data\n input_data = data,\n\n # object slots\n plot = plot,\n active = active,\n size = size,\n schemes = schemes,\n\n # call\n call = call\n )\n}\n\n#' @details\n#' Each of the `Align*` objects is just a [`ggproto()`][ggplot2::ggproto]\n#' object, descended from the top-level `CraftAlign`, and each implements\n#' various methods and fields.\n#'\n#' To create a new type of `Align*` object, you typically will want to\n#' override one or more of the following:\n#' - `setup_params`: Prepare parameter or check parameters used by this plot.\n#' - `setup_data`: Prepare data used by this plot.\n#' - `compute`: A method used to compute statistics.\n#' - `align`: A method used to group observations into panel or reorder\n#' observations.\n#' - `draw`: A method used to draw the plot. Must return a `ggplot` object.\n#' @importFrom ggplot2 ggproto\n#' @export\n#' @format NULL\n#' @usage NULL\n#' @rdname align\n#' @include craftbox-.R\nCraftAlign <- ggproto(\"CraftAlign\", Craftsman,\n interact_layout = function(self, layout) {\n # check plot is compatible with the layout\n if (is_layout_continuous(layout)) {\n layout_name <- self$layout_name\n # `CraftAlign` object is special for discrete variables\n cli_abort(c(\n sprintf(\"Cannot add %s to %s\", object_name(self), layout_name),\n i = sprintf(\"%s cannot align discrete variables\", layout_name)\n ))\n }\n layout\n },\n setup_design = function(self, design) {\n old_panel <- .subset2(design, \"panel\")\n old_index <- .subset2(design, \"index\")\n # prepare the data -------------------------------\n # compute statistics ---------------------------------\n self$statistics <- self$compute(panel = old_panel, index = old_index)\n\n # make the new layout -------------------------------\n panel_and_index <- self$align(panel = old_panel, index = old_index)\n\n # check panel\n layout_name <- self$layout_name\n nobs <- .subset2(design, \"nobs\")\n new_panel <- .subset2(panel_and_index, 1L)\n if (!is.null(new_panel)) {\n if (!is.atomic(new_panel)) {\n cli_abort(c(\n sprintf(\n \"invalid layout panels defined by %s\",\n object_name(self)\n ),\n i = \"layout panels must be an atomic vector\"\n ))\n } else if (anyNA(new_panel)) {\n cli_abort(sprintf(\n \"layout panels defined by %s contain `NA`\",\n object_name(self)\n ))\n } else if (is.null(nobs)) {\n # we have defined panel, but don't define the `nobs`\n cli_abort(sprintf(\n \"%s defined the panels but not define {.field nobs}\", object_name(self)\n ))\n } else if (length(new_panel) != nobs) {\n # we have defined panel, but don't define the `nobs`\n cli_abort(sprintf(\n \"layout panels defined by %s (nobs: %d) is not compatible with the nobs: %d\",\n object_name(self), length(new_panel), nobs\n ))\n } else if (!is.null(old_panel) && !(new_panel %nest% old_panel)) {\n cli_abort(sprintf(\n \"%s disrupt the previously established panel groups of %s\",\n object_name(self), layout_name\n ))\n }\n } else if (!is.null(old_panel)) {\n # push developer to reset the panel in the layout\n cli_abort(c(\n sprintf(\"invalid %s\", object_name(self)),\n i = sprintf(\n \"%s reset the {.field panel}, but don't change the {.field panel} of the layout\", object_name(self)\n )\n ))\n }\n panel <- new_panel\n if (!is.null(panel) && !is.factor(panel)) panel <- factor(panel)\n\n # check index\n new_index <- .subset2(panel_and_index, 2L)\n if (!is.null(new_index)) {\n if (!is.integer(new_index)) {\n cli_abort(c(\n sprintf(\n \"invalid layout ordering index defined by %s\", object_name(self)\n ),\n i = \"layout ordering index must be an integer\"\n ))\n } else if (anyNA(new_index)) {\n cli_abort(sprintf(\n \"layout ordering index defined by %s contain `NA`\",\n object_name(self)\n ))\n } else if (is.null(nobs)) {\n # we have defined panel, but don't define the `nobs`\n cli_abort(sprintf(\n \"%s defined the ordering index but not define nobs\", object_name(self)\n ))\n } else if (length(new_index) != nobs) {\n # we have defined index, but don't define the `nobs`\n cli_abort(sprintf(\n \"layout ordering index defined by %s (nobs: %d) is not compatible with the nobs (%d)\",\n object_name(self), length(new_index), nobs\n ))\n }\n } else if (!is.null(old_index)) {\n # push developer to reset the `index` in the layout\n cli_abort(c(\n sprintf(\"invalid %s\", object_name(self)),\n i = sprintf(\n \"%s reset the {.field index}, but don't change the {.field index} of the layout\",\n object_name(self)\n )\n ))\n }\n index <- new_index\n\n # we always make the index following the panel\n if (!is.null(panel) && !is.null(index)) {\n index <- reorder_index(panel, index)\n }\n\n # we always prevent from reordering twice.\n if (!is.null(old_index) && !all(old_index == index)) {\n cli_abort(sprintf(\n \"%s disrupt the previously established ordering index of %s\",\n object_name(self), layout_name\n ))\n }\n discrete_design(panel, index, nobs)\n },\n\n # Following fields should be defined for the new `CraftAlign` object.\n # argument name in these function doesn't matter.\n compute = function(self, panel, index) NULL,\n\n # Group heamap row/column and reorder, Must return a list of 2:\n # - the first one should be the groups for heatmap row/column, the factor\n # levels will determine the panel order, so it should always follow the\n # index if you don't want the panel levels break the index. See\n # `AlignDendro` for example.\n # - the second one should be the heatmap row/column order index, and will\n # determine the order in each grouped panel.\n #\n # See `$setup_design()` method for details\n # There will have following situations (the input is old index and old\n # panel):\n #\n # 1. old index is NULL and old panel is NULL, there is nothing wrong to\n # define any new index or panel\n # 2. old index is `NULL` and old panel is not `NULL`, in this way, new\n # index must follow the old panel.\n #\n # For new `CraftAlign` object, which can do clustering, we must\n # abort, if it can not do sub-clustering, if it can do sub-clustering, we\n # should know if we want to change the order between the groups (panel\n # levels).\n #\n # Please check `AlignGroup` object and `CraftAlign` object\n # For dendrogram, it can do sub-clustering within each group, it also\n # allows reordering between groups (it provide `reorder_group` argument),\n # so the new panel levels may be not the same with old panel\n #\n # For `CraftAlign` object reordering the heatmap rows/columns.\n # usually we provide a `strict` argument, to allow reorder heatmap within\n # group only. See `AlignOrder2`.\n #\n # 3. old index is not `NULL`, no matter whether old panel is `NULL` or not,\n # in this way, we should always ensure the new index won't change the old\n # index, this will be checked in `$setup_design()` method.\n align = function(self, panel, index) list(panel, index),\n\n # let Craftsman to add schemes and theme acoordingly\n finish_plot = function(self, plot, schemes, theme) {\n ggproto_parent(AlignGg, self)$finish_plot(plot, schemes, theme)\n },\n summary = function(self, plot) {\n header <- ggproto_parent(Craftsman, self)$summary(plot)\n oo <- self$summary_align()\n nms <- c(\"plot\", \"reorder\", \"split\")\n content <- c(\n if (is.null(plot)) \"no\" else \"yes\",\n if (isTRUE(oo[1L])) \"yes\" else \"no\",\n if (isTRUE(oo[2L])) \"yes\" else \"no\"\n )\n nms <- format(nms, justify = \"right\")\n content <- format(content, justify = \"left\")\n content <- paste0(\" \", nms, \": \", content)\n c(header, content)\n },\n\n # Summary the action of `Align`\n #\n # @return A logical vector of length 2, indicating:\n # - Whether the object reorders the observations.\n # - Whether the object splits the observations into groups.\n # @keywords internal\n summary_align = function(self) c(FALSE, FALSE)\n)\n"], ["/ggalign/R/utils.R", "# `vec_rep`\nrecycle_whole <- function(x, len) {\n out <- x %% len\n if (out == 0L) len else out\n}\n\n# `vec_rep_each`\nrecycle_each <- function(x, len) {\n (x - 1L) %/% len + 1L\n}\n\n#' @importFrom utils modifyList\nupdate_non_waive <- function(old, new, keep_null = TRUE) {\n modifyList(old,\n new[!vapply(new, is.waive, logical(1L), USE.NAMES = FALSE)],\n keep.null = keep_null\n )\n}\n\nis_s3 <- function(x) is.object(x) && !isS4(x) && !inherits(x, \"R6\")\n\n#' @importFrom rlang names2\nnames_or_index <- function(x) {\n nms <- names2(x)\n empty <- nms == \"\"\n nms[empty] <- seq_along(x)[empty]\n nms\n}\n\n#################################################################\n#' Read Example Data\n#'\n#' This function reads example data from the file. If no file is specified, it\n#' returns a list of available example files.\n#'\n#' @param file A string representing the name of the example file to be read. If\n#' `NULL`, the function will return a list of available example file names.\n#' @return If `file` is `NULL`, returns a character vector of available example\n#' file names. Otherwise, returns the contents of the specified example file,\n#' read as an R object.\n#' @examples\n#' read_example()\n#' @export\nread_example <- function(file = NULL) {\n if (is.null(file)) {\n dir(pkg_extdata())\n } else {\n readRDS(pkg_extdata(file, mustWork = TRUE))\n }\n}\n\nwith_options <- function(code, ...) {\n opts <- options(...)\n on.exit(options(opts))\n force(code)\n}\n\n#' @param ans Whether to assign the final results into the 'ans' variable.\n#' @noRd\nfn_body_append <- function(fn, ..., ans = FALSE) {\n args <- rlang::fn_fmls(fn)\n body <- rlang::fn_body(fn)\n body <- as.list(body)\n if (ans) body[[length(body)]] <- rlang::expr(ans <- !!body[[length(body)]])\n body <- as.call(c(body, rlang::enexprs(...)))\n rlang::new_function(args, body)\n}\n\n# This will work with most things but be aware that it might fail with some\n# complex objects. For example, according to `?S3Methods`, calling foo on\n# matrix(1:4, 2, 2) would try `foo.matrix`, then `foo.numeric`, then\n# `foo.default`; whereas this code will just look for `foo.matrix` and\n# `foo.default`.\n#' @importFrom utils getS3method\n#' @importFrom methods extends\nhas_method <- function(x, f, inherit = TRUE, default = inherit) {\n x_class <- class(x)\n if (inherit) {\n if (isS4(x)) x_class <- extends(x_class)\n if (default) x_class <- c(x_class, \"default\")\n } else {\n x_class <- .subset(x_class, 1L)\n }\n for (cls in x_class) {\n if (!is.null(getS3method(f, cls, optional = TRUE))) {\n return(TRUE)\n }\n }\n return(FALSE)\n}\n\n#' For functions with a `call` argument, we check if the call originates from\n#' the current package. If it does, we use the caller's call; if not, we use the\n#' current call directly. Used by `align()` and `free()`\n#' @noRd\n#' @importFrom utils packageName\noverride_call <- function(call = NULL) {\n # if no caller call\n if (is.null(call) || is.function(f <- .subset2(call, 1L))) {\n return(TRUE)\n }\n # if call from the current package\n !identical(\n packageName(environment(eval(f))),\n pkg_nm()\n )\n}\n\n# library(data.table)\n# library(vctrs)\n# `%nest_unique%` <- function(x, y) {\n# ans <- new_data_frame(list(x = x, y = y))\n# ans <- unique(ans)\n# !anyDuplicated(ans$x)\n# }\n# `%nest_vctrs%` <- function(x, y) {\n# ans <- new_data_frame(list(x = x, y = y))\n# ans <- vec_unique(ans)\n# !vec_duplicate_any(.subset2(ans, \"x\"))\n# }\n# `%nest_vctrs_loc%` <- function(x, y) {\n# # we don't check the inputs for performance\n# loc <- vec_unique_loc(new_data_frame(list(x = x, y = y)))\n# !vec_duplicate_any(vec_slice(x, loc))\n# }\n# `%nest_data_table%` <- function(x, y) {\n# ans <- data.table(x = x, y = y)\n# ans <- unique(ans)\n# !anyDuplicated(.subset2(ans, \"x\"))\n# }\n# `%nest_split%` <- function(x, y) {\n# all(lengths(lapply(split(y, x), unique)) == 1L)\n# }\n# `%nest_table%` <- function(x, y) {\n# all(rowSums(table(x, y) > 0L) == 1L)\n# }\n# foo <- rep(seq(10^4L / 2L), each = 4)\n# bar <- rep(seq(10^4L), each = 2)\n# bench::mark(\n# nest_unique = bar %nest_unique% foo,\n# nest_vctrs = bar %nest_vctrs% foo,\n# nest_vctrs_loc = bar %nest_vctrs_loc% foo,\n# nest_data_table = bar %nest_data_table% foo,\n# nest_split = bar %nest_split% foo,\n# nest_table = bar %nest_table% foo,\n# )\n#> Warning: Some expressions had a GC in every iteration; so filtering is\n#> disabled.\n#> # A tibble: 6 x 6\n#> expression min median `itr/sec` mem_alloc `gc/sec`\n#> \n#> 1 nest_unique 5.37ms 7.49ms 134. 1.33MB 69.2\n#> 2 nest_vctrs 200.3us 214.57us 3591. 754.7KB 6.00\n#> 3 nest_vctrs_loc 193.99us 207.29us 4490. 706.95KB 6.00\n#> 4 nest_data_table 402.71us 459.55us 1918. 985.25KB 4.00\n#> 5 nest_split 11.87ms 14.08ms 69.8 1.15MB 54.3\n#> 6 nest_table 183.52ms 189.87ms 5.20 576.35MB 8.67\n`%nest%` <- function(x, y) {\n # we don't check the inputs for performance\n loc <- vec_unique_loc(new_data_frame(list(x = x, y = y)))\n !vec_duplicate_any(vec_slice(x, loc))\n}\n\nsave_png <- function(code, width = 400L, height = 400L) {\n path <- tempfile(fileext = \".png\")\n grDevices::png(path, width = width, height = height)\n on.exit(grDevices::dev.off())\n print(code)\n path\n}\n\nadd_class <- function(x, ...) {\n if (is.null(x)) return(x) # styler: off\n class(x) <- vec_unique(c(..., class(x)))\n x\n}\n\nremove_class <- function(x, ...) {\n oldClass(x) <- vec_set_difference(oldClass(x), c(...))\n x\n}\n\n###########################################################\nswitch_position <- function(position, x, y) {\n switch(position,\n top = ,\n bottom = x,\n left = ,\n right = y\n )\n}\n\nto_direction <- function(position) {\n switch_position(position, \"vertical\", \"horizontal\")\n}\n\nis_vertical <- function(direction) direction == \"vertical\"\n\nis_horizontal <- function(direction) direction == \"horizontal\"\n\nswitch_direction <- function(direction, h, v) {\n if (is_horizontal(direction)) {\n h\n } else {\n v\n }\n}\n\nto_coord_axis <- function(direction) {\n switch_direction(direction, \"y\", \"x\")\n}\n\nto_matrix_axis <- function(direction) {\n switch_direction(direction, \"row\", \"column\")\n}\n\n##########################################################\ndata_frame0 <- function(...) data_frame(..., .name_repair = \"minimal\")\n\nas_data_frame0 <- function(data, ...) {\n as.data.frame(\n x = data, ...,\n make.names = FALSE,\n stringsAsFactors = FALSE,\n fix.empty.names = FALSE\n )\n}\n\nquickdf <- function(x) {\n class(x) <- \"data.frame\"\n attr(x, \"row.names\") <- .set_row_names(length(.subset2(x, 1L)))\n x\n}\n\nfct_rev <- function(x) {\n ans <- as.factor(x)\n factor(ans, levels = rev(levels(ans)))\n}\n\nreverse_trans <- function(x) sum(range(x, na.rm = TRUE)) - x\n\nfclass <- function(x) .subset(class(x), 1L)\n\nis_scalar <- function(x) length(x) == 1L\n\nis_scalar_numeric <- function(x) length(x) == 1L && is.numeric(x)\n"], ["/ggalign/R/layout-heatmap-oncoplot.R", "#' Create an OncoPrint\n#'\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' The `ggoncoplot()` function generates `oncoPrint` visualizations that display\n#' genetic alterations in a matrix format. This function is especially useful\n#' for visualizing complex genomic data, such as mutations, copy number\n#' variations, and other genomic alterations in cancer research.\n#'\n#' @details\n#' `ggoncoplot()` is a wrapper around the [`ggheatmap()`] function, designed to\n#' simplify the creation of `OncoPrint`-style visualizations. The function\n#' automatically processes the input character matrix by splitting the encoded\n#' alterations (delimited by `r oxford_or(c(\";\", \":\", \",\", \"|\"))`) into\n#' individual genomic events and unnesting the columns for visualization.\n#'\n#' @param data A character matrix which encodes the alterations, you can use\n#' `r oxford_or(c(\";\", \":\", \",\", \"|\"))` to separate multiple alterations.\n#' @inheritParams heatmap_layout\n#' @param map_width,map_height A named numeric value defines the width/height of\n#' each alterations.\n#'\n#' @param reorder_row A boolean value indicating whether to reorder the rows\n#' based on the frequency of alterations. You can set this to `FALSE`, then add\n#' `align_order(~rowSums(!is.na(.x)), reverse = TRUE)` to achieve the same\n#' result. You may also need to set `strit = FALSE` in [`align_order()`] if\n#' there are already groups.\n#'\n#' @param reorder_column A boolean value indicating whether to reorder the\n#' columns based on the characteristics of the alterations. You can set this to\n#' `FALSE`, then add `align_order2(memo_order)` to achieve the same result. You\n#' may also need to set `strit = FALSE` in [`align_order2()`] if there are\n#' already groups.\n#'\n#' @param remove_duplicates A logical value indicating whether to remove\n#' duplicated variants within the same cell.\n#'\n#' @param filling Same as [`ggheatmap()`], but only `\"tile\"` can be used.\n#' @examples\n#' # A simple example from `ComplexHeatmap`\n#' mat <- read.table(textConnection(\n#' \"s1,s2,s3\n#' g1,snv;indel,snv,indel\n#' g2,,snv;indel,snv\n#' g3,snv,,indel;snv\"\n#' ), row.names = 1, header = TRUE, sep = \",\", stringsAsFactors = FALSE)\n#'\n#' ggoncoplot(mat, map_width = c(snv = 0.5), map_height = c(indel = 0.9)) +\n#' guides(fill = \"none\") +\n#' anno_top(size = 0.5) +\n#' ggalign() +\n#' geom_bar(aes(fill = value), data = function(x) {\n#' subset(x, !is.na(value))\n#' }) +\n#' anno_right(size = 0.5) +\n#' ggalign() +\n#' geom_bar(aes(fill = value), orientation = \"y\", data = function(x) {\n#' subset(x, !is.na(value))\n#' }) &\n#' scale_fill_brewer(palette = \"Dark2\", na.translate = FALSE)\n#' @inherit heatmap_layout return\n#' @importFrom ggplot2 aes\n#' @export\nggoncoplot <- function(data = NULL, mapping = aes(), ...,\n map_width = NULL, map_height = NULL,\n reorder_row = reorder_column,\n reorder_column = TRUE,\n remove_duplicates = FALSE,\n width = NA, height = NA, filling = waiver(),\n theme = NULL, active = NULL) {\n UseMethod(\"ggoncoplot\")\n}\n\n#' @export\nggoncoplot.NULL <- function(data = NULL, mapping = aes(), ...) {\n cli_abort(\"{.fn ggoncoplot} only accept a valid character matrix\")\n}\n\n#' @export\nggoncoplot.functon <- ggoncoplot.NULL\n\n#' @export\nggoncoplot.formula <- ggoncoplot.functon\n\n#' @importFrom ggplot2 aes\n#' @importFrom rlang arg_match0\n#' @export\n#' @rdname ggoncoplot\nggoncoplot.default <- function(data = NULL, mapping = aes(), ...,\n map_width = NULL, map_height = NULL,\n reorder_row = reorder_column,\n reorder_column = TRUE,\n remove_duplicates = FALSE,\n width = NA, height = NA, filling = waiver(),\n theme = NULL, active = NULL) {\n # prepare the matrix\n data <- fortify_matrix(data = data, ...)\n if (!is.character(data)) {\n cli_abort(\"{.arg data} must be a character matrix\")\n }\n\n assert_bool(reorder_column)\n assert_bool(reorder_row)\n assert_bool(remove_duplicates)\n\n # convert empty string into NA\n data <- trimws(data, whitespace = \"[\\\\h\\\\v]\")\n data[data == \"\"] <- NA_character_\n\n # check filling\n if (isTRUE(filling) || is.waive(filling)) {\n filling <- \"tile\"\n } else if (isFALSE(filling)) {\n filling <- NULL\n } else if (!is.null(filling)) {\n filling <- arg_match0(filling, c(\"tile\", \"raster\"))\n if (filling == \"raster\") {\n cli_warn(\"Cannot use {.fn geom_raster} in oncoplot\")\n filling <- \"tile\"\n }\n }\n\n # prepare the plot data action\n pdata <- function(data) {\n vars <- strsplit(data$value, split = \"\\\\s*[;:,|]\\\\s*\", perl = TRUE)\n if (remove_duplicates) vars <- lapply(vars, vec_unique)\n lvls <- ggalign_lvls_get(data)\n data <- vec_rep_each(data, list_sizes(vars))\n value <- unlist(vars, recursive = FALSE, use.names = FALSE)\n if (!is.null(lvls)) value <- factor(value, levels = lvls)\n data$value <- value\n data\n }\n\n # draw the oncoplot\n ans <- heatmap_layout(\n data = data, mapping = mapping,\n width = width, height = height,\n theme = theme, active = active, filling = NULL\n ) -\n # set the default `scheme_data()`\n scheme_data(data = pdata)\n\n # prepare counts matrix to reorder the column or rows\n if (reorder_column || reorder_row) {\n counts <- !is.na(data)\n storage.mode(counts) <- \"integer\"\n weights <- rowSums(counts)\n row_index <- order(weights, decreasing = TRUE)\n }\n\n if (reorder_row) {\n ans <- ans + anno_left() + align_order(row_index, reverse = TRUE)\n }\n if (reorder_column) {\n column_scores <- .memo_order(vec_slice(counts, row_index))\n ans <- ans +\n anno_top() +\n align_order(order(column_scores, decreasing = TRUE))\n }\n\n # reset the active context\n ans <- ans + quad_active()\n if (!is.null(filling)) {\n # we always make sure heatmap body has such action data\n ans <- ans + scheme_data(data = pdata)\n\n # set mapping for width and height\n tile_mapping <- aes(\n .data$.x, .data$.y,\n fill = .data$value,\n width = replace_na(map_width[.data$value], 1),\n height = replace_na(map_height[.data$value], 1)\n )\n if (!is.null(map_width)) {\n if (!rlang::is_named(map_width) || !is.numeric(map_width)) {\n cli_abort(\"{.arg map_width} must be a named numeric\")\n }\n } else {\n tile_mapping$width <- NULL\n }\n if (!is.null(map_height)) {\n if (!rlang::is_named(map_height) || !is.numeric(map_height)) {\n cli_abort(\"{.arg map_height} must be a named numeric\")\n }\n } else {\n tile_mapping$height <- NULL\n }\n # check if user has provided and manual fill mapping\n if (!is.null(.subset2(ans@plot$mapping, \"fill\"))) {\n tile_mapping$fill <- NULL\n }\n ans <- ans + ggplot2::geom_tile(tile_mapping)\n }\n ans\n}\n\n#' Sort matrix for better visualization\n#'\n#' Helper function used to order the Oncoplot samples. Typically, you would use\n#' this in combination with [`align_order2()`], e.g.,\n#' `align_order2(memo_order)`.\n#'\n#' @param x A matrix, where `NA` values will be treated as empty.\n#' @return A vector of ordering weights.\n#' @export\nmemo_order <- function(x) {\n # For `align_order2()`, rows are considered as the observations\n # `.memo_order` will regard the columns as the observations\n .memo_order(t(x), counts = FALSE, reorder_rows = TRUE)\n}\n\n# Following code is modified from\n# \n.memo_order <- function(x, counts = TRUE, reorder_rows = FALSE) {\n if (!isTRUE(counts)) {\n x <- !is.na(x)\n storage.mode(x) <- \"integer\"\n }\n if (isTRUE(reorder_rows)) {\n row_index <- order(rowSums(x), decreasing = TRUE)\n x <- vec_slice(x, row_index)\n }\n structure(\n apply(x, 2L, function(x) {\n score <- 2^(length(x) - seq_along(x))\n score[x == 0L] <- 0\n sum(score)\n }),\n class = \"memo_weights\"\n )\n}\n\n#' @export\n#' @rdname order2\norder2.memo_weights <- function(x) order(x, decreasing = TRUE)\n"], ["/ggalign/R/layout-align.R", "#' Set Expansion for the Layout\n#'\n#' @description\n#' To align axes, it is important to keep the expansion consistent across all\n#' plots in the layout. You can add a `layout_expand` object to the layout. For\n#' the `quad_layout()` function, you must specify `x` and `y` arguments. For\n#' other layouts, you can pass the expansion values using `...` directly.\n#'\n#' @param ... A list of range expansion constants, used to add padding around\n#' the data to ensure they are placed some distance away from the axes. Use the\n#' convenience function [`expansion()`][ggplot2::expansion()] to generate the\n#' values.\n#' @param x,y Same as `...`, but specifically for `quad_layout()`.\n#'\n#' @importFrom rlang list2\n#' @keywords internal\nlayout_expand <- function(..., x = waiver(), y = waiver()) {\n if (...length() > 0L && (!is.waive(x) || !is.waive(y))) {\n cli_abort(\n \"Cannot mix the usage of {.arg ...} with {.arg x}/{.arg y} argument\"\n )\n }\n if (...length() > 0L) {\n ans <- list2(...)\n names(ans) <- NULL\n } else {\n ans <- list(x = x, y = y)\n }\n structure(ans, class = \"ggalign_layout_expand\")\n}\n\n#' Set continuous limits for the layout\n#'\n#' @description\n#' To align continuous axes, it is important to keep the limits consistent\n#' across all plots in the layout. You can set the limits by passing a function\n#' directly to the `limits` or `xlim`/`ylim` argument, using `...` only.\n#' Alternatively, you can add a `continuous_limits()` object to the layout. For\n#' the `quad_layout()` function, you must specify `x`/`y` arguments. For other\n#' layouts, you should pass the limits using `...` directly.\n#'\n#' @param ... A list of two numeric values, specifying the left/lower limit and\n#' the right/upper limit of the scale.\n#' @inheritParams layout_expand\n#' @importFrom rlang list2\n#' @export\ncontinuous_limits <- function(..., x = waiver(), y = waiver()) {\n if (...length() > 0L && (!is.waive(x) || !is.waive(y))) {\n cli_abort(\n \"Cannot mix the usage of {.arg ...} with {.arg x}/{.arg y} argument\"\n )\n }\n if (...length() > 0L) {\n ans <- list2(...)\n names(ans) <- NULL\n } else {\n ans <- list(x = x, y = y)\n }\n structure(ans, class = c(\"continuous_limits\", \"layout_design\"))\n}\n\n# layout params are used to align the observations\ndiscrete_design <- function(panel = NULL, index = NULL, nobs = NULL) {\n structure(\n list(panel = panel, index = index, nobs = nobs),\n class = c(\"discrete_design\", \"layout_design\")\n )\n}\n\n################################################################\nis_continuous_design <- function(x) {\n is.null(x) || inherits(x, \"continuous_limits\")\n}\n\nis_discrete_design <- function(x) inherits(x, \"discrete_design\")\n\n#' Layout can align ordinal variable or continuous variable\n#'\n#' @param x A `LayoutProto` object.\n#' @noRd\nis_layout_discrete <- function(x, ...) UseMethod(\"is_layout_discrete\")\n\nis_layout_continuous <- function(x, ...) UseMethod(\"is_layout_continuous\")\n\n################################################################\n# Initialize the index and panel\n# Reorder the panel based the ordering index and\nsetup_design <- function(design) {\n # for continuous axis, do noting special\n if (is_continuous_design(design)) return(design) # styler: off\n # if `nobs` is not initialized, it means no `Align` object exist\n # it's not necessary to initialize the `panel` and `index`\n # this is for `stack_layout` which may have no data\n if (is.null(nobs <- .subset2(design, \"nobs\"))) {\n return(design)\n }\n panel <- .subset2(design, \"panel\") %||% factor(rep_len(1L, nobs))\n index <- .subset2(design, \"index\") %||% reorder_index(panel)\n discrete_design(panel[index], index, nobs)\n}\n\nreorder_index <- function(panel, index = NULL) {\n index <- index %||% seq_along(panel)\n unlist(split(index, panel[index]), recursive = FALSE, use.names = FALSE)\n}\n\n############################################################\n#' @keywords internal\nupdate_design <- function(layout, ..., design, object_name) {\n UseMethod(\"update_design\")\n}\n\n#' @importFrom methods slot slot<-\n#' @export\nupdate_design.QuadLayout <- function(layout, ..., direction, design,\n object_name) {\n slot(layout, direction) <- design\n if (is_horizontal(direction)) {\n if (!is.null(left <- layout@left)) {\n layout@left <- update_design(left,\n design = design, object_name = object_name\n )\n }\n if (!is.null(right <- layout@right)) {\n layout@right <- update_design(right,\n design = design, object_name = object_name,\n from_head = TRUE\n )\n }\n } else {\n if (!is.null(top <- layout@top)) {\n layout@top <- update_design(top,\n design = design, object_name = object_name\n )\n }\n if (!is.null(bottom <- layout@bottom)) {\n layout@bottom <- update_design(bottom,\n design = design, object_name = object_name,\n from_head = TRUE\n )\n }\n }\n layout\n}\n\n#' @importFrom methods slot slot<-\n#' @export\nupdate_design.StackLayout <- function(layout, ..., design, object_name) {\n layout@design <- design\n layout@plot_list <- lapply(layout@plot_list, function(plot) {\n if (is_craftbox(plot)) return(plot) # styler: off\n update_design(plot,\n direction = layout@direction,\n design = design\n )\n })\n layout\n}\n\n#' @export\nupdate_design.CircleLayout <- update_design.StackLayout\n\n#' @importFrom methods slot slot<-\n#' @export\nupdate_design.StackCross <- function(layout, ..., design, object_name,\n from_head = FALSE) {\n # `design` must be a discrete_design()\n design_list <- c(layout@odesign, list(layout@design))\n\n # for cross_points, the updating will span it, but only update the panel\n # information\n cross_points <- layout@cross_points\n\n # the break_points set breaks, updating won't span the break points\n break_points <- layout@break_points\n\n plot_list <- layout@plot_list\n n <- length(plot_list)\n points <- c(cross_points, n)\n point_index <- seq_along(points)\n if (!from_head) point_index <- rev(point_index)\n for (i in point_index) {\n cross_point <- .subset(points, i)\n\n # we first update the design in the updated tail\n # it means the first design when `from_head` is `TRUE`\n # the last design when `from_head` is `FALSE`\n if ((from_head && i == 1L) || (!from_head && cross_point == n)) {\n new_design <- design\n } else if (!from_head && any(cross_point == break_points)) {\n break\n } else {\n # for design not in updated tail, we'll only update `panel` and\n # `nobs`, we check the new panel doesn't break the original index\n new_nobs <- .subset2(design, \"nobs\")\n new_panel <- .subset2(design, \"panel\")\n new_design <- .subset2(design_list, i)\n # we check the new panel don't disrupt the ordering index\n if (!is.null(new_panel) &&\n !is.null(old_index <- .subset2(new_design, \"index\"))) {\n # we always prevent from reordering twice.\n new_index <- reorder_index(new_panel, old_index)\n if (!all(old_index == new_index)) {\n cli_abort(sprintf(\n \"%s disrupt the previously established ordering index of %s (%d)\",\n object_name, object_name(layout), i\n ))\n }\n new_design[\"index\"] <- list(new_index)\n }\n new_design[\"nobs\"] <- list(new_nobs)\n new_design[\"panel\"] <- list(new_panel)\n }\n design_list[i] <- list(new_design)\n\n # we then update the design for each plot\n if (i == 1L) {\n subset <- seq_len(cross_point)\n } else {\n subset <- (.subset(points, i - 1L) + 1L):cross_point\n }\n\n layout@plot_list[subset] <- lapply(\n plot_list[subset], function(plot) {\n if (is_craftbox(plot)) {\n return(plot)\n }\n update_design(plot,\n direction = layout@direction,\n design = new_design\n )\n }\n )\n if (from_head && any(cross_point == break_points)) break\n }\n layout@odesign <- vec_slice(design_list, seq_len(length(design_list) - 1L))\n layout@design <- design_list[[length(design_list)]]\n layout\n}\n\n############################################################\nmelt_discrete_design <- function(old, new, old_name, new_name,\n call = caller_call()) {\n old_nobs <- .subset2(old, \"nobs\")\n new_nobs <- .subset2(new, \"nobs\")\n if (is.null(new_nobs)) { # no `nobs` provided\n nobs <- old_nobs\n } else if (is.null(old_nobs)) {\n nobs <- new_nobs\n } else if (!identical(new_nobs, old_nobs)) {\n cli_abort(sprintf(\n \"%s (nobs: %d) is not compatible with the %s (nobs: %d)\",\n new_name, new_nobs, old_name, old_nobs\n ), call = call)\n } else {\n nobs <- new_nobs\n }\n\n # check panel\n old_panel <- .subset2(old, \"panel\")\n new_panel <- .subset2(new, \"panel\")\n\n if (is.null(new_panel)) { # no panel provided\n panel <- old_panel\n } else if (!is.null(old_panel) && !(new_panel %nest% old_panel)) {\n cli_abort(sprintf(\n \"%s disrupt the previously established panel groups of %s\",\n new_name, old_name\n ), call = call)\n } else {\n panel <- new_panel\n }\n\n # check index\n old_index <- .subset2(old, \"index\")\n new_index <- .subset2(new, \"index\")\n if (is.null(new_index)) {\n index <- old_index\n } else {\n index <- new_index\n }\n\n # we always make the index following the panel\n if (!is.null(panel) && !is.null(index)) {\n index <- reorder_index(panel, index)\n }\n\n # we always prevent from reordering twice.\n if (!is.null(old_index) && !all(old_index == index)) {\n cli_abort(sprintf(\n \"%s disrupt the previously established ordering index of %s\",\n new_name, old_name\n ), call = call)\n }\n discrete_design(panel, index, nobs)\n}\n\n#######################################################################\n# ggplot2 add default scales in `compute_aesthetics` process\n# then ggplot2 transform all scales\n# layout:\n# in ggplot_build\n# - `setup`:\n# - call `facet$setup_params`\n# - attach `plot_env`\n# - call `facet$setup_data`\n# - call `facet$compute_layout`\n# - call `coord$setup_layout`\n# - call `facet$map_data`\n# - `train_position`: (run twice)\n# - call `facet$init_scales`\n# - call `facet$train_scales`\n# - `setup_panel_params`\n# - call `coord$modify_scales`: we align scales here, since this step\n# scales have been trained\n# - call `coord$setup_panel_params`: `view_scales_from_scale()`\n# - `map_position`\n# - `setup_panel_guides`\n# - call `coord$setup_panel_guides`\n# - call `coord$train_panel_guides`\n# in ggplot_gtable\n# - `layout$render`:\n# - call `facet$draw_back`\n# - call `facet$draw_front`\n# - call `coord$draw_panel` for each panel\n# - call `facet$draw_panels`: only once\n# - call `facet$init_gtable`:\n# - call `facet$attach_axes`:\n# - call `coord$render_axis_h`:\n# - call `guide$draw`:\n# - call `coord$render_axis_v`:\n# - call `guide$draw`:\n# - call `facet$attach_strips`:\n\n#' Set `limits`, `breaks`, `labels` for each panel\n#'\n#' @param x,y design for the layout.\n#' @keywords internal\n#' @noRd\nggalign_design <- function(x = NULL, y = NULL,\n xlabels = NULL, ylabels = NULL,\n xlim = TRUE, ylim = TRUE) {\n structure(\n list(\n x = x, y = y,\n xlabels = xlabels, ylabels = ylabels,\n xlim = xlim, ylim = ylim\n ),\n class = \"ggalign_design\"\n )\n}\n\nsetup_discrete_limits <- function(axis, design, n_panels) {\n panel <- .subset2(design, \"panel\")\n index <- .subset2(design, \"index\")\n if (n_panels == 1L) {\n list(range(index) + c(-0.5, 0.5))\n } else {\n # For y-axis, ggplot arrange panel from top to bottom,\n # we always choose to reverse the panel order\n if (axis == \"y\") panel <- fct_rev(panel)\n lapply(split(seq_along(index), panel), function(plot_index) {\n range(plot_index) + c(-0.5, 0.5)\n })\n }\n}\n\n#' @importFrom ggplot2 ggplot_add ggproto ggproto_parent\n#' @export\nggplot_add.ggalign_design <- function(object, plot, object_name, ...) {\n x_design <- .subset2(object, \"x\")\n y_design <- .subset2(object, \"y\")\n if (is.null(x_design) && is.null(y_design)) {\n return(plot)\n }\n ParentCoord <- plot$coordinates\n plot$coordinates <- ggproto(\n NULL, ParentCoord,\n num_of_panels = NULL,\n panel_counter = NULL,\n n_row_panels = NULL, # should be the number of panels in y\n n_column_panels = NULL, # should be the number of panels in x\n setup_layout = function(self, layout, params) {\n # we always initialize the number of panels and a panel counter\n self$num_of_panels <- vec_unique_count(.subset2(layout, \"PANEL\"))\n self$panel_counter <- 0L\n self$n_column_panels <- vec_unique_count(.subset2(layout, \"COL\"))\n self$n_row_panels <- vec_unique_count(.subset2(layout, \"ROW\"))\n if (.subset2(object, \"xlim\") && !is.null(x_design)) {\n if (is_discrete_design(x_design)) {\n self$xlim_list <- setup_discrete_limits(\n \"x\", x_design, self$n_column_panels\n )\n } else {\n self$xlim_list <- x_design\n }\n }\n if (.subset2(object, \"ylim\") && !is.null(y_design)) {\n if (is_discrete_design(y_design)) {\n self$ylim_list <- setup_discrete_limits(\n \"y\", y_design, self$n_row_panels\n )\n } else {\n self$ylim_list <- y_design\n }\n }\n # call the parent method\n ggproto_parent(ParentCoord, self)$setup_layout(layout, params)\n },\n # take the tricks to modify scales in place\n modify_scales = function(self, scales_x, scales_y) {\n # for each scale, we set the `breaks` and `labels`\n if (is_discrete_design(x_design)) {\n align_discrete_scales(\n \"x\", scales_x, x_design,\n labels = .subset2(object, \"xlabels\"),\n n_panels = self$n_column_panels,\n circle_layout = inherits(ParentCoord, \"CoordRadial\")\n )\n }\n if (is_discrete_design(y_design)) {\n align_discrete_scales(\n \"y\", scales_y, y_design,\n labels = .subset2(object, \"ylabels\"),\n n_panels = self$n_row_panels,\n circle_layout = inherits(ParentCoord, \"CoordRadial\")\n )\n }\n ggproto_parent(ParentCoord, self)$modify_scales(scales_x, scales_y)\n },\n setup_panel_params = function(self, scale_x, scale_y, params = list()) {\n # `setup_panel_params()` will utilize the `limits`\n # set limits here to ensure each plot will have the same limits\n cur_panel <- self$panel_counter + 1L\n if (!is.null(self$xlim_list)) {\n xlim <- .subset2(\n self$xlim_list,\n recycle_whole(cur_panel, self$n_column_panels)\n )\n if (is_discrete_design(x_design) && scale_x$is_discrete() &&\n !is.null(scale_x$range$range)) {\n # for discrete scale, the limits starts from zero in each\n # panel\n xlim <- xlim - (min(xlim) - 0.5)\n }\n if (inherits(self, \"CoordRadial\")) {\n self$limits$theta <- xlim\n } else {\n self$limits$x <- xlim\n }\n }\n if (!is.null(self$ylim_list)) {\n ylim <- .subset2(\n self$ylim_list,\n recycle_each(cur_panel, self$n_column_panels)\n )\n if (is_discrete_design(y_design) && scale_y$is_discrete() &&\n !is.null(scale_y$range$range)) {\n # for discrete scale, the limits starts from zero in each\n # panel\n ylim <- ylim - (min(ylim) - 0.5)\n }\n if (inherits(self, \"CoordRadial\")) {\n self$limits$r <- ylim\n } else {\n self$limits$y <- ylim\n }\n }\n self$panel_counter <- cur_panel\n ggproto_parent(ParentCoord, self)$setup_panel_params(\n scale_x = scale_x, scale_y = scale_y, params = params\n )\n }\n )\n plot\n}\n\nalign_discrete_scales <- function(axis, scales, design, labels, n_panels,\n circle_layout) {\n panel <- .subset2(design, \"panel\")\n index <- .subset2(design, \"index\")\n\n if (n_panels == 1L) {\n panel <- factor(vec_rep(1L, length(index)))\n } else {\n # For y-axis, ggplot arrange panel from top to bottom,\n # we always choose to reverse the panel order\n if (axis == \"y\") panel <- fct_rev(panel)\n }\n if (is.null(labels)) {\n data_labels <- NULL\n } else {\n data_labels <- split(labels, panel)\n }\n data_index <- split(index, panel)\n plot_index <- split(seq_along(index), panel)\n default_expand <- ggplot2::expansion()\n for (i in seq_along(scales)) {\n scale <- .subset2(scales, i)\n # we always use the discrete scale to determine labels and breaks\n # https://github.com/tidyverse/ggplot2/blob/7fb4c382f9ea332844d469663a8047355a88dd7a/R/scale-.R#L927\n # setup breaks and labels --------------------\n if (is.null(data_labels) &&\n is.waive(scale$labels) &&\n is.waive(scale$breaks)) {\n # special case for data have no labels\n # By default we also remove the breaks\n scale$breaks <- NULL\n scale$labels <- NULL\n } else {\n dindex <- .subset2(data_index, i)\n pindex <- .subset2(plot_index, i)\n labels <- .subset2(data_labels, i)\n scale$breaks <- get_discrete_breaks(scale, pindex, dindex, labels)\n scale$labels <- get_discrete_labels(\n scale, scale$breaks, pindex, dindex, labels\n )\n }\n\n # by default we elways remove any expansion\n # we don't allow the set of expansion for discrete variables\n # otherwise, ggmark and `cross_mark` won't work properly\n if (!circle_layout) scale$expand <- default_expand\n\n # for continuous scale, we don't allow the trans\n # if (!scale$is_discrete() && !identical(scale$trans$name, \"identity\")) {\n # cli_warn(sprintf(\n # \"{.arg trans} must be {.field identity} in {.code %s}\",\n # deparse(scale$call)\n # ))\n # scale$trans <- scales::as.transform(\"identity\")\n # }\n }\n}\n\n#' @importFrom rlang is_empty\nget_discrete_breaks <- function(scale, pindex, dindex, labels) {\n if (scale$is_empty()) return(numeric()) # styler: off\n breaks <- scale$breaks\n if (identical(breaks, NA)) {\n cli_abort(c(\n \"Invalid {.arg breaks} specification.\",\n i = \"Use {.code NULL}, not {.code NA}.\"\n ), call = scale$call)\n }\n if (is.null(breaks)) {\n return(NULL)\n }\n if (is.waive(breaks)) {\n if (scale$is_discrete() &&\n !is.null(labels) &&\n !is.null(scale$range$range) &&\n all(scale$range$range %in% labels)) {\n ans <- labels\n } else {\n ans <- pindex\n }\n } else {\n if (is.null(labels)) {\n limits <- dindex\n } else {\n limits <- labels\n }\n if (is.function(breaks)) {\n breaks <- breaks(limits)\n }\n\n if (is.factor(breaks) || is.character(breaks)) {\n # we interpreted the character breaks as the names of the original\n # matrix data.\n pos <- match(\n as.character(limits),\n vec_cast(breaks, character(),\n x_arg = \"breaks\", call = scale$call\n )\n )\n } else {\n # By default, we interpreted the breaks as the data index\n # If wrapped with `I()`, we interpreted it as the plot index\n if (inherits(breaks, \"AsIs\")) { # plot index\n pos <- match(pindex, vec_cast(breaks, integer(),\n x_arg = \"breaks\", call = scale$call\n ))\n } else { # data index\n pos <- match(dindex, vec_cast(breaks, integer(),\n x_arg = \"breaks\", call = scale$call\n ))\n }\n }\n index <- which(!is.na(pos))\n if (is_empty(index)) {\n return(NULL)\n }\n pos <- pos[index]\n if (scale$is_discrete() &&\n !is.null(labels) &&\n !is.null(scale$range$range) &&\n all(scale$range$range %in% labels)) {\n ans <- structure(labels[index], index = index, pos = pos)\n } else {\n ans <- structure(pindex[index], index = index, pos = pos)\n }\n }\n ans\n}\n\n#' @importFrom rlang is_empty\nget_discrete_labels <- function(scale, breaks, pindex, dindex, labels) {\n scale_labels <- scale$labels\n if (is_empty(breaks) || is.null(scale_labels)) { # if no breaks, no labels\n return(NULL)\n }\n\n if (identical(scale_labels, NA)) {\n cli_abort(c(\n \"Invalid {.arg labels} specification.\",\n i = \"Use {.code NULL}, not {.code NA}.\"\n ), call = scale$call)\n }\n\n # Need to ensure that if breaks were dropped\n if (!is.null(index <- attr(breaks, \"index\"))) {\n dindex <- dindex[index]\n labels <- labels[index]\n }\n\n # if layout have no names, use the data index directly\n # re-defined the breaks, the plot use the coordinates index\n # we interpreted user input as the data index\n if (is.null(labels)) {\n user_breaks <- dindex\n } else {\n user_breaks <- labels\n }\n if (is.waive(scale_labels)) { # By default, use the breaks\n user_breaks\n } else if (is.function(scale_labels)) {\n scale_labels(user_breaks)\n } else if (!is.null(names(scale_labels))) {\n # If labels have names, use them to match with breaks\n map <- match(as.character(user_breaks), names(scale_labels))\n user_breaks[map] <- scale_labels[!is.na(map)]\n user_breaks\n } else {\n # Need to ensure that if breaks were dropped, corresponding labels\n # are too\n if (is.null(pos <- attr(breaks, \"pos\"))) {\n if (inherits(scale_labels, \"AsIs\")) { # already in the plot index\n # we sort the `pos` so labels ordering won't be changed\n scale_labels <- scale_labels[pindex]\n } else { # in the data index\n scale_labels <- scale_labels[dindex]\n }\n } else {\n if (inherits(scale_labels, \"AsIs\")) { # already in the plot index\n # we sort the `pos` so labels ordering won't be changed\n scale_labels <- scale_labels[sort(pos)]\n } else { # in the data index\n scale_labels <- scale_labels[pos]\n }\n }\n scale_labels\n }\n}\n\n######################################################\n# this will remove the old coordinate,\n# so always run firstly\ngguse_linear_coord <- function(plot, layout_name) {\n coord <- plot$coordinates\n if (!inherits(coord, \"CoordTrans\") && !coord$is_linear()) {\n cli_warn(c(\n sprintf(\n \"{.fn %s} is not supported in %s\",\n snake_class(coord), layout_name\n ),\n i = \"Will use {.fn coord_cartesian} instead\"\n ))\n plot$coordinates <- ggplot2::coord_cartesian()\n }\n plot\n}\n\ngguse_circle_coord <- function(plot, coord, ..., layout_name) {\n if (inherits(plot_coord <- plot$coordinates, \"CoordRadial\")) {\n out <- ggproto(\n NULL, plot_coord,\n theta = coord$theta,\n r = coord$r,\n arc = coord$arc,\n direction = coord$direction,\n r_axis_inside = coord$r_axis_inside,\n expand = coord$expand,\n ...,\n setup_panel_params = circle_panel_params\n )\n } else {\n if (!isTRUE(plot$coordinates$default)) {\n cli_warn(c(\n sprintf(\n \"{.fn %s} is not supported in %s\",\n snake_class(plot_coord), layout_name\n ),\n i = sprintf(\"Will use {.fn %s} instead\", snake_class(coord))\n ))\n }\n if (!inherits(coord, \"CoordCircle\")) {\n out <- ggproto(NULL, coord, ...,\n setup_panel_params = circle_panel_params\n )\n } else {\n out <- ggproto(NULL, coord, ...)\n }\n }\n out\n}\n\n######################################################\n#' @importFrom ggplot2 ggproto\nggfacet_modify <- function(plot, ...) {\n ParentFacet <- plot$facet\n plot$facet <- ggproto(NULL, ParentFacet, ...)\n plot\n}\n\ngguse_facet <- function(plot, facet) {\n plot$facet <- facet\n plot\n}\n\nggmelt_facet <- function(plot, facet, ...) {\n gguse_facet(plot, melt_facet(facet, plot$facet, ...))\n}\n\n#' @param use A template facet object which will be used.\n#' @param facet User provided facet object.\n#' @noRd\nmelt_facet <- function(use, facet, ...) UseMethod(\"melt_facet\")\n\n#' @export\nmelt_facet.NULL <- function(use, facet, ...) {\n facet\n}\n\n#' @importFrom ggplot2 ggproto\n#' @export\nmelt_facet.FacetGrid <- function(use, facet, ...,\n free_row = FALSE,\n free_column = FALSE) {\n if (inherits(facet, \"FacetGrid\")) {\n # re-dispatch parameters\n params <- facet$params\n if (length(use$params$rows) || !free_row) {\n params$rows <- use$params$rows\n }\n if (length(use$params$cols) || !free_column) {\n params$cols <- use$params$cols\n }\n if (!free_row) { # Don't allow user change the rows\n params$free$y <- use$params$free$y\n params$space_free$y <- use$params$space_free$y\n }\n if (!free_column) { # Don't allow user change the cols\n params$free$x <- use$params$free$x\n params$space_free$x <- use$params$space_free$x\n }\n\n params$drop <- use$params$drop\n params$as.table <- use$params$as.table\n\n # if the use is free, it must be free\n ggproto(NULL, facet, params = params)\n } else {\n use\n }\n}\n\n#' @importFrom ggplot2 ggproto\n#' @export\nmelt_facet.FacetWrap <- function(use, facet, ...) {\n if (inherits(facet, \"FacetWrap\")) {\n # re-dispatch parameters\n params <- facet$params\n\n # we always fix the grid rows and cols\n params$facets <- use$params$facets\n params$nrow <- use$params$nrow\n params$ncol <- use$params$ncol\n params$drop <- use$params$drop\n params$as.table <- use$params$as.table\n ggproto(NULL, facet, params = params)\n } else {\n use\n }\n}\n\n#' @export\nmelt_facet.FacetNull <- function(use, facet, ...) {\n if (inherits(facet, \"FacetNull\")) {\n facet\n } else {\n use\n }\n}\n\n#' @export\nmelt_facet.FacetStack <- function(use, facet, ...) {\n if (inherits(facet, \"FacetGrid\")) {\n params <- facet$params\n if (is_horizontal(.subset2(use, \"direction\"))) {\n # for horizontal stack, we cannot facet by rows\n if (!is.null(params$rows)) {\n cli_warn(sprintf(\n \"Cannot facet by rows in %s\",\n .subset2(use, \"object_name\")\n ))\n params$rows <- NULL\n }\n } else if (!is.null(params$cols)) {\n # for vertical stack, we cannot facet by cols\n cli_warn(sprintf(\n \"Cannot facet by cols in %s\",\n .subset2(use, \"object_name\")\n ))\n params$cols <- NULL\n }\n ggproto(NULL, facet, params = params)\n } else if (inherits(facet, \"FacetWrap\")) {\n params <- facet$params\n if (is_horizontal(.subset2(use, \"direction\"))) {\n # for horizontal stack, we cannot facet by rows\n if (is.null(params$nrow)) {\n params$nrow <- 1L\n } else if (params$nrow > 1L) {\n cli_warn(sprintf(\n \"Cannot wrap facet by rows in %s\",\n .subset2(use, \"object_name\")\n ))\n params$nrow <- 1L\n }\n } else if (!is.null(params$cols)) {\n # for vertical stack, we cannot facet by cols\n if (is.null(params$ncol)) {\n params$ncol <- 1L\n } else if (params$ncol > 1L) {\n cli_warn(sprintf(\n \"Cannot wrap facet by cols in %s\",\n .subset2(use, \"object_name\")\n ))\n params$ncol <- 1L\n }\n }\n } else if (inherits(facet, \"FacetNull\")) {\n facet\n } else {\n ggplot2::facet_null()\n }\n}\n\nfacet_stack <- function(direction, object_name) {\n structure(\n list(direction = direction, object_name = object_name),\n class = \"FacetStack\"\n )\n}\n\n#' @export\nmelt_facet.FacetQuad <- function(use, facet, ...,\n free_row = FALSE,\n free_column = FALSE) {\n if (inherits(facet, \"FacetGrid\")) {\n if (free_row || free_column) {\n params <- facet$params\n if (!free_row && !is.null(params$rows)) {\n cli_warn(sprintf(\n \"Cannot facet by rows in %s\",\n .subset2(use, \"layout_name\")\n ))\n params$rows <- NULL\n # for horizontal stack, we cannot facet by rows\n }\n if (!free_column && !is.null(params$cols)) {\n cli_warn(sprintf(\n \"Cannot facet by cols in %s\",\n .subset2(use, \"layout_name\")\n ))\n params$cols <- NULL\n }\n ggproto(NULL, facet, params = params)\n } else {\n ggplot2::facet_null()\n }\n } else if (inherits(facet, \"FacetNull\")) {\n facet\n } else {\n ggplot2::facet_null()\n }\n}\n\nfacet_quad <- function(layout_name) {\n structure(list(layout_name = layout_name), class = \"FacetQuad\")\n}\n"], ["/ggalign/R/layout-quad-add.R", "#' @keywords internal\nquad_layout_add <- function(object, quad, object_name) {\n UseMethod(\"quad_layout_add\")\n}\n\n#############################################################\n#' @export\nquad_layout_add.layout_title <- function(object, quad, object_name) {\n quad@titles <- update_non_waive(quad@titles, object)\n quad\n}\n\n##############################################################\n# Preventing from adding following elements\n#' @export\nquad_layout_add.matrix <- function(object, quad, object_name) {\n cli_abort(sprintf(\"Can't change data of %s\", object_name(quad)))\n}\n\n#' @export\nquad_layout_add.data.frame <- quad_layout_add.matrix\n\n#############################################################\n# Add elements for the main body or the annotation\n#' @importFrom methods slot slot<-\n#' @export\nquad_layout_add.default <- function(object, quad, object_name) {\n if (is.null(position <- quad@active)) {\n quad <- quad_body_add(object, quad, object_name)\n } else if (is.null(stack <- slot(quad, position))) {\n cli_abort(c(\n sprintf(\"Cannot add {.var {object_name}} to %s\", object_name(quad)),\n i = \"the {.field {position}} annotation stack is not initialized\",\n i = \"Try to use {.code quad_anno(initialize = TRUE)} or you can add a {.code stack_layout()} manually\"\n ))\n } else {\n slot(quad, position) <- chain_layout_add(object, stack, object_name)\n }\n quad\n}\n\n#' @export\nquad_layout_add.list <- function(object, quad, object_name) {\n for (o in object) quad <- quad_layout_add(o, quad, object_name)\n quad\n}\n\n#' @export\nquad_layout_add.NULL <- function(object, quad, object_name) {\n quad\n}\n\n#' @export\nquad_layout_add.ggalign_with_quad <- function(object, quad, object_name) {\n old <- quad@active\n contexts <- quad_operated_context(object, old, \"+\") %||%\n list(NULL) # we wrap `NULL` to a list for `for loop`.\n object <- .subset2(object, \"object\")\n object_name <- .subset2(object, \"object_name\")\n for (active in contexts) {\n quad@active <- active\n quad <- quad_layout_add(object, quad, object_name)\n }\n quad@active <- old\n quad\n}\n\n##################################################################\n#' @export\nquad_layout_add.quad_active <- function(object, quad, object_name) {\n if (!is.null(width <- .subset2(object, \"width\"))) {\n quad@width <- width\n }\n if (!is.null(height <- .subset2(object, \"height\"))) {\n quad@height <- height\n }\n quad@active <- NULL\n quad\n}\n\n#' @importFrom methods slot\n#' @export\nquad_layout_add.quad_anno <- function(object, quad, object_name) {\n position <- .subset2(object, \"position\")\n initialize <- .subset2(object, \"initialize\")\n stack <- slot(quad, position)\n if (is.null(stack) && !isFALSE(initialize)) {\n # try to initialize the annotation stack with the layout data\n direction <- to_direction(position)\n layout_design <- slot(quad, direction)\n # for the annotation stack, we try to take the data from the\n # quad layout\n quad_data <- quad@data\n data <- waiver() # use waiver() to indicate data is not initialized\n quad_matrix <- FALSE # the default value for `quad_matrix` in the stack\n if (is_continuous_design(layout_design)) { # the stack need a data frame\n if (!is.data.frame(quad_data)) {\n if (is.null(initialize)) {\n cli_warn(paste(\n \"`data` in {.fn {quad@name}} is\",\n \"{.obj_type_friendly {quad_data}}, but the\",\n \"{.field {position}} annotation stack need a\",\n \"{.cls data.frame}, won't initialize\",\n \"the {.field {position}} annotation stack\"\n ))\n } else {\n data <- NULL\n }\n } else {\n data <- quad_data\n }\n } else if (is.matrix(quad_data)) { # the stack need a matrix\n if (is_horizontal(direction)) {\n data <- quad_data\n } else {\n data <- ggalign_data_restore(t(quad_data), quad_data)\n }\n quad_matrix <- TRUE\n } else {\n if (is.null(initialize)) {\n cli_warn(paste(\n \"`data` in {.fn {quad@name}} is\",\n \"{.obj_type_friendly {quad_data}}, but the\",\n \"{.field {position}} annotation stack need a\",\n \"{.cls data.frame}, won't initialize\",\n \"the {.field {position}} annotation stack\"\n ))\n } else {\n data <- NULL\n }\n }\n if (!is.waive(data)) { # initialize the annotation stack\n stack <- new_stack_layout(\n data = data,\n direction = direction,\n # the layout parameters should be the same with `quad_layout()`\n design = layout_design,\n # we'll inherit the action data function when\n schemes = default_schemes(if (is.null(data)) NULL else waiver())\n )\n stack@heatmap$position <- position\n stack@heatmap$quad_matrix <- quad_matrix\n }\n } else if (!is.null(stack) && isTRUE(initialize)) {\n cli_abort(c(\n \"Cannot initialize the {position} annotation stack\",\n i = \"{position} annotation stack has already been initialized\"\n ))\n }\n\n if (!is.null(stack)) {\n # update parameters\n if (!is.null(size <- .subset2(object, \"size\"))) {\n stack@sizes <- size\n }\n if (!is.waive(free_guides <- .subset2(object, \"free_guides\"))) {\n stack@heatmap[\"free_guides\"] <- list(free_guides)\n }\n stack <- switch_chain_plot(\n stack, .subset2(object, \"what\"), quote(quad_anno())\n )\n slot(quad, position) <- stack\n }\n quad@active <- position\n quad\n}\n\n#' @export\nquad_layout_add.QuadLayout <- function(object, quad, object_name) {\n cli_abort(c(\n sprintf(\"Cannot add {.var {object_name}} to %s\", object_name(quad)),\n i = \"Did you mean to place multiple {.fn quad_layout} elements inside a {.fn stack_layout}?\"\n ))\n}\n\n#' @export\nquad_layout_add.StackLayout <- function(object, quad, object_name) {\n # we check if there is an active annotation\n if (is.null(position <- quad@active)) {\n cli_abort(c(\n sprintf(\"Cannot add {.var {object_name}} to %s\", object_name(quad)),\n i = \"no active annotation stack\",\n i = \"try to activate an annotation stack with {.fn anno_*}\"\n ))\n }\n # check the annotation stack is not initialized\n if (!is.null(slot(quad, position))) {\n cli_abort(c(\n sprintf(\"Cannot add {.var {object_name}} to %s\", object_name(quad)),\n i = \"{position} annotation stack already exists\"\n ))\n }\n # cannot contain nested layout\n if (!all(vapply(object@plot_list, is_craftbox, logical(1L),\n USE.NAMES = FALSE))) { # styler: off\n cli_abort(c(\n sprintf(\"Cannot add {.var {object_name}} to %s\", object_name(quad)),\n i = \"annotation stack cannot contain nested layout\"\n ))\n }\n # check quad layout is compatible with stack layout\n if (!identical(direction <- to_direction(position), object@direction)) {\n cli_abort(c(\n sprintf(\"Cannot add {.var {object_name}} to %s\", object_name(quad)),\n i = \"only {.field {direction}} stack is allowed in {position} annotation\"\n ))\n }\n if (length(object@sizes) > 1L) {\n cli_abort(c(\n sprintf(\"Cannot add {.var {object_name}} to %s\", object_name(quad)),\n i = \"{.arg sizes} must be of length one to use the stack as an annotation\"\n ))\n }\n quad_design <- slot(quad, direction)\n if (is_cross_layout(object) &&\n any(position == c(\"bottom\", \"right\")) &&\n !is_empty(object@cross_points)) {\n # if there are cross points in bottom or right annotation,\n # use the first design\n stack_design <- .subset2(object@odesign, 1L)\n } else {\n stack_design <- object@design\n }\n # check if we can align in this direction\n # `stack_layout()` is free from aligning obervations in this axis\n if (is_continuous_design(stack_design)) {\n if (!is_continuous_design(quad_design)) {\n cli_abort(c(\n sprintf(\n \"Cannot add {.var {object_name}} to %s\",\n object_name(quad)\n ),\n i = sprintf(\n \"%s cannot align continuous variable in {.field {direction}} direction\",\n object_name(quad)\n )\n ))\n }\n layout_design <- stack_design\n } else if (is_discrete_design(quad_design)) {\n layout_design <- melt_discrete_design(\n quad_design, stack_design,\n old_name = object_name(quad),\n new_name = object_name\n )\n } else {\n cli_abort(c(\n sprintf(\"Cannot add {.var {object_name}} to %s\", object_name(quad)),\n i = sprintf(\n \"%s cannot align discrete variable in {.field {direction}} direction\",\n object_name(quad)\n )\n ))\n }\n object@heatmap$position <- position\n slot(quad, position) <- object\n update_design(quad,\n direction = direction,\n design = layout_design,\n object_name = object_name\n )\n}\n\n#' @importFrom methods slot slot<-\n#' @export\nquad_layout_add.CraftBox <- function(object, quad, object_name) {\n if (is.null(position <- quad@active)) {\n cli_abort(c(\n sprintf(\"Cannot add {.var {object_name}} to %s\", object_name(quad)),\n i = \"no active annotation stack\",\n i = \"try to activate an annotation stack with {.fn anno_*}\"\n ))\n }\n if (is.null(stack <- slot(quad, position))) {\n cli_abort(c(\n sprintf(\"Cannot add {.var {object_name}} to %s\", object_name(quad)),\n i = \"the {.field {position}} annotation stack is not initialized\",\n i = \"Try to use {.code quad_anno(initialize = TRUE)} or you can add a {.code stack_layout()} manually\"\n ))\n }\n\n # add annotation -----------------------------\n stack <- chain_layout_add(object, stack, object_name)\n slot(quad, position) <- stack\n\n # if there are cross points in bottom or right annotation, we use\n # the first design\n if (is_cross_layout(stack) &&\n any(position == c(\"bottom\", \"right\")) &&\n !is_empty(stack@cross_points)) {\n new_design <- .subset2(stack@odesign, 1L)\n } else {\n new_design <- stack@design\n }\n\n update_design(\n quad,\n direction = to_direction(position),\n design = new_design,\n object_name = object_name\n )\n}\n\n#######################################################\n# used to add elements for main body\n#' @keywords internal\nquad_body_add <- function(object, quad, object_name) {\n UseMethod(\"quad_body_add\")\n}\n\n#' @importFrom ggplot2 ggplot_add\n#' @export\nquad_body_add.default <- function(object, quad, object_name) {\n quad@plot <- ggplot_add(object, ggfun(\"plot_clone\")(quad@plot), object_name)\n quad\n}\n\n#' @export\nquad_body_add.Coord <- function(object, quad, object_name) {\n if (!inherits(object, \"CoordCartesian\")) {\n cli_warn(c(\n \"only {.field cartesian coordinate} is supported\",\n i = \"will discard {.var {object_name}} directly\"\n ))\n return(quad)\n }\n NextMethod() # call default method\n}\n\n#' @export\nquad_body_add.layout_theme <- function(object, quad, object_name) {\n quad@theme <- update_layout_theme(quad@theme, object)\n quad\n}\n\n#' @export\nquad_body_add.ggalign_scheme <- function(object, quad, object_name) {\n name <- ggalign_scheme_name(object)\n quad@body_schemes[name] <- list(update_scheme(\n object, .subset2(quad@body_schemes, name), object_name\n ))\n quad\n}\n"], ["/ggalign/R/craft-align-order.R", "#' Order observations based on weights\n#'\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' Ordering observations based on summary weights or a specified ordering\n#' character or integer index.\n#'\n#' @param weights A summary function which accepts a data and returns the\n#' weights for each observations. Alternatively, you can provide an ordering\n#' index as either an integer or a character. Since characters have been\n#' designated as character indices, if you wish to specify a function name as a\n#' string, you must enclose it with [`I()`].\n#' @param ... <[dyn-dots][rlang::dyn-dots]> Additional arguments passed to\n#' function provided in `weights` argument.\n#' @param reverse A boolean value. Should the sort order be in reverse?\n#' @param strict A boolean value indicates whether the order should be strict.\n#' If previous groups has been established, and strict is `FALSE`, this will\n#' reorder the observations in each group.\n#' @param data A `matrix`, `data frame`, or atomic vector used as the input for\n#' the `weights` function. Alternatively, you can specify a `function`\n#' (including purrr-like lambda syntax) that will be applied to the layout\n#' matrix, transforming it as necessary for weight calculations. By default, it\n#' will inherit from the layout matrix.\n#' @inheritParams align\n#' @inheritSection align Discrete Axis Alignment\n#' @examples\n#' ggheatmap(matrix(rnorm(81), nrow = 9)) +\n#' anno_left() +\n#' align_order(I(\"rowMeans\"))\n#' @importFrom ggplot2 waiver\n#' @importFrom rlang list2\n#' @export\nalign_order <- function(weights = rowMeans, ...,\n reverse = FALSE, strict = TRUE, data = NULL,\n active = NULL) {\n if (is.numeric(weights) ||\n (is.character(weights) && !inherits(weights, \"AsIs\"))) {\n # vec_duplicate_any is slight faster than `anyDuplicated`\n if (vec_any_missing(weights) || vec_duplicate_any(weights)) {\n cli_abort(paste(\n \"{.arg weights} must be an ordering numeric or character\",\n \"without missing value or ties\"\n ))\n } else if (is.numeric(weights)) {\n weights <- vec_cast(weights, integer())\n }\n if (vec_size(weights) == 0L) {\n cli_abort(\"{.arg weights} cannot be empty\")\n }\n if (!is.null(data)) {\n cli_warn(c(\n \"{.arg data} won't be used\",\n i = \"{.arg weights} is not a {.cls function}\"\n ))\n }\n } else {\n weights <- rlang::as_function(weights)\n data <- data %||% waiver()\n }\n assert_bool(strict)\n assert_bool(reverse)\n assert_active(active)\n active <- update_active(active, new_active(use = FALSE))\n align(\n align = AlignOrder,\n weights = weights,\n params = list2(...),\n reverse = reverse,\n strict = strict,\n active = active,\n data = data\n )\n}\n\n#' @importFrom ggplot2 ggproto\n#' @importFrom rlang inject is_atomic\nAlignOrder <- ggproto(\"AlignOrder\", CraftAlign,\n interact_layout = function(self, layout) {\n if (is.function(self$weights)) {\n layout <- ggproto_parent(AlignOrder2, self)$interact_layout(layout)\n } else {\n layout <- ggproto_parent(CraftAlign, self)$interact_layout(layout)\n if (is.null(layout_nobs <- .subset2(layout@design, \"nobs\"))) {\n layout@design[\"nobs\"] <- list(vec_size(self$weights))\n } else {\n assert_mismatch_nobs(\n self, layout_nobs, vec_size(self$weights),\n arg = \"weights\"\n )\n }\n self$labels <- vec_names(layout@data)\n }\n layout\n },\n compute = function(self, panel, index) {\n if (is.function(self$weights)) {\n ans <- inject(self$weights(self$data, !!!self$params))\n if (!is_atomic(ans)) {\n cli_abort(\n \"{.arg weights} must return an atomic weights\",\n call = self$call\n )\n }\n assert_mismatch_nobs(\n self, vec_size(ans), vec_size(ans),\n arg = \"weights\"\n )\n ans\n }\n },\n align = function(self, panel, index) {\n if (is.function(self$weights)) {\n index <- order(self$statistics)\n } else {\n index <- vec_as_location(\n self$weights,\n n = vec_size(self$weights),\n names = self$labels,\n missing = \"error\",\n call = self$call\n )\n }\n if (self$reverse) index <- rev(index)\n assert_reorder(self, panel, index, self$strict)\n list(panel, index)\n },\n summary_align = function(self) c(TRUE, FALSE)\n)\n"], ["/ggalign/R/utils-assert.R", "# `assert_*()` functions will do the side effects\n# `check_*()` functions will return the arguments\n#' @importFrom rlang caller_arg caller_call\nassert_gp <- function(gp, arg = caller_arg(gp), call = caller_call()) {\n assert_s3_class(gp, \"gpar\", arg = arg, call = call)\n}\n\n#' @importFrom rlang caller_arg caller_call\nassert_mapping <- function(mapping, arg = caller_arg(mapping),\n call = caller_call()) {\n if (!inherits(mapping, \"uneval\")) {\n cli_abort(c(\"{.arg {arg}} must be created with {.fn aes}.\",\n x = \"You've supplied {.obj_type_friendly {mapping}}.\"\n ), call = call)\n }\n}\n\nassert_mismatch_nobs <- function(align, n, nobs, arg) {\n if (n != nobs) {\n cli_abort(sprintf(\n \"{.arg %s} (nobs: %d) of %s is not compatible with the %s (nobs: %d)\",\n arg, nobs, object_name(align), align$layout_name, n\n ))\n }\n}\n\nassert_sub_split <- function(align, panel) {\n if (!is.null(panel)) {\n cli_abort(c(\n sprintf(\"%s cannot do sub-split\", object_name(align)),\n i = sprintf(\n \"Group of layout %s-axis already exists\",\n to_coord_axis(align$direction)\n )\n ), call = align$call)\n }\n}\n\nassert_reorder <- function(align, panel, index, strict) {\n if (!is.null(panel) && nlevels(panel) > 1L && strict &&\n !all(index == reorder_index(panel, index))) {\n layout_name <- align$layout_name\n object_name <- object_name(align)\n cli_abort(c(\n sprintf(\"Cannot add %s to %s\", object_name, layout_name),\n i = sprintf(\n \"Group of %s will disrupt the ordering index of %s\", layout_name, object_name\n ),\n i = \"try to set {.code strict = FALSE} to reorder within each group\"\n ), call = align$call)\n }\n}\n\nassert_position <- function(position, arg = caller_arg(position),\n call = caller_call()) {\n assert_string(position, empty_ok = FALSE, arg = arg, call = call)\n if (grepl(\"[^tlbr]\", position)) {\n cli_abort(sprintf(\n \"{.arg {arg}} can only contain the %s characters\",\n oxford_and(.tlbr)\n ), call = call)\n }\n}\n\nassert_guides <- function(guides, arg = caller_arg(guides),\n call = caller_call()) {\n assert_string(guides, empty_ok = FALSE, arg = arg, call = call)\n if (grepl(\"[^tlbri]\", guides)) {\n cli_abort(sprintf(\n \"{.arg {arg}} can only contain the %s characters\",\n oxford_and(c(.tlbr, \"i\"))\n ), call = call)\n }\n}\n\nassert_layout_position <- function(position, arg = caller_arg(position),\n call = caller_call()) {\n if (!is.waive(position) && !is.null(position)) {\n assert_position(position, arg = arg, call = call)\n }\n}\n\nassert_layout_guides <- function(guides, arg = caller_arg(guides),\n call = caller_call()) {\n if (!is.waive(guides) && !is.null(guides)) {\n assert_guides(guides, arg = arg, call = call)\n }\n}\n\n#' @importFrom grid is.unit\ncheck_stack_sizes <- function(sizes, arg = caller_arg(sizes),\n call = caller_call()) {\n if (!(all(is.na(sizes)) || is.numeric(sizes) || is.unit(sizes))) {\n cli_abort(\n \"{.arg {arg}} must be a numeric or {.cls unit} object\",\n call = call\n )\n }\n l <- length(sizes)\n if (l != 1L && l != 3L) {\n cli_abort(\n \"{.arg {arg}} must have size `1` or `3`, not size {l}\",\n call = call\n )\n }\n if (!is.unit(sizes)) sizes <- unit(sizes, \"null\")\n sizes\n}\n\n#' @importFrom rlang arg_match0\ncheck_direction <- function(direction, arg = caller_arg(direction),\n call = caller_call()) {\n direction <- arg_match0(direction, c(\"h\", \"v\"),\n arg_nm = arg, error_call = call\n )\n switch(direction, h = \"horizontal\", v = \"vertical\") # styler: off\n}\n\nassert_limits <- function(limits, allow_null = TRUE, arg = caller_arg(limits),\n call = caller_call()) {\n if (is.null(limits) && allow_null) {\n return(invisible(NULL))\n }\n if (!inherits(limits, \"continuous_limits\")) {\n cli_abort(\n \"{.arg {arg}} must be specified with {.fn continuous_limits}\",\n call = call\n )\n }\n if (rlang::is_named(limits)) {\n cli_abort(\n \"{.arg {arg}} shouldn't be created with {.arg x}/{.arg y} argument in {.fn continuous_limits}\",\n call = call\n )\n }\n}\n\n#' @importFrom grid is.unit\ncheck_size <- function(size, arg = caller_arg(size), call = caller_call()) {\n if (!is_scalar(size) &&\n !(is.na(size) || is.numeric(size) || is.unit(size))) {\n cli_abort(\n \"{.arg {arg}} must be a single numeric or unit object\",\n call = call\n )\n }\n if (!is.unit(size)) size <- unit(size, \"null\")\n size\n}\n\ncheck_scheme_data <- function(data, arg = caller_arg(data),\n call = caller_call()) {\n if (!is.waive(data) && !is.null(data) &&\n !is.function(data <- allow_lambda(data))) {\n cli_abort(paste(\n \"{.arg {arg}} must be a function,\",\n \"{.code NULL} or {.fn waiver}\"\n ), call = call)\n }\n data\n}\n\ncheck_stack_context <- function(what, arg = caller_arg(what),\n call = caller_call()) {\n if (is.null(what)) return(what) # styler: off\n if (.rlang_check_number(what, allow_decimal = FALSE, min = 1) != 0L &&\n !is_string(what)) {\n cli_abort(\n \"{.arg {arg}} must be a single positive integer number or string\",\n call = call\n )\n }\n what\n}\n\ncheck_order <- function(order, arg = caller_arg(order), call = caller_call()) {\n if (is.null(order)) {\n NA_integer_\n } else if (.rlang_check_number(order, allow_decimal = FALSE) == 0L) {\n as.integer(order)\n } else {\n cli_abort(\"{.arg {arg}} must be single integer number\", call = call)\n }\n}\n\nassert_align <- function(x, arg = caller_arg(x), call = caller_call()) {\n if (!inherits(x, \"scheme_align\")) {\n cli_abort(\n \"{.arg {arg}} must be created by {.fn scheme_align}\",\n call = call\n )\n }\n}\n\nassert_active <- function(x, allow_null = TRUE,\n arg = caller_arg(x), call = caller_call()) {\n if (is.null(x) && allow_null) {\n return(invisible(NULL))\n }\n if (!inherits(x, \"ggalign_active\")) {\n cli_abort(\n \"{.arg {arg}} must be created by {.fn active}\",\n call = call\n )\n }\n}\n\nassert_obs_size <- function(obs_size, arg = caller_arg(obs_size),\n call = caller_call()) {\n if (.rlang_check_number(obs_size, allow_decimal = TRUE, # styler: off\n .Machine$double.eps, 1) != 0L) { # styler: off\n cli_abort(\n \"{.arg {arg}} must be a single number in `(0, 1]`\",\n call = call\n )\n }\n}\n"], ["/ggalign/R/scheme-data.R", "#' Plot data Specifications\n#'\n#' @description\n#' `r lifecycle::badge('experimental')`\n#'\n#' Transforms the plot data. Many functions in this package require a specific\n#' data format to align observations, `scheme_data()` helps reformat data frames\n#' as needed.\n#'\n#' @param data A function to transform the plot data before rendering.\n#' Acceptable values include:\n#'\n#' - `NULL`: No action taken.\n#' - [`waiver()`][ggplot2::waiver()]: Inherits from the parent layout.\n#' - A `function` or purrr-style `formula`: Used to transform the plot data,\n#' which should accept a data frame and return a data frame. You can apply\n#' this after the parent layout `scheme_data` function, using the `inherit`\n#' argument.\n#'\n#' Use this hook to modify the data for all `geoms` after the layout is created\n#' (for matrix data, it has been melted to a long format data frame) but before\n#' rendering by `ggplot2`. The returned data must be a data frame for ggplot.\n#'\n#' @param inherit A single boolean value indicates whether to apply the parent\n#' `scheme_data` first and then apply the specified `scheme_data` for the plot.\n#' Defaults to `FALSE`.\n#'\n#' @details\n#' Defaults will attempt to inherit from the parent layout if the actual data is\n#' inherited from the parent layout, with one exception: `align_dendro()`, which\n#' will not inherit the `scheme_data` by default.\n#'\n#' @export\nscheme_data <- function(data, inherit = FALSE) {\n data <- check_scheme_data(data)\n assert_bool(inherit)\n new_scheme_data(data, inherit)\n}\n\nnew_scheme_data <- function(data = NULL, inherit = FALSE) {\n new_scheme(\n name = \"scheme_data\",\n list(data = data, inherit = inherit),\n class = \"scheme_data\"\n )\n}\n\n#' @export\ninherit_scheme.scheme_data <- function(scheme, pscheme) {\n if (is.null(o <- .subset2(scheme, \"data\"))) return(scheme) # styler: off\n if (is.waive(o)) return(pscheme) # inherit from parent; styler: off\n if (!is.function(p_function <- .subset2(pscheme, \"data\"))) {\n return(scheme)\n }\n # if both are function, we check if we should call parent first then call\n # itself\n if (.subset2(scheme, \"inherit\")) {\n user_scheme_data <- o # current action data function\n scheme$data <- function(data) {\n # we always restore the attached attribute\n ans <- ggalign_data_restore(p_function(data), data)\n user_scheme_data(ans)\n }\n }\n scheme\n}\n\n#' @export\nplot_add_scheme.scheme_data <- function(plot, scheme) {\n # by default, we won't change the data\n if (!is.null(scheme_data <- .subset2(scheme, \"data\") %|w|% NULL) &&\n !is.null(raw_data <- plot$data)) {\n # To be compatible with ggplot2, it must be a data frame\n if (!is.null(data <- scheme_data(raw_data)) &&\n !is.waive(data) &&\n !is.data.frame(data)) {\n cli_abort(\"{.fn scheme_data} must return a {.cls data.frame}\")\n }\n plot <- gguse_data(plot, data)\n }\n plot\n}\n"], ["/ggalign/R/layout-quad-switch.R", "#' Determine the Active Context of Quad-Layout\n#'\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' - `quad_active`: Sets the active context to the `r rd_quad()` itself.\n#' - `quad_anno`: Sets the active context to the specified annotation stack\n#' based on the `position` argument.\n#' - `anno_top`: A special case of `quad_anno` with `position = \"top\"`.\n#' - `anno_left`: A special case of `quad_anno` with `position = \"left\"`.\n#' - `anno_bottom`: A special case of `quad_anno` with `position = \"bottom\"`.\n#' - `anno_right`: A special case of `quad_anno` with `position = \"right\"`.\n#'\n#' @inheritParams quad_layout\n#' @return An object that can be added to `r rd_quad()`.\n#' @export\n#' @rdname quad_active\nquad_active <- function(width = NULL, height = NULL) {\n if (!is.null(width)) width <- check_size(width)\n if (!is.null(height)) height <- check_size(height)\n structure(\n list(width = width, height = height),\n class = c(\"quad_active\", \"quad_switch\")\n )\n}\n\n#' @details\n#' By default, `quad_anno()` attempts to initialize the annotation stack layout\n#' using data from `r rd_quad()`. However, in situations where you want to use\n#' different data for the annotation stack, you can set `initialize = FALSE`\n#' and then provide a custom `stack_layout()`.\n#'\n#' @param position `r rd_quad_position(\"activated\")`.\n#' @param size A numeric value or an [`unit`][grid::unit] object to set the\n#' total `height`/`width` of the annotation stack.\n#' - If `position` is `\"top\"` or `\"bottom\"`, `size` sets the total height of\n#' the annotation.\n#' - If `position` is `\"left\"` or `\"right\"`, `size` sets the total width of the\n#' annotation.\n#' @param free_guides Override the `guides` collection behavior specified in the\n#' `r rd_quad()` for the annotation stack.\n#' @param initialize A boolean indicating whether the annotation stack should be\n#' initialized if it is not already. By default, the annotation stack layout\n#' will attempt to initialize when the data is compatible. If set to `TRUE`, and\n#' the data in `r rd_quad()` is incompatible with the annotation stack, no\n#' data will be used in the stack.\n#' @param what What should get activated in the annotation stack?\n#' `r rd_chain_what()`.\n#' @seealso [`quad_switch()`]\n#' @export\n#' @rdname quad_active\nquad_anno <- function(position, size = NULL, free_guides = waiver(),\n initialize = NULL, what = waiver()) {\n if (is.null(position)) {\n cli_abort(c(\n paste(\n \"{.arg position} must be a single string of\",\n \"{oxford_or(.TLBR)}, not `NULL`\"\n ),\n i = \"Do you want to set the active context to the `quad_layout()` with {.fn quad_active}?\"\n ))\n }\n position <- match.arg(position, .TLBR)\n quad_switch_anno(\n size = size, free_guides = free_guides,\n initialize = initialize, what = what,\n position = position\n )\n}\n\n#' @export\n#' @rdname quad_active\nanno_top <- function(size = NULL, free_guides = waiver(), initialize = NULL,\n what = waiver()) {\n quad_switch_anno(\n size = size, free_guides = free_guides,\n initialize = initialize, what = what,\n position = \"top\"\n )\n}\n\n#' @export\n#' @rdname quad_active\nanno_left <- function(size = NULL, free_guides = waiver(), initialize = NULL,\n what = waiver()) {\n quad_switch_anno(\n size = size, free_guides = free_guides,\n initialize = initialize, what = what,\n position = \"left\"\n )\n}\n\n#' @export\n#' @rdname quad_active\nanno_bottom <- function(size = NULL, free_guides = waiver(), initialize = NULL,\n what = waiver()) {\n quad_switch_anno(\n size = size, free_guides = free_guides,\n initialize = initialize, what = what,\n position = \"bottom\"\n )\n}\n\n#' @export\n#' @rdname quad_active\nanno_right <- function(size = NULL, free_guides = waiver(), initialize = NULL,\n what = waiver()) {\n quad_switch_anno(\n size = size, free_guides = free_guides,\n initialize = initialize, what = what,\n position = \"right\"\n )\n}\n\nquad_switch_anno <- function(position, size, free_guides, initialize, what,\n call = caller_call()) {\n if (!is.null(size)) size <- check_size(size, call = call)\n assert_layout_position(free_guides, call = call)\n if (!is.waive(what)) what <- check_stack_context(what, call = call)\n assert_bool(initialize, allow_null = TRUE)\n structure(\n list(\n position = position, size = size,\n free_guides = free_guides, what = what,\n initialize = initialize\n ),\n class = c(\"quad_anno\", \"quad_switch\")\n )\n}\n\n#' Initialize Quad-Layout Annotation\n#'\n#' @description\n#' `r lifecycle::badge(\"deprecated\")`\n#'\n#' This function was deprecated, you can add `stack_layout()` directly.\n#'\n#' @export\n#' @keywords internal\nquad_init <- function(position, data = waiver(), ...) {\n lifecycle::deprecate_stop(\"0.0.6\", \"quad_init()\", \"stack_layout()\")\n}\n\n#' @inherit quad_active title return\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' `quad_switch()` integrates [`quad_active()`] and [`quad_anno()`] into one\n#' function for ease of use. This function allows you to quickly change the\n#' active context of the [`quad_layout()`] and its annotations.\n#'\n#' `hmanno` is an alias for `quad_switch`, with additional arguments for\n#' backward compatibility\n#'\n#' @param position `r rd_quad_position(\"activated\")`. If `NULL`, it sets the\n#' active context to the `r rd_quad()` itself.\n#' @inheritParams rlang::args_dots_empty\n#' @inheritParams quad_active\n#' @examples\n#' ggheatmap(matrix(rnorm(81), nrow = 9)) +\n#' anno_top() +\n#' align_dendro()\n#' @importFrom ggplot2 waiver\n#' @seealso [`quad_active()`]/[`quad_anno()`]\n#' @export\nquad_switch <- function(position = NULL, size = NULL,\n width = NULL, height = NULL, free_guides = waiver(),\n initialize = NULL, what = waiver()) {\n if (is.null(position)) {\n quad_active(width = width, height = height)\n } else {\n position <- match.arg(position, .TLBR)\n quad_switch_anno(\n size = size,\n free_guides = free_guides, what = what,\n initialize = initialize,\n position = position\n )\n }\n}\n\n#' @inheritParams heatmap_layout\n#' @export\n#' @rdname quad_switch\nhmanno <- quad_switch\n"], ["/ggalign/R/layout-chain-.R", "# Used by both `circle_layout()` and `stack_layout()`\n#' @keywords internal\n#' @include layout-.R\nmethods::setClass(\n \"ChainLayout\",\n contains = \"LayoutProto\",\n list(\n data = \"ANY\",\n name = \"character\", # used to provide message\n plot_list = \"list\", # save the list of plots\n design = \"ANY\" # used to align axis\n )\n)\n\n#' Finalize plot modifications from a ChainLayout object.\n#'\n#' This generic function lets a ChainLayout apply any final transformations\n#' to the composed plot before returning it. It does not extract or store\n#' the plot, but instead allows the layout to inject custom modifications\n#' (e.g., spacing guides, annotations, alignment fixes) at the last step.\n#'\n#' @param layout A ChainLayout object.\n#' @param plot The plot being finalized.\n#' @keywords internal\nchain_decorate <- function(layout, plot) UseMethod(\"chain_decorate\")\n\n#' @export\nchain_decorate.ChainLayout <- function(layout, plot) plot\n\n#' @export\nis_layout_discrete.ChainLayout <- function(x, ...) {\n is_discrete_design(x@design)\n}\n\n#' @export\nis_layout_continuous.ChainLayout <- function(x, ...) {\n is_continuous_design(x@design)\n}\n\n#############################################################\n# To-DO: Use double dispatch\n#' @keywords internal\nchain_layout_add <- function(object, layout, object_name) {\n UseMethod(\"chain_layout_add\")\n}\n\n#' @export\nchain_layout_add.layout_title <- function(object, layout, object_name) {\n layout@titles <- update_non_waive(layout@titles, object)\n layout\n}\n\n#' @export\nchain_layout_add.list <- function(object, layout, object_name) {\n for (o in object) layout <- chain_layout_add(o, layout, object_name)\n layout\n}\n\n#' @export\nchain_layout_add.NULL <- function(object, layout, object_name) {\n layout\n}\n\n#' @export\nchain_layout_add.CraftBox <- function(object, layout, object_name) {\n craftsman <- object@craftsman\n # To-Do: Use S7 and double dispatch\n if (is.null(active_index <- layout@active) ||\n is_craftbox(plot <- .subset2(layout@plot_list, active_index))) {\n # unlock the object\n craftsman$unlock()\n\n # we lock the `Craftsman` object to prevent user from modifying this\n # object in `$build_plot()` method, we shouldn't do any calculations in\n # `$build_plot()` method\n on.exit(craftsman$lock())\n\n # initialize the necessary parameters for `Craftsman` object\n if (is_stack_layout(layout)) {\n craftsman$direction <- layout@direction\n craftsman$position <- .subset2(layout@heatmap, \"position\")\n } else if (is_circle_layout(layout)) {\n # we treat circle layout as a vertical stack layout\n craftsman$direction <- \"vertical\"\n }\n craftsman$in_linear <- is_linear(layout)\n craftsman$layout_name <- object_name(layout)\n\n # firstly, we let the object do some changes in the layout\n layout <- craftsman$interact_layout(layout)\n\n # this step, the object will act with the stack layout\n # group rows into panel or reorder rows, we can also\n # initialize object data\n new_design <- craftsman$setup_design(layout@design)\n\n # initialize the plot object\n object@plot <- craftsman$setup_plot(object@plot)\n\n layout <- chain_add_plot(layout, object, object@active, object_name)\n } else { # should be a QuadLayout object\n plot <- quad_layout_add(object, plot, object_name)\n layout@plot_list[[active_index]] <- plot\n new_design <- slot(plot, layout@direction)\n }\n update_design(layout, design = new_design, object_name = object_name)\n}\n\n#' @export\nchain_layout_add.continuous_limits <- function(object, layout, object_name) {\n if (is_discrete_design(layout@design)) {\n cli_abort(c(\n sprintf(\n \"Cannot add {.var {object_name}} to %s\",\n object_name(layout)\n ),\n i = sprintf(\n \"%s cannot align continuous variables\",\n object_name(layout)\n )\n ))\n }\n update_design(layout, design = object, object_name = object_name)\n}\n\n#' @export\nchain_layout_add.ggplot <- function(object, layout, object_name) {\n chain_layout_add(ggfree(data = object), layout, object_name)\n}\n\n# Add ggplot2 elements\n#' @export\nchain_layout_add.default <- function(object, layout, object_name) {\n if (is.null(active_index <- layout@active)) {\n cli_abort(c(\n sprintf(\n \"Cannot add {.var {object_name}} to %s\",\n object_name(layout)\n ),\n i = \"No active plot component\",\n i = paste(\n \"Did you forget to initialize a {.cls ggplot} object\",\n \"with {.fn ggalign} or {.fn ggfree}?\"\n )\n ))\n }\n plot <- .subset2(layout@plot_list, active_index)\n if (is_craftbox(plot)) {\n plot <- chain_plot_add(plot, object, object_name, TRUE)\n } else {\n plot <- quad_layout_add(object, plot, object_name)\n }\n layout@plot_list[[active_index]] <- plot\n layout\n}\n\n#' @export\nchain_layout_add.layout_theme <- function(object, layout, object_name) {\n if (is.null(active_index <- layout@active) ||\n is_craftbox(plot <- .subset2(layout@plot_list, active_index))) {\n layout@theme <- update_layout_theme(layout@theme, object)\n } else {\n layout@plot_list[[active_index]] <- quad_layout_add(\n object, plot, object_name\n )\n }\n layout\n}\n\nchain_plot_add <- function(plot, object, object_name, force) {\n # if `align` has plot, we added the object\n if (force || !is.null(plot@plot)) {\n plot <- craftbox_add(object, plot, object_name)\n }\n plot\n}\n\nchain_add_plot <- function(layout, plot, active, object_name) {\n # set up context index\n plot_list <- layout@plot_list\n if (.subset2(active, \"use\")) {\n active_index <- length(plot_list) + 1L\n } else {\n active_index <- layout@active\n }\n # check the name is unique\n if (!is.na(name <- .subset2(active, \"name\"))) {\n if (any(names(plot_list) == name)) {\n cli_warn(\n \"Adding {.var {object_name}} will replace existing {.field {name}} plot\"\n )\n }\n plot_list[[name]] <- plot\n } else {\n plot_list <- c(plot_list, list(plot))\n }\n\n # add QuadLayout\n layout@plot_list <- plot_list\n layout@active <- active_index\n layout\n}\n\nswitch_chain_plot <- function(layout, what, call = caller_call()) {\n if (!is.waive(what)) {\n if (!is.null(what)) {\n what <- vec_as_location2(\n what,\n vec_size(layout@plot_list),\n vec_names(layout@plot_list),\n missing = \"error\",\n arg = \"what\", call = call\n )\n }\n layout@active <- what\n }\n layout\n}\n\n##############################################################\n# for `stack_layout()` only\n#' @export\nchain_layout_add.ggalign_with_quad <- function(object, layout, object_name) {\n if (!is_stack_layout(layout)) {\n cli_abort(sprintf(\n \"Cannot add {.var {object_name}} to %s\",\n object_name(layout)\n ))\n }\n if (is.null(active_index <- layout@active) ||\n is_craftbox(plot <- .subset2(layout@plot_list, active_index))) {\n cli_abort(c(\n sprintf(\n \"Cannot add {.var {object_name}} to %s\",\n object_name(layout)\n ),\n i = \"Did you forget to add a {.fn quad_layout}?\"\n ))\n } else {\n layout@plot_list[[active_index]] <- quad_layout_add(\n object, plot, object_name\n )\n }\n layout\n}\n\n#' @export\nchain_layout_add.quad_active <- chain_layout_add.ggalign_with_quad\n\n#' @export\nchain_layout_add.quad_anno <- chain_layout_add.quad_active\n\n#' @export\nchain_layout_add.StackLayout <- chain_layout_add.quad_active\n\n#' @export\nchain_layout_add.StackCross <- function(object, layout, object_name) {\n if (!is_stack_layout(layout)) {\n cli_abort(sprintf(\n \"Cannot add {.var {object_name}} to %s\",\n object_name(layout)\n ))\n }\n\n # preventing from adding `stack_cross` with the same direction in this way,\n # `stack_cross()` cannot be added to the heatmap annotation parallelly with\n # the `stack_layout()`\n if (identical(object@direction, layout@direction)) {\n cli_abort(c(\n sprintf(\n \"Cannot add {.var {object_name}} to %s\",\n object_name(layout)\n ),\n i = \"Cannot add {.fn stack_cross} with the same direction as {.fn stack_discrete}.\"\n ))\n }\n NextMethod() # call StackLayout method\n}\n\n#' @export\nchain_layout_add.stack_switch <- function(object, layout, object_name) {\n if (!is_stack_layout(layout)) {\n cli_abort(c(\n sprintf(\n \"Cannot add {.var {object_name}} to %s\",\n object_name(layout)\n ),\n i = \"Did you want to add a {.fn circle_switch}?\"\n ))\n }\n layout <- switch_chain_plot(\n layout, .subset2(object, \"what\"),\n quote(stack_switch())\n )\n if (!is.null(sizes <- .subset2(object, \"sizes\"))) {\n layout@sizes <- sizes\n }\n layout\n}\n\n#' @importFrom methods slot\n#' @export\nchain_layout_add.QuadLayout <- function(object, layout, object_name) {\n if (!is_stack_layout(layout)) {\n cli_abort(sprintf(\n \"Cannot add {.var {object_name}} to %s\",\n object_name(layout)\n ))\n }\n\n # preventing from adding `stack_cross` with the same direction\n # `cross_link()` cannot be added to the heatmap annotation\n # parallelly with the `stack_cross()`\n if (is_horizontal(direction <- layout@direction)) {\n if (is_cross_layout(object@left) || is_cross_layout(object@right)) {\n cli_abort(c(\n sprintf(\n \"Cannot add {.var {object_name}} to %s\",\n object_name(layout)\n ),\n i = sprintf(\n \"{.field left} or {.field right} annotation contains %s\",\n \"{.fn stack_cross}\"\n )\n ))\n }\n } else if (is_cross_layout(object@top) || is_cross_layout(object@bottom)) {\n cli_abort(c(\n sprintf(\n \"Cannot add {.var {object_name}} to %s\",\n object_name(layout)\n ),\n i = sprintf(\n \"{.field top} or {.field bottom} annotation contains %s\",\n \"{.fn stack_cross}\"\n )\n ))\n }\n\n # check quad layout is compatible with stack layout\n quad_data <- object@data\n stack_design <- layout@design\n quad_design <- slot(object, direction)\n if (is_continuous_design(quad_design)) {\n if (is_discrete_design(stack_design)) {\n cli_abort(c(\n sprintf(\n \"Cannot add %s to %s\",\n object_name(object), object_name(layout)\n ),\n i = sprintf(\n \"%s cannot align continuous variable\",\n object_name(layout)\n )\n ))\n }\n # `quad_layout()` will align continuous variables,\n # `data` can be `NULL`\n extra_design <- slot(object, vec_set_difference(\n c(\"vertical\", \"horizontal\"), direction\n ))\n allow_null <- is_continuous_design(extra_design)\n if (is.waive(quad_data) || is.function(quad_data)) {\n # check if we should initialize the `quad_layout()` data\n if (is.null(stack_data <- layout@data)) {\n if (allow_null) {\n quad_data <- NULL\n } else {\n cli_abort(c(\n sprintf(\n \"you must provide {.arg data} argument in %s\",\n object_name(object)\n ),\n i = sprintf(\n \"no data was found in %s\",\n object_name(layout)\n )\n ))\n }\n } else {\n data <- stack_data # should be a data frame\n if (is.waive(quad_data)) { # inherit from the stack layout\n if (!allow_null) { # we need a matrix\n cli_abort(c(\n sprintf(\n \"Cannot add %s to %s\",\n object_name(object), object_name(layout)\n ),\n i = sprintf(\n \"{.arg data} in %s is %s, but %s need a {.cls matrix}.\",\n object_name(layout),\n \"{.obj_type_friendly {data}}\",\n object_name(object)\n ),\n i = sprintf(\n \"Try provide {.arg data} in %s\",\n object_name(object)\n )\n ))\n }\n } else { # `quad_data` is a function\n data <- quad_data(data)\n # check the data format is correct\n if (allow_null) { # we need a data frame\n if (!is.data.frame(data)) {\n cli_abort(sprintf(\n \"{.arg data} in %s must return a {.cls data.frame}\",\n object_name(object)\n ))\n }\n } else if (!is.matrix(data)) { # we need a matrix\n cli_abort(sprintf(\n \"{.arg data} in %s must return a {.cls matrix}\",\n object_name(object)\n ))\n } else {\n if (NROW(data) == 0L || ncol(data) == 0L) {\n cli_abort(sprintf(\n \"{.arg data} in %s return an empty matrix\",\n object_name(object)\n ))\n }\n }\n }\n # we initialize the `nobs` of the extra_design for the\n # `quad_layout()`\n if (is_horizontal(direction)) {\n if (is_discrete_design(slot(object, \"vertical\"))) {\n slot(object, \"vertical\")$nobs <- ncol(data)\n }\n } else {\n if (is_discrete_design(slot(object, \"horizontal\"))) {\n slot(object, \"horizontal\")$nobs <- nrow(data)\n }\n }\n }\n # restore the ggalign attribute\n object@data <- ggalign_data_restore(data, stack_data)\n }\n layout_design <- quad_design\n } else if (is_discrete_design(stack_design)) {\n # both `quad_layout()` and `stack_layout()` will align discrete\n # variables\n if (is.waive(quad_data) || is.function(quad_data)) {\n if (is.null(stack_data <- layout@data)) {\n cli_abort(c(\n sprintf(\n \"you must provide {.arg data} argument in %s\",\n object_name(object)\n ),\n i = sprintf(\n \"no data was found in %s\",\n object_name(layout)\n )\n ))\n }\n # set `quad_layout()` data\n data <- switch_direction(direction, stack_data, t(stack_data))\n if (is.function(quad_data)) {\n data <- quad_data(data)\n if (!is.matrix(data)) {\n cli_abort(sprintf(\n \"{.arg data} in %s must return a matrix\",\n object_name(object)\n ))\n }\n if (NROW(data) == 0L || ncol(data) == 0L) {\n cli_abort(sprintf(\n \"{.arg data} in %s return an empty matrix\",\n object_name(object)\n ))\n }\n } else {\n if (NROW(data) == 0L || ncol(data) == 0L) {\n cli_abort(c(\n sprintf(\n \"Cannot use data from %s in %s\",\n object_name(layout), object_name(object)\n ),\n i = sprintf(\n \"{.arg data} in %s is an empty matrix\",\n object_name(layout)\n )\n ))\n }\n }\n # set the `nobs` for `quad_layout()`\n if (is_horizontal(direction)) {\n quad_design$nobs <- nrow(data)\n if (is_discrete_design(slot(object, \"vertical\"))) {\n slot(object, \"vertical\")$nobs <- ncol(data)\n }\n } else {\n quad_design$nobs <- ncol(data)\n if (is_discrete_design(slot(object, \"horizontal\"))) {\n slot(object, \"horizontal\")$nobs <- nrow(data)\n }\n }\n # restore the ggalign attribute\n object@data <- ggalign_data_restore(data, stack_data)\n }\n layout_design <- melt_discrete_design(\n stack_design, quad_design,\n old_name = object_name(layout),\n new_name = object_name\n )\n } else {\n cli_abort(c(\n sprintf(\n \"Cannot add %s to %s\",\n object_name(object), object_name(layout)\n ),\n i = sprintf(\n \"%s cannot align discrete variable\",\n object_name(layout)\n )\n ))\n }\n stack <- chain_add_plot(layout, object, object@plot_active, object_name)\n update_design(\n stack,\n design = layout_design,\n object_name = object_name\n )\n}\n\n##################################################\n#' @export\nchain_layout_add.circle_switch <- function(object, layout, object_name) {\n if (!is_circle_layout(layout)) {\n cli_abort(c(\n sprintf(\n \"Cannot add {.var {object_name}} to %s\",\n object_name(layout)\n ),\n i = \"Did you want to add a {.fn stack_switch}?\"\n ))\n }\n if (!is.waive(radial <- .subset2(object, \"radial\"))) {\n layout@radial <- radial\n }\n if (!is.null(direction <- .subset2(object, \"direction\"))) {\n layout@direction <- direction\n }\n layout <- switch_chain_plot(\n layout, .subset2(object, \"what\"),\n quote(circle_switch())\n )\n layout\n}\n"], ["/ggalign/R/import-standalone-assert.R", "# Standalone file: do not edit by hand\n# Source: https://github.com/Yunuuuu/standalone/blob/HEAD/R/standalone-assert.R\n# Generated by: usethis::use_standalone(\"Yunuuuu/standalone\", \"assert\")\n# ----------------------------------------------------------------------\n#\n# ---\n# repo: Yunuuuu/standalone\n# file: standalone-assert.R\n# last-updated: 2025-04-16\n# license: https://unlicense.org\n# dependencies: [standalone-obj-type.R]\n# imports: rlang\n# ---\n\n# ## Changelog\n# 2025-04-16:\n# - `assert_number_whole` gains `allow_infinite` argument\n#\n# 2025-04-11:\n# - new `.rlang_allow_number`\n# - new `.rlang_check_number`\n# - new `.rlang_check_bool`\n# - new `.rlang_check_string`\n#\n# 2024-11-10:\n# - Added support for S3 object\n#\n# nocov start\n# Following codes were modified from `rlang` package\n\n#' Report if an argument is a specific class\n#'\n#' @param x The object type which does not conform to `what`. Its\n#' `obj_type_friendly()` is taken and mentioned in the error message.\n#' @param what The friendly expected type as a string. Can be a\n#' character vector of expected types, in which case the error\n#' message mentions all of them in an \"or\" enumeration.\n#' @param show_value Passed to `value` argument of `obj_type_friendly()`.\n#' @param show_length Passed to `length` argument of `obj_type_friendly()`.\n#' @param ... Arguments passed to [rlang::abort()].\n#' @importFrom rlang is_missing\n#' @noRd\nassert_ <- function(x, check, what,\n allow_null = FALSE,\n allow_na = FALSE,\n show_value = TRUE,\n show_length = FALSE,\n ...,\n arg = caller_arg(x),\n call = caller_env()) {\n if (!is_missing(x) && (\n (allow_null && is.null(x)) || check(x)\n )) {\n return(invisible(NULL))\n }\n stop_input_type(x, what,\n allow_na = allow_na,\n allow_null = allow_null,\n show_value = show_value,\n show_length = show_length,\n ...,\n arg = arg, call = call\n )\n}\n\nIS_NUMBER_true <- 0\nIS_NUMBER_false <- 1\nIS_NUMBER_oob <- 2\n\n.standalone_types_check_assert_call <- .Call\n\n#' @importFrom rlang ffi_standalone_check_number_1.0.7\n.rlang_check_number <- function(x, allow_decimal,\n min = NULL,\n max = NULL,\n allow_infinite = allow_decimal,\n allow_na = FALSE,\n allow_null = FALSE) {\n .standalone_types_check_assert_call(\n ffi_standalone_check_number_1.0.7,\n x,\n allow_decimal,\n min,\n max,\n allow_infinite,\n allow_na,\n allow_null\n )\n}\n\n#' @importFrom rlang ffi_standalone_is_bool_1.0.7\n.rlang_check_bool <- function(x, allow_na = FALSE, allow_null = FALSE) {\n .standalone_types_check_assert_call(\n ffi_standalone_is_bool_1.0.7,\n x,\n allow_na,\n allow_null\n )\n}\n\n#' @importFrom rlang is_string\n.rlang_check_string <- function(x, allow_empty = TRUE,\n allow_na = FALSE, allow_null = FALSE) {\n if (is_string(x) && !is.na(x)) {\n if (allow_empty || x != \"\") {\n return(TRUE)\n }\n }\n\n if (allow_null && is.null(x)) {\n return(TRUE)\n }\n\n if (allow_na && (identical(x, NA) || identical(x, NA_character_))) {\n return(TRUE)\n }\n\n FALSE\n}\n\n#' @importFrom rlang abort\n.rlang_allow_number <- function(x, exit_code, allow_decimal,\n min = NULL,\n max = NULL,\n allow_na = FALSE,\n allow_null = FALSE) {\n if (allow_decimal) {\n what <- \"a number\"\n } else {\n what <- \"a whole number\"\n }\n if (exit_code == IS_NUMBER_oob) {\n min <- min %||% -Inf\n max <- max %||% Inf\n\n if (min > -Inf && max < Inf) {\n what <- sprintf(\"%s between %s and %s\", what, min, max)\n } else if (x < min) {\n what <- sprintf(\"%s larger than or equal to %s\", what, min)\n } else if (x > max) {\n what <- sprintf(\"%s smaller than or equal to %s\", what, max)\n } else {\n abort(\"Unexpected state in OOB check\", .internal = TRUE)\n }\n }\n allow_what_type(what, allow_na = allow_na, allow_null = allow_null)\n}\n\n# scalar object ----------------------------------\nassert_string <- function(x,\n ...,\n allow_empty = TRUE,\n allow_na = FALSE,\n allow_null = FALSE,\n arg = caller_arg(x),\n call = caller_env()) {\n assert_(\n x = x,\n check = function(x) {\n .rlang_check_string(\n x,\n allow_empty = allow_empty,\n allow_na = allow_na,\n allow_null = allow_null\n )\n },\n what = \"a single string\",\n ...,\n allow_na = allow_na,\n allow_null = allow_null,\n arg = arg,\n call = call\n )\n}\n\n#' @importFrom rlang abort\n.stop_not_number <- function(x,\n exit_code,\n allow_decimal,\n ...,\n min = NULL,\n max = NULL,\n allow_na = FALSE,\n allow_null = FALSE,\n show_value = TRUE,\n show_length = FALSE,\n arg = caller_arg(x),\n call = caller_env()) {\n what <- .rlang_allow_number(\n x = x,\n exit_code = exit_code,\n allow_decimal = allow_decimal,\n min = min, max = max,\n allow_na = allow_na,\n allow_null = allow_null\n )\n if (inherits(arg, \"AsIs\")) {\n format_arg <- identity\n } else {\n format_arg <- function(x) sprintf(\"`%s`\", x)\n }\n message <- sprintf(\n \"%s must be %s, not %s.\",\n format_arg(arg), what,\n obj_type_friendly(x, value = show_value, length = show_length)\n )\n abort(message, ..., call = call, arg = arg)\n}\n\n#' @importFrom rlang is_missing\nassert_number_decimal <- function(x,\n ...,\n min = NULL,\n max = NULL,\n allow_infinite = TRUE,\n allow_na = FALSE,\n allow_null = FALSE,\n arg = caller_arg(x),\n call = caller_env()) {\n if (is_missing(x)) {\n exit_code <- IS_NUMBER_false\n } else if (0 == (exit_code <- .rlang_check_number(\n x,\n allow_decimal = TRUE,\n min = min,\n max = max,\n allow_infinite = allow_infinite,\n allow_na = allow_na,\n allow_null = allow_null\n ))) {\n return(invisible(NULL))\n }\n\n .stop_not_number(\n x,\n ...,\n exit_code = exit_code,\n allow_decimal = TRUE,\n min = min,\n max = max,\n allow_na = allow_na,\n allow_null = allow_null,\n arg = arg,\n call = call\n )\n}\n\n#' @importFrom rlang is_missing\nassert_number_whole <- function(x,\n ...,\n min = NULL,\n max = NULL,\n allow_infinite = FALSE,\n allow_na = FALSE,\n allow_null = FALSE,\n arg = caller_arg(x),\n call = caller_env()) {\n if (is_missing(x)) {\n exit_code <- IS_NUMBER_false\n } else if (0 == (exit_code <- .rlang_check_number(\n x,\n allow_decimal = FALSE,\n min = min,\n max = max,\n allow_infinite = allow_infinite,\n allow_na = allow_na,\n allow_null = allow_null\n ))) {\n return(invisible(NULL))\n }\n\n .stop_not_number(\n x,\n ...,\n exit_code = exit_code,\n allow_decimal = FALSE,\n min = min,\n max = max,\n allow_na = allow_na,\n allow_null = allow_null,\n arg = arg,\n call = call\n )\n}\n\n#' @importFrom rlang ffi_standalone_is_bool_1.0.7\nassert_bool <- function(x,\n ...,\n allow_na = FALSE,\n allow_null = FALSE,\n arg = caller_arg(x),\n call = caller_env()) {\n if (!missing(x) && .rlang_check_bool(x, allow_na, allow_null)) {\n return(invisible(NULL))\n }\n\n stop_input_type(\n x,\n c(\"`TRUE`\", \"`FALSE`\"),\n ...,\n allow_na = allow_na,\n allow_null = allow_null,\n arg = arg,\n call = call\n )\n}\n\n# atomic vector ------------------------------------\n#' @importFrom rlang abort\nassert_character <- function(x,\n ...,\n allow_na = TRUE,\n allow_null = FALSE,\n arg = caller_arg(x),\n call = caller_env()) {\n if (!missing(x)) {\n if (is.character(x)) {\n if (!allow_na && anyNA(x)) {\n abort(\n sprintf(\"`%s` can't contain NA values.\", arg),\n arg = arg, call = call\n )\n }\n return(invisible(NULL))\n }\n\n if (allow_null && is.null(x)) {\n return(invisible(NULL))\n }\n }\n stop_input_type(\n x,\n \"a character vector\",\n ...,\n allow_na = FALSE,\n allow_null = allow_null,\n arg = arg,\n call = call\n )\n}\n\n#' @importFrom rlang abort\nassert_logical <- function(x,\n ...,\n allow_na = TRUE,\n allow_null = FALSE,\n arg = caller_arg(x),\n call = caller_env()) {\n if (!missing(x)) {\n if (is.logical(x)) {\n if (!allow_na && anyNA(x)) {\n abort(\n sprintf(\"`%s` can't contain NA values.\", arg),\n arg = arg, call = call\n )\n }\n return(invisible(NULL))\n }\n if (allow_null && is.null(x)) {\n return(invisible(NULL))\n }\n }\n\n stop_input_type(\n x,\n \"a logical vector\",\n ...,\n allow_na = FALSE,\n allow_null = allow_null,\n arg = arg,\n call = call\n )\n}\n\n# S3 object ----------------------------------------\n#' @importFrom rlang is_string is_missing\nassert_s3_class <- function(x, is_class, what, ...,\n arg = caller_arg(x),\n call = caller_env()) {\n if (is.character(is_class)) {\n class <- is_class\n is_class <- function(x) inherits(x, what = class)\n if (is_missing(what)) what <- sprintf(\"a <%s>\", class)\n }\n assert_(\n x = x, check = is_class,\n what = what,\n ...,\n arg = arg, call = call\n )\n}\n\n# nocov end\n"], ["/ggalign/R/ggmark.R", "#' Add a plot to annotate selected observations\n#'\n#' @param mark A [`mark_draw()`] object to define how to draw the links. Like\n#' [`mark_line()`], [`mark_tetragon()`]. Note the names of the pair links will\n#' be used to define the panel names so must be unique.\n#' @inheritParams ggalign\n#' @param group1,group2 A single boolean value indicating whether to use the\n#' panel group information from the layout as the paired groups. By default,\n#' if no specific observations are selected in `mark`, `ggmark()` will\n#' automatically connect all observations and group them according to the\n#' layout's defined groups.\n#' @param obs_size A single numeric value that indicates the size of a single\n#' observation, ranging from `(0, 1]`.\n#' @section ggplot2 specification:\n#' `ggmark` initializes a ggplot object. The underlying data is created using\n#' [`fortify_data_frame()`]. Please refer to it for more details.\n#'\n#' In addition, the following columns will be added to the data frame:\n#'\n#' - `.panel`: the panel for the aligned axis. It means `x-axis` for vertical\n#' stack layout (including top and bottom annotation), `y-axis` for\n#' horizontal stack layout (including left and right annotation).\n#'\n#' - `.names` ([`vec_names()`][vctrs::vec_names]) and `.index`\n#' ([`vec_size()`][vctrs::vec_size()]/[`NROW()`]): a character names (only\n#' applicable when names exists) and an integer of index of the original\n#' data.\n#'\n#' - `.hand`: A factor with levels `c(\"left\", \"right\")` for horizontal stack\n#' layouts, or `c(\"top\", \"bottom\")` for vertical stack layouts, indicating\n#' the position of the linked observations.\n#'\n#' @examples\n#' set.seed(123)\n#' small_mat <- matrix(rnorm(56), nrow = 7)\n#' rownames(small_mat) <- paste0(\"row\", seq_len(nrow(small_mat)))\n#' colnames(small_mat) <- paste0(\"column\", seq_len(ncol(small_mat)))\n#'\n#' # mark_line\n#' ggheatmap(small_mat) +\n#' theme(axis.text.x = element_text(hjust = 0, angle = -60)) +\n#' anno_right() +\n#' align_kmeans(3L) +\n#' ggmark(mark_line(I(1:3) ~ NULL)) +\n#' geom_boxplot(aes(.names, value)) +\n#' theme(plot.margin = margin(l = 0.1, t = 0.1, unit = \"npc\"))\n#'\n#' # mark_tetragon\n#' ggheatmap(small_mat) +\n#' theme(axis.text.x = element_text(hjust = 0, angle = -60)) +\n#' anno_right() +\n#' align_kmeans(3L) +\n#' ggmark(mark_tetragon(I(1:3) ~ NULL)) +\n#' geom_boxplot(aes(.names, value)) +\n#' theme(plot.margin = margin(l = 0.1, t = 0.1, unit = \"npc\"))\n#' @importFrom rlang list2\n#' @export\nggmark <- function(mark, data = waiver(), mapping = aes(), ...,\n group1 = NULL, group2 = NULL,\n obs_size = 1, size = NULL, active = NULL) {\n if (!inherits(mark, \"ggalign_mark_draw\")) {\n cli_abort(\"{.arg mark} must be a {.fn mark_draw} object\")\n }\n assert_obs_size(obs_size)\n assert_active(active)\n active <- update_active(active, new_active(use = TRUE))\n assert_bool(group1, allow_null = TRUE)\n assert_bool(group2, allow_null = TRUE)\n new_craftbox(\n MarkGg,\n # fields added to `MarkGg`\n input_data = allow_lambda(data), # used by AlignGg\n params = list2(...), # used by AlignGg\n mark = mark, # used by MarkGg\n group1 = group1, group2 = group2,\n obs_size = obs_size,\n\n # slot\n plot = ggplot(mapping = mapping),\n size = size,\n schemes = default_schemes(data, th = theme_panel_border()),\n active = active\n )\n}\n\n#' @importFrom ggplot2 ggproto ggplot margin element_rect\nMarkGg <- ggproto(\"MarkGg\", Craftsman,\n free_facet = TRUE,\n free_limits = TRUE,\n interact_layout = function(self, layout) {\n layout_name <- self$layout_name\n if (!self$in_linear) { # only used for linear coordinate\n cli_abort(c(\n sprintf(\n \"Cannot add %s to %s\",\n object_name(self), layout_name\n ),\n i = sprintf(\n \"%s can only be used in linear layout\",\n object_name(self)\n )\n ))\n }\n if (is_layout_continuous(layout)) { # only used for discrete variable\n # ggmark special for discrete variables\n cli_abort(c(\n sprintf(\"Cannot add %s to %s\", object_name(self), layout_name),\n i = sprintf(\"%s cannot align discrete variables\", layout_name)\n ))\n }\n ans <- ggproto_parent(AlignGg, self)$interact_layout(layout)\n self$labels0 <- self$labels # CrossMark uses `labels0`\n ans\n },\n build_plot = function(self, plot, design, extra_design = NULL,\n previous_design = NULL) {\n if (is.null(.subset2(design, \"nobs\"))) {\n cli_abort(sprintf(\n \"you must initialize %s before drawing %s\",\n self$layout_name, object_name(self)\n ), call = self$call)\n }\n mark <- self$mark\n\n # parse links --------------------------------------------\n links <- .subset2(mark, \"links\")\n group1 <- self$group1\n group2 <- self$group2\n position <- self$position\n if (is_empty(links) && is.null(group1) && is.null(group2)) {\n # guess group1 and group2 from position\n if (is.null(position)) { # a normal stack layout\n group1 <- TRUE\n } else if (any(position == c(\"top\", \"left\"))) {\n group2 <- TRUE\n } else {\n group1 <- TRUE\n }\n }\n full_data <- split(\n seq_len(.subset2(design, \"nobs\")),\n .subset2(design, \"panel\")\n )\n if (isTRUE(group1) && isTRUE(group2)) {\n extra_links <- mapply(function(l1, l2) {\n new_pair_link(I(l1), I(l2))\n }, full_data, full_data, SIMPLIFY = FALSE)\n } else if (isTRUE(group1)) {\n extra_links <- lapply(full_data, function(l) {\n new_pair_link(hand1 = I(l))\n })\n } else if (isTRUE(group2)) {\n extra_links <- lapply(full_data, function(l) {\n new_pair_link(hand2 = I(l))\n })\n } else {\n extra_links <- NULL\n }\n\n # unlock the object\n self$unlock()\n self$mark$links <- vec_c(extra_links, links)\n on.exit(self$mark <- mark, add = TRUE) # restore the original `mark`\n on.exit(self$lock(), add = TRUE)\n\n # setup the plot\n plot <- ggproto_parent(CrossMark, self)$build_plot(\n plot,\n design,\n extra_design,\n previous_design %||% design\n )\n plot_data <- plot$data\n\n # prepare data for the plot ------------------------------\n if (!is.null(data <- self$data)) {\n plot_data <- inner_join(plot_data, data, by = \".index\")\n }\n gguse_data(plot, ggalign_data_restore(plot_data, data))\n },\n finish_plot = function(self, plot, schemes, theme) {\n ggproto_parent(CrossMark, self)$finish_plot(plot, schemes, theme)\n },\n summary = function(self, plot) {\n header <- ggproto_parent(Craftsman, self)$summary(plot)\n c(header, \" Add plot to annotate observations\")\n }\n)\n"], ["/ggalign/R/alignpatch-align_plots.R", "#' Arrange multiple plots into a grid\n#'\n#' @param ... <[dyn-dots][rlang::dyn-dots]> A list of plots, ususally the\n#' ggplot object. Use `NULL` to indicate an empty spacer.\n#' @param ncol,nrow The dimensions of the grid to create - if both are `NULL` it\n#' will use the same logic as [`facet_wrap()`][ggplot2::facet_wrap] to set the\n#' dimensions\n#' @param byrow If `FALSE` the plots will be filled in in column-major order.\n#' @param widths,heights The relative widths and heights of each column and row\n#' in the grid. Will get repeated to match the dimensions of the grid. The\n#' special value of `NA` will behave as `1null` unit unless a fixed aspect plot\n#' is inserted in which case it will allow the dimension to expand or contract\n#' to match the aspect ratio of the content.\n#' @param area Specification of the location of areas in the layout. Can\n#' either be specified as a text string or by concatenating calls to\n#' [`area()`] together.\n#' @param guides A string with one or more of `r oxford_and(c(.tlbr, \"i\"))`\n#' indicating which side of guide legends should be collected. Defaults to\n#' [`waiver()`][ggplot2::waiver()], which inherits from the parent layout. If\n#' there is no parent layout, or if `NULL` is provided, no guides will be\n#' collected.\n#' @param theme A [`theme()`][ggplot2::theme] object used to customize various\n#' elements of the layout. By default, the theme will inherit from the parent\n#' `layout`.\n#' @param design An alias for `area`, retained for backward compatibility.\n#' @return An `AlignPatches` object.\n#' @seealso\n#' - [layout_design()]\n#' - [layout_title()]\n#' - [layout_theme()]\n#' @examples\n#' # directly copied from patchwork\n#' p1 <- ggplot(mtcars) +\n#' geom_point(aes(mpg, disp))\n#' p2 <- ggplot(mtcars) +\n#' geom_boxplot(aes(gear, disp, group = gear))\n#' p3 <- ggplot(mtcars) +\n#' geom_bar(aes(gear)) +\n#' facet_wrap(~cyl)\n#' p4 <- ggplot(mtcars) +\n#' geom_bar(aes(carb))\n#' p5 <- ggplot(mtcars) +\n#' geom_violin(aes(cyl, mpg, group = cyl))\n#'\n#' # Either add the plots as single arguments\n#' align_plots(p1, p2, p3, p4, p5)\n#'\n#' # Or use bang-bang-bang to add a list\n#' align_plots(!!!list(p1, p2, p3), p4, p5)\n#'\n#' # Match plots to areas by name\n#' area <- \"#BB\n#' AA#\"\n#' align_plots(B = p1, A = p2, area = area)\n#'\n#' # Compare to not using named plot arguments\n#' align_plots(p1, p2, area = area)\n#' @export\nalign_plots <- function(..., ncol = NULL, nrow = NULL, byrow = TRUE,\n widths = NA, heights = NA, area = NULL,\n guides = waiver(), theme = NULL, design = NULL) {\n plots <- rlang::dots_list(..., .ignore_empty = \"all\", .named = NULL)\n nms <- names(plots)\n area <- area %||% design\n if (!is.null(nms) && is.character(area)) {\n area_names <- unique(trimws(.subset2(strsplit(area, \"\"), 1L)))\n area_names <- sort(vec_set_difference(area_names, c(\"\", \"#\")))\n if (all(nms %in% area_names)) {\n plot_list <- vector(\"list\", length(area_names))\n names(plot_list) <- area_names\n plot_list[nms] <- plots\n plots <- plot_list\n }\n }\n\n for (plot in plots) {\n if (!has_method(plot, \"alignpatch\", default = FALSE)) {\n cli_abort(\"Cannot align {.obj_type_friendly {plot}}\")\n }\n }\n\n # setup layout parameters\n layout <- layout_design(\n ncol = ncol, nrow = nrow, byrow = byrow,\n widths = widths, heights = heights, area = area,\n guides = guides\n )\n AlignPatches(plots = plots, layout = layout, theme = theme)\n}\n\n#' @importFrom ggplot2 is_theme\n#' @importFrom S7 new_object S7_object prop prop<-\nAlignPatches <- S7::new_class(\"AlignPatches\",\n properties = list(\n plots = S7::new_property(\n S7::class_list,\n setter = function(self, value) {\n if (!is.null(prop(self, \"plots\"))) {\n cli_abort(\"'@plots' is read-only\")\n }\n prop(self, \"plots\", check = FALSE) <- value\n self\n }\n ),\n layout = S7::new_property(\n S7::class_list,\n setter = function(self, value) {\n if (!inherits(value, \"layout_design\")) {\n cli_abort(\"'@layout' must be a {.fn layout_design} object\")\n }\n old <- prop(self, \"layout\") %||% list(\n ncol = NULL, nrow = NULL, byrow = TRUE,\n widths = NA, heights = NA, area = NULL,\n guides = waiver()\n )\n guides <- .subset2(value, \"guides\")\n value$guides <- NULL # guides need special consideration\n old <- update_non_waive(old, value)\n if (is.null(guides) || is.waive(guides)) {\n old[\"guides\"] <- list(guides)\n } else if (!identical(guides, NA)) {\n old[\"guides\"] <- list(setup_guides(guides))\n }\n prop(self, \"layout\", check = FALSE) <- old\n self\n }\n ),\n titles = S7::new_property(\n S7::class_list,\n setter = function(self, value) {\n if (!inherits(value, \"layout_title\")) {\n cli_abort(\"'@titles' must be a {.fn layout_title} object'\")\n }\n old <- prop(self, \"titles\") %||%\n list(title = NULL, subtitle = NULL, caption = NULL)\n prop(self, \"titles\", check = FALSE) <- update_non_waive(\n old, value\n )\n self\n }\n ),\n theme = S7::new_property(\n S7::class_any,\n setter = function(self, value) {\n if (!is.null(value) && !is_theme(value)) {\n cli_abort(\"'@theme' must be a {.cls theme} object'\")\n }\n if (is.null(prop(self, \"theme\")) || is.null(value)) {\n prop(self, \"theme\", check = FALSE) <- value\n } else {\n prop(self, \"theme\", check = FALSE) <- prop(self, \"theme\") +\n value\n }\n self\n },\n default = NULL\n )\n ),\n constructor = function(plots = list(), layout = NULL,\n titles = NULL, theme = NULL) {\n out <- new_object(\n S7_object(),\n plots = plots,\n layout = layout %||% layout_design(),\n titles = titles %||% layout_title(),\n theme = theme\n )\n # for backward compatibility\n add_class(out, \"alignpatches\")\n }\n)\n\n#' @importFrom rlang caller_env\nlocal(\n S7::method(`+`, list(AlignPatches, S7::class_any)) <-\n function(e1, e2) {\n # Get the name of what was passed in as e2, and pass along so that\n # it can be displayed in error messages\n if (missing(e2)) {\n cli_abort(c(\n \"Cannot use {.code +} with a single argument.\",\n \"i\" = \"Did you accidentally put {.code +} on a new line?\"\n ))\n }\n e2name <- deparse(substitute(e2, env = caller_env(2)))\n alignpatches_add(e2, e1, e2name)\n }\n)\n\n#' @importFrom S7 S7_dispatch\nalignpatches_add <- S7::new_generic(\n \"alignpatches_add\", \"object\",\n function(object, patches, objectname) S7_dispatch()\n)\n\nS7::method(alignpatches_add, S7::class_any) <-\n function(object, patches, objectname) {\n if (is.null(object)) return(patches) # styler: off\n cli_abort(c(\n \"Cannot add {objectname}\",\n \"x\" = \"Only other layout elements or compatible objects can be added.\"\n ))\n }\n\n#############################################################\n#' Define the grid to compose plots in\n#'\n#' To control how different plots are laid out, you need to add a layout design\n#' specification. If you are nesting grids, the layout is scoped to the current\n#' nesting level.\n#' @inheritParams align_plots\n#' @return A `layout_design` object.\n#' @examples\n#' p1 <- ggplot(mtcars) +\n#' geom_point(aes(mpg, disp))\n#' p2 <- ggplot(mtcars) +\n#' geom_boxplot(aes(gear, disp, group = gear))\n#' p3 <- ggplot(mtcars) +\n#' geom_bar(aes(gear)) +\n#' facet_wrap(~cyl)\n#' align_plots(p1, p2, p3) +\n#' layout_design(nrow = 1L)\n#' align_plots(p1, p2, p3) +\n#' layout_design(ncol = 1L)\n#' @importFrom ggplot2 waiver\n#' @export\nlayout_design <- function(ncol = waiver(), nrow = waiver(), byrow = waiver(),\n widths = waiver(), heights = waiver(),\n area = waiver(), guides = NA, design = waiver()) {\n if (!is.waive(ncol)) {\n assert_number_whole(ncol, min = 1, allow_na = TRUE, allow_null = TRUE)\n }\n if (!is.waive(nrow)) {\n assert_number_whole(nrow, min = 1, allow_na = TRUE, allow_null = TRUE)\n }\n if (!is.waive(byrow)) assert_bool(byrow)\n area <- area %|w|% design\n if (!is.waive(area)) area <- as_areas(area)\n if (!identical(guides, NA) && !is.waive(guides) && !is.null(guides)) {\n assert_guides(guides)\n }\n structure(\n list(\n ncol = ncol,\n nrow = nrow,\n byrow = byrow,\n widths = widths,\n heights = heights,\n area = area,\n guides = guides\n ),\n class = c(\"layout_design\", \"plot_layout\")\n )\n}\n\nS3_layout_design <- S7::new_S3_class(\"layout_design\")\n\nS7::method(alignpatches_add, S3_layout_design) <-\n function(object, patches, objectname) {\n patches@layout <- object\n patches\n }\n\nS7::method(alignpatches_add, S7::new_S3_class(\"plot_layout\")) <-\n function(object, patches, objectname) {\n object$area <- object$design # pathwork use `design`\n object <- .subset(object, names(layout_design()))\n if (is.waive(object$guides)) {\n object$guides <- NA\n } else if (identical(object$guides, \"auto\")) {\n object$guides <- waiver()\n } else if (identical(object$guides, \"collect\")) {\n object$guides <- \"tlbr\"\n } else if (identical(object$guides, \"keep\")) {\n object[\"guides\"] <- list(NULL)\n }\n alignpatches_add(add_class(object, \"layout_design\"), patches)\n }\n\n##############################################################\n#' Annotate the whole layout\n#'\n#' @inheritParams ggplot2::labs\n#' @return A `layout_title` object.\n#' @examples\n#' p1 <- ggplot(mtcars) +\n#' geom_point(aes(mpg, disp))\n#' p2 <- ggplot(mtcars) +\n#' geom_boxplot(aes(gear, disp, group = gear))\n#' p3 <- ggplot(mtcars) +\n#' geom_bar(aes(gear)) +\n#' facet_wrap(~cyl)\n#' align_plots(p1, p2, p3) +\n#' layout_title(title = \"I'm title\")\n#' @importFrom ggplot2 waiver\n#' @export\nlayout_title <- function(title = waiver(), subtitle = waiver(),\n caption = waiver()) {\n if (!is.waive(title)) assert_string(title, allow_null = TRUE)\n if (!is.waive(subtitle)) assert_string(subtitle, allow_null = TRUE)\n if (!is.waive(caption)) assert_string(caption, allow_null = TRUE)\n structure(\n list(title = title, subtitle = subtitle, caption = caption),\n class = c(\"layout_title\", \"plot_annotation\")\n )\n}\n\nS3_layout_title <- S7::new_S3_class(\"layout_title\")\n\nS7::method(alignpatches_add, S3_layout_title) <-\n function(object, patches, objectname) {\n patches@titles <- object\n patches\n }\n\n##############################################################\n#' Modify theme of the layout\n#'\n#' @inherit ggplot2::theme\n#' @param ... A [`theme()`][ggplot2::theme] object or additional element\n#' specifications not part of base ggplot2. In general, these should also be\n#' defined in the `element tree` argument. [`Splicing`][rlang::splice] a list\n#' is also supported.\n#'\n#' @details\n#' A [`theme()`][ggplot2::theme] object used to customize various elements of\n#' the layout, including `guides`, `title`, `subtitle`, `caption`, `margins`,\n#' `panel.border`, and `background`. By default, the theme will inherit from the\n#' parent `layout`.\n#'\n#' - `guides`, `panel.border`, and `background` will always be used even for the\n#' nested `alignpatches` object.\n#'\n#' - `title`, `subtitle`, `caption`, and `margins` will be added for the\n#' top-level `alignpatches` object only.\n#'\n#' @examples\n#' p1 <- ggplot(mtcars) +\n#' geom_point(aes(mpg, disp))\n#' p2 <- ggplot(mtcars) +\n#' geom_boxplot(aes(gear, disp, group = gear))\n#' p3 <- ggplot(mtcars) +\n#' geom_bar(aes(gear)) +\n#' facet_wrap(~cyl)\n#' align_plots(\n#' p1 + theme(plot.background = element_blank()),\n#' p2 + theme(plot.background = element_blank()),\n#' p3 + theme(plot.background = element_blank())\n#' ) +\n#' layout_theme(plot.background = element_rect(fill = \"red\"))\n#' @importFrom ggplot2 theme\n#' @export\nlayout_theme <- rlang::new_function(\n # We utilize editor completion by listing all `theme()` arguments here.\n # By placing `...` at the beginning, we can check if the first\n # following argument is a `theme()` object rather than individual theme\n # elements.\n c(\n rlang::exprs(... = ),\n .subset(\n rlang::fn_fmls(theme),\n vec_set_difference(names(rlang::fn_fmls(theme)), \"...\")\n )\n ),\n quote({\n elements <- ggfun(\"find_args\")(..., complete = NULL, validate = NULL)\n ans <- theme(!!!elements)\n th <- NULL\n for (i in seq_len(...length())) {\n if (inherits(t <- ...elt(i), \"theme\")) {\n th <- ggfun(\"add_theme\")(th, t)\n }\n }\n add_class(ggfun(\"add_theme\")(th, ans), \"layout_theme\")\n })\n)\n\nS3_layout_theme <- S7::new_S3_class(\"layout_theme\")\n\nS7::method(alignpatches_add, S3_layout_theme) <-\n function(object, patches, objectname) {\n patches@theme <- object\n patches\n }\n\nS7::method(alignpatches_add, S7::new_S3_class(\"plot_annotation\")) <-\n function(object, patches, objectname) {\n patches@titles <- .subset(object, names(layout_title()))\n patches@theme <- .subset2(object, \"theme\")\n patches\n }\n\nupdate_layout_theme <- function(old, new) {\n if (is.null(old) || is.null(new)) return(new) # styler: off\n old + new\n}\n\n#' Add layout annotation (internal use)\n#'\n#' This function is a placeholder for future extensions.\n#' If you're trying to apply a theme, use [layout_theme()] instead.\n#'\n#' @param ... Currently unused. May accept a theme in the future.\n#' @param theme A theme object. If not `waiver()`, an error will be raised.\n#'\n#' @return None. This function is used for input validation.\n#' @importFrom ggplot2 is_theme\n#' @export\n#' @keywords internal\nlayout_annotation <- function(..., theme = waiver()) {\n if (is_theme(...elt(1)) || !is.waive(theme)) {\n cli_abort(\"Please use {.fn layout_theme} instead; {.fn layout_annotation} is reserved for future extensions.\")\n }\n}\n"], ["/ggalign/R/grid-grob-magick.R", "#' Rasterize a grob object with magick\n#'\n#' @param grob A [`grob()`][grid::grob]. Use [`patch()`] to convert any objects\n#' into a `grob`.\n#' @param magick A function (purrr-style formula is accepted) that takes an\n#' [`image_read()`][magick::image_read] object as input and returns an object\n#' compatible with [`as.raster()`][grDevices::as.raster]. You can use any of\n#' the `image_*()` functions from the **magick** package to process the raster\n#' image.\n#' @param res An integer sets the desired resolution in pixels.\n#' @inheritParams rlang::args_dots_empty\n#' @inheritParams grid::rasterGrob\n#' @return A `magickGrob` object.\n#' @export\nmagickGrob <- function(grob, magick = NULL, ...,\n res = NULL, interpolate = FALSE,\n name = NULL, vp = NULL) {\n rlang::check_installed(\"magick\", \"to use `magickGrob()`\")\n if (!is.null(magick) && !is.function(magick <- allow_lambda(magick))) {\n cli_abort(\"{.arg magick} must be a function\")\n }\n assert_number_whole(res, min = 1, allow_null = TRUE)\n assert_bool(interpolate)\n magickGrob0(\n grob = grob, magick = magick, ..., res = res,\n interpolate = interpolate, name = name, vp = vp\n )\n}\n\nmagickGrob0 <- function(grob, ...) UseMethod(\"magickGrob0\")\n\n#' @importFrom grid gTree\n#' @export\nmagickGrob0.grob <- function(grob, magick = NULL, ...,\n res = NULL, interpolate = FALSE,\n name = NULL, vp = NULL) {\n rlang::check_dots_empty()\n gTree(\n grob = grob, magick = magick, res = res,\n interpolate = interpolate, name = name, vp = vp,\n cl = \"magickGrob\"\n )\n}\n\n#' @importFrom grid gTree\n#' @export\nmagickGrob0.gList <- function(grob, ...) {\n magickGrob0(grob = gTree(children = grob), ...)\n}\n\n#' @importFrom grid editGrob\n#' @importFrom rlang inject\n#' @export\nmagickGrob0.magickGrob <- function(grob, magick = waiver(), ...,\n res = waiver(), interpolate = waiver(),\n name = waiver(), vp = waiver()) {\n rlang::check_dots_empty()\n params <- list(\n magick = magick, res = res,\n interpolate = interpolate, name = name, vp = vp\n )\n params <- params[!vapply(params, is.waive, logical(1L), USE.NAMES = FALSE)]\n inject(editGrob(grob, !!!params))\n}\n\n#' @export\nmagickGrob0.default <- function(grob, ...) {\n cli_abort(\"{.arg grob} must be a {.cls grob} object\")\n}\n\n# preDraw:\n# - makeContext\n# - pushvpgp\n# - preDrawDetails: by default, do noting\n# makeContent:\n# drawDetails:\n# postDraw:\n# - postDrawDetails: by default, do noting\n# - popgrobvp\n#' @importFrom grid makeContent unit convertHeight convertWidth viewport gList\n#' @export\nmakeContent.magickGrob <- function(x) {\n # Grab viewport information\n width <- convertWidth(unit(1, \"npc\"), \"pt\", valueOnly = TRUE)\n height <- convertHeight(unit(1, \"npc\"), \"pt\", valueOnly = TRUE)\n\n # Grab grob metadata\n plot_res <- convertWidth(unit(1, \"inch\"), \"pt\", valueOnly = TRUE)\n res <- .subset2(x, \"res\") %||% plot_res\n\n magick <- .subset2(x, \"magick\")\n interpolate <- .subset2(x, \"interpolate\")\n\n # Track current device\n old_dev <- grDevices::dev.cur()\n\n # Reset current device upon function exit\n on.exit(grDevices::dev.set(old_dev), add = TRUE)\n\n # open the magick raster device\n image <- magick::image_graph(\n width = width * res / plot_res,\n height = height * res / plot_res,\n bg = NA_character_, res = res,\n clip = FALSE, antialias = FALSE\n )\n\n # Render the grob\n grid::pushViewport(viewport())\n\n # Clean up the grob for rendering\n grid::grid.draw(.subset2(x, \"grob\")) # should respect the viewport of `x`\n grid::popViewport()\n grDevices::dev.off()\n on.exit(magick::image_destroy(image), add = TRUE)\n\n # run `magick` when necessary\n if (!is.null(magick)) image <- magick(image)\n\n # Use native raster instead\n raster <- grDevices::as.raster(image, native = TRUE)\n\n # Forward raster grob\n setChildren(x, children = gList(\n grid::rasterGrob(\n raster, # should contain current area of full viewport\n x = 0.5, y = 0.5,\n height = unit(height, \"pt\"),\n width = unit(width, \"pt\"),\n default.units = \"npc\",\n just = \"center\",\n interpolate = interpolate\n )\n ))\n}\n"], ["/ggalign/R/import-standalone-obj-type.R", "# Standalone file: do not edit by hand\n# Source: https://github.com/Yunuuuu/standalone/blob/HEAD/R/standalone-obj-type.R\n# Generated by: usethis::use_standalone(\"Yunuuuu/standalone\", \"obj-type\")\n# ----------------------------------------------------------------------\n#\n# ---\n# repo: Yunuuuu/standalone\n# file: standalone-obj-type.R\n# last-updated: 2025-04-11\n# license: https://unlicense.org\n# imports: rlang (>= 1.1.0)\n# ---\n#\n# ## Changelog\n# 2025-04-11:\n# - new `allow_what_type`\n#\n# 2024-11-10:\n# - `obj_type_friendly()` gains a `length` argument to control whether to show\n# the length of the vector.\n# - `stop_input_type()` gains a `show_length` argument passed to\n# `obj_type_friendly`.\n#\n# 2024-02-14:\n# - `obj_type_friendly()` now works for S7 objects.\n#\n# 2023-05-01:\n# - `obj_type_friendly()` now only displays the first class of S3 objects.\n#\n# 2023-03-30:\n# - `stop_input_type()` now handles `I()` input literally in `arg`.\n#\n# 2022-10-04:\n# - `obj_type_friendly(value = TRUE)` now shows numeric scalars\n# literally.\n# - `stop_friendly_type()` now takes `show_value`, passed to\n# `obj_type_friendly()` as the `value` argument.\n#\n# 2022-10-03:\n# - Added `allow_na` and `allow_null` arguments.\n# - `NULL` is now backticked.\n# - Better friendly type for infinities and `NaN`.\n#\n# 2022-09-16:\n# - Unprefixed usage of rlang functions with `rlang::` to\n# avoid onLoad issues when called from rlang (#1482).\n#\n# 2022-08-11:\n# - Prefixed usage of rlang functions with `rlang::`.\n#\n# 2022-06-22:\n# - `friendly_type_of()` is now `obj_type_friendly()`.\n# - Added `obj_type_oo()`.\n#\n# 2021-12-20:\n# - Added support for scalar values and empty vectors.\n# - Added `stop_input_type()`\n#\n# 2021-06-30:\n# - Added support for missing arguments.\n#\n# 2021-04-19:\n# - Added support for matrices and arrays (#141).\n# - Added documentation.\n# - Added changelog.\n#\n# nocov start\n# Following codes were modified from `rlang` package\n\n#' @param x The object type which does not conform to `what`. Its\n#' `obj_type_friendly()` is taken and mentioned in the error message.\n#' @param show_value Passed to `value` argument of `obj_type_friendly()`.\n#' @param show_length Passed to `length` argument of `obj_type_friendly()`.\n#' @param ... Arguments passed to [abort()].\n#' @inheritParams args_error_context\n#' @importFrom rlang caller_arg caller_env abort\n#' @noRd\nstop_input_type <- function(x,\n what,\n ...,\n allow_na = FALSE,\n allow_null = FALSE,\n show_value = TRUE,\n show_length = FALSE,\n arg = caller_arg(x),\n call = caller_env()) {\n what <- allow_what_type(\n what,\n allow_na = allow_na,\n allow_null = allow_null\n )\n if (inherits(arg, \"AsIs\")) {\n format_arg <- identity\n } else {\n format_arg <- function(x) sprintf(\"`%s`\", x)\n }\n message <- sprintf(\n \"%s must be %s, not %s.\",\n format_arg(arg), what,\n obj_type_friendly(x, value = show_value, length = show_length)\n )\n abort(message, ..., call = call, arg = arg)\n}\n\n#' @param what The friendly expected type as a string. Can be a\n#' character vector of expected types, in which case the error\n#' message mentions all of them in an \"or\" enumeration.\n#' @noRd\nallow_what_type <- function(what, allow_na = FALSE, allow_null = FALSE) {\n if (allow_na) {\n what <- c(what, \"`NA`\")\n }\n if (allow_null) {\n what <- c(what, \"`NULL`\")\n }\n if (length(what)) {\n what <- .standalone_oxford_comma(what, final = \"or\")\n }\n what\n}\n\n#' Return English-friendly type\n#' @param x Any R object.\n#' @param value Whether to describe the value of `x`. Special values\n#' like `NA` or `\"\"` are always described.\n#' @param length Whether to mention the length of vectors and lists.\n#' @return A string describing the type. Starts with an indefinite\n#' article, e.g. \"an integer vector\".\n#' @importFrom rlang is_missing is_vector\n#' @noRd\nobj_type_friendly <- function(x, value = TRUE, length = FALSE) {\n if (is_missing(x)) {\n return(\"absent\")\n }\n\n if (is.object(x)) {\n if (inherits(x, \"quosure\")) {\n type <- \"quosure\"\n } else {\n type <- class(x)[[1L]]\n }\n return(sprintf(\"a <%s> object\", type))\n }\n\n if (!is_vector(x)) {\n return(.rlang_as_friendly_type(typeof(x)))\n }\n\n n_dim <- length(dim(x))\n\n if (!n_dim) {\n if (!is.list(x) && length(x) == 1) {\n if (is.na(x)) {\n return(switch(typeof(x),\n logical = \"`NA`\",\n integer = \"an integer `NA`\",\n double =\n if (is.nan(x)) {\n \"`NaN`\"\n } else {\n \"a numeric `NA`\"\n },\n complex = \"a complex `NA`\",\n character = \"a character `NA`\",\n .rlang_stop_unexpected_typeof(x)\n ))\n }\n\n show_infinites <- function(x) {\n if (x > 0) {\n \"`Inf`\"\n } else {\n \"`-Inf`\"\n }\n }\n str_encode <- function(x, width = 30, ...) {\n if (nchar(x) > width) {\n x <- substr(x, 1, width - 3)\n x <- paste0(x, \"...\")\n }\n encodeString(x, ...)\n }\n\n if (value) {\n if (is.numeric(x) && is.infinite(x)) {\n return(show_infinites(x))\n }\n\n if (is.numeric(x) || is.complex(x)) {\n number <- as.character(round(x, 2))\n what <- if (is.complex(x)) {\n \"the complex number\"\n } else {\n \"the number\"\n }\n return(paste(what, number))\n }\n\n return(switch(typeof(x),\n logical = if (x) \"`TRUE`\" else \"`FALSE`\",\n character = {\n what <- if (nzchar(x)) {\n \"the string\"\n } else {\n \"the empty string\"\n }\n paste(what, str_encode(x, quote = \"\\\"\"))\n },\n raw = paste(\"the raw value\", as.character(x)),\n .rlang_stop_unexpected_typeof(x)\n ))\n }\n\n return(switch(typeof(x),\n logical = \"a logical value\",\n integer = \"an integer\",\n double = if (is.infinite(x)) show_infinites(x) else \"a number\",\n complex = \"a complex number\",\n character = if (nzchar(x)) \"a string\" else \"\\\"\\\"\",\n raw = \"a raw value\",\n .rlang_stop_unexpected_typeof(x)\n ))\n }\n\n if (length(x) == 0) {\n return(switch(typeof(x),\n logical = \"an empty logical vector\",\n integer = \"an empty integer vector\",\n double = \"an empty numeric vector\",\n complex = \"an empty complex vector\",\n character = \"an empty character vector\",\n raw = \"an empty raw vector\",\n list = \"an empty list\",\n .rlang_stop_unexpected_typeof(x)\n ))\n }\n }\n\n vec_type_friendly(x, length = length)\n}\n\n#' @importFrom rlang is_vector abort\nvec_type_friendly <- function(x, length = FALSE) {\n if (!is_vector(x)) {\n abort(\"`x` must be a vector.\")\n }\n type <- typeof(x)\n n_dim <- length(dim(x))\n\n add_length <- function(type) {\n if (length && !n_dim) {\n paste0(type, sprintf(\" of length %s\", length(x)))\n } else {\n type\n }\n }\n\n if (type == \"list\") {\n if (n_dim < 2) {\n return(add_length(\"a list\"))\n } else if (is.data.frame(x)) {\n return(\"a data frame\")\n } else if (n_dim == 2) {\n return(\"a list matrix\")\n } else {\n return(\"a list array\")\n }\n }\n\n type <- switch(type,\n logical = \"a logical %s\",\n integer = \"an integer %s\",\n numeric = ,\n double = \"a double %s\",\n complex = \"a complex %s\",\n character = \"a character %s\",\n raw = \"a raw %s\",\n type = paste0(\"a \", type, \" %s\")\n )\n\n if (n_dim < 2) {\n kind <- \"vector\"\n } else if (n_dim == 2) {\n kind <- \"matrix\"\n } else {\n kind <- \"array\"\n }\n out <- sprintf(type, kind)\n\n if (n_dim >= 2) {\n out\n } else {\n add_length(out)\n }\n}\n\n.rlang_as_friendly_type <- function(type) {\n switch(type,\n list = \"a list\",\n NULL = \"`NULL`\",\n environment = \"an environment\",\n externalptr = \"a pointer\",\n weakref = \"a weak reference\",\n S4 = \"an S4 object\",\n name = ,\n symbol = \"a symbol\",\n language = \"a call\",\n pairlist = \"a pairlist node\",\n expression = \"an expression vector\",\n char = \"an internal string\",\n promise = \"an internal promise\",\n ... = \"an internal dots object\",\n any = \"an internal `any` object\",\n bytecode = \"an internal bytecode object\",\n primitive = ,\n builtin = ,\n special = \"a primitive function\",\n closure = \"a function\",\n type\n )\n}\n\n#' @importFrom rlang abort caller_env\n.rlang_stop_unexpected_typeof <- function(x, call = caller_env()) {\n abort(sprintf(\"Unexpected type <%s>.\", typeof(x)), call = call)\n}\n\n#' Return OO type\n#' @param x Any R object.\n#' @return One of `\"bare\"` (for non-OO objects), `\"S3\"`, `\"S4\"`,\n#' `\"R6\"`, or `\"S7\"`.\n#' @noRd\nobj_type_oo <- function(x) {\n if (!is.object(x)) {\n return(\"bare\")\n }\n\n class <- inherits(x, c(\"R6\", \"S7_object\"), which = TRUE)\n\n if (class[[1]]) {\n \"R6\"\n } else if (class[[2]]) {\n \"S7\"\n } else if (isS4(x)) {\n \"S4\"\n } else {\n \"S3\"\n }\n}\n\n.standalone_oxford_comma <- function(x, sep = \", \", final = \"and\") {\n n <- length(x)\n\n if (n < 2L) return(x) # styler: off\n\n head <- x[seq_len(n - 1L)]\n last <- x[n]\n\n head <- paste(head, collapse = sep)\n\n # Write a or b. But a, b, or c.\n if (n > 2L) {\n paste0(head, sep, final, \" \", last)\n } else {\n paste0(head, \" \", final, \" \", last)\n }\n}\n\n# nocov end\n"], ["/ggalign/R/link.R", "#' Define the links to connect a pair of observations\n#'\n#' @description\n#' This function allows users to define links between a pair of observations,\n#' facilitating the visualization of connections between related data points.\n#'\n#' @param .draw A function used to draw the links. The function must return a\n#' [`grob()`][grid::grob] object. If the function does not return a valid\n#' `grob`, no drawing will occur. The input data for the function should\n#' include a data frame with the coordinates of the pair of observations to\n#' be linked.\n#' @inheritParams .link_draw\n#' @seealso\n#' - [`link_line()`]\n#' - [`.link_draw()`]\n#' @importFrom rlang is_empty inject\n#' @importFrom grid gTree gList\n#' @export\nlink_draw <- function(.draw, ...) {\n if (!is.function(draw <- allow_lambda(.draw))) {\n cli_abort(\"{.arg .draw} must be a function\")\n }\n new_draw <- function(data) {\n ans <- lapply(data, draw)\n ans <- ans[vapply(ans, is.grob, logical(1L), USE.NAMES = FALSE)]\n if (!is_empty(ans)) inject(gList(!!!ans))\n }\n .link_draw(new_draw, ...)\n}\n\n#' @inherit link_draw title\n#'\n#' @description\n#' A base version of [`link_draw()`], optimized for performance. This function\n#' serves as the foundation for building other `link_*` functions that manage\n#' the drawing of links between pairs of observations.\n#'\n#' @param .draw A function used to draw the links. The function must return a\n#' [`grob()`][grid::grob] object. If the function does not return a valid\n#' `grob`, no drawing will occur. The input data for the function should be\n#' a list, where each item is a data frame containing the coordinates of\n#' the pair of observations.\n#' @inheritParams pair_links\n#' @seealso [`link_draw()`]\n#' @export\n.link_draw <- function(.draw, ...) {\n if (override_call(call <- caller_call())) {\n call <- current_call()\n }\n if (!is.function(draw <- allow_lambda(.draw))) {\n cli_abort(\"{.arg .draw} must be a function\", call = call)\n }\n links <- pair_links(...)\n structure(list(draw = draw, links = links), class = \"ggalign_link_draw\")\n}\n\n#' @export\nprint.ggalign_link_draw <- function(x, ...) {\n header <- sprintf(\"<%s>\", vec_ptype_full(x))\n cat(header, sep = \"\\n\")\n obj_print_data(.subset2(x, \"links\"))\n invisible(x)\n}\n\n#' Link the paired observations with a line\n#'\n#' @inheritParams .link_draw\n#' @param .element A [`element_line()`][ggplot2::element_line] object.\n#' Vectorized fields will be recycled to match the total number of groups, or\n#' you can wrap the element with [`I()`] to recycle to match the drawing\n#' groups. The drawing groups typically correspond to the product of the\n#' number of observations from both sides, as each pair of observations will\n#' be linked with a single line.\n#' @importFrom ggplot2 element_line\n#' @export\nlink_line <- function(..., .element = NULL) {\n assert_s3_class(.element, \"element_line\", allow_null = TRUE)\n default <- calc_element(\"ggalign.line\", complete_theme(theme_get()))\n if (is.null(.element)) {\n .element <- default\n } else {\n .element <- ggplot2::merge_element(.element, default)\n }\n ans <- .link_draw(.draw = function(data) {\n data <- lapply(data, function(d) {\n # if the link is only in one side, we do nothing\n if (vec_unique_count(.subset2(d, \".hand\")) < 2L) {\n return(NULL)\n }\n both <- .subset2(vec_split(d, .subset2(d, \".hand\")), \"val\")\n data <- cross_join(.subset2(both, 1L), .subset2(both, 2L))\n data_frame0(\n x = vec_interleave(\n (data$x.x + data$xend.x) / 2L,\n (data$x.y + data$xend.y) / 2L\n ),\n y = vec_interleave(\n (data$y.x + data$yend.x) / 2L,\n (data$y.y + data$yend.y) / 2L\n )\n )\n })\n if (inherits(.element, \"AsIs\")) {\n .element <- element_rep_len(.element,\n length.out = sum(list_sizes(data)) / 2L\n )\n } else {\n .element <- element_rep_len(.element, length.out = length(data))\n .element <- element_vec_rep_each(.element,\n times = list_sizes(data) / 2L\n )\n }\n data <- vec_rbind(!!!data)\n if (vec_size(data)) {\n element_grob(\n .element,\n x = data$x, y = data$y,\n id.lengths = vec_rep(2L, vec_size(data) / 2L),\n default.units = \"native\"\n )\n }\n }, ...)\n add_class(ans, \"ggalign_link_line\")\n}\n\n#' Link the paired observations with a quadrilateral\n#'\n#' @inheritParams .link_draw\n#' @inheritParams mark_tetragon\n#' @export\nlink_tetragon <- function(..., .element = NULL) {\n assert_s3_class(.element, \"element_polygon\", allow_null = TRUE)\n default <- calc_element(\"ggalign.polygon\", complete_theme(theme_get()))\n if (is.null(.element)) {\n .element <- default\n } else {\n .element <- ggplot2::merge_element(.element, default)\n }\n .link_draw(.draw = function(data) {\n data <- lapply(data, function(d) {\n # if the link is only in one side, we do nothing\n if (vec_unique_count(.subset2(d, \".hand\")) < 2L) {\n return(NULL)\n }\n both <- .subset2(vec_split(d, .subset2(d, \".hand\")), \"val\")\n both <- lapply(both, function(link) {\n # find the consecutive groups\n index <- .subset2(link, \"link_index\")\n oindex <- order(index)\n group <- cumsum(c(0L, diff(index[oindex])) != 1L)\n\n # restore the order\n group <- group[order(oindex)]\n\n # split link into groups\n .subset2(vec_split(link, group), \"val\")\n })\n both <- vec_expand_grid(\n hand1 = .subset2(both, 1L),\n hand2 = .subset2(both, 2L)\n )\n ans <- .mapply(function(hand1, hand2) {\n data_frame0(\n x = vec_c(\n min(hand1$x), max(hand1$xend),\n max(hand2$xend), min(hand2$x)\n ),\n y = vec_c(\n min(hand1$y), max(hand1$yend),\n max(hand2$yend), min(hand2$y)\n )\n )\n }, both, NULL)\n vec_rbind(!!!ans)\n })\n if (inherits(.element, \"AsIs\")) {\n .element <- element_rep_len(.element,\n length.out = sum(list_sizes(data)) / 4L\n )\n } else {\n .element <- element_rep_len(.element, length.out = length(data))\n .element <- element_vec_rep_each(.element,\n times = list_sizes(data) / 4L\n )\n }\n data <- vec_rbind(!!!data)\n if (vec_size(data)) {\n element_grob(\n .element,\n x = data$x, y = data$y,\n id.lengths = vec_rep(4L, vec_size(data) / 4L),\n default.units = \"native\"\n )\n }\n }, ...)\n}\n\n# preDraw:\n# - makeContext\n# - pushvpgp\n# - preDrawDetails: by default, do noting\n# makeContent:\n# drawDetails:\n# postDraw:\n# - postDrawDetails: by default, do noting\n# - popgrobvp\n#' @importFrom grid makeContent convertHeight convertWidth gList setChildren\n#' @export\nmakeContent.ggalignLinkTree <- function(x) {\n # Grab viewport information\n width <- convertWidth(unit(1, \"npc\"), \"mm\", valueOnly = TRUE)\n height <- convertHeight(unit(1, \"npc\"), \"mm\", valueOnly = TRUE)\n\n # Grab grob metadata\n full_data1 <- .subset2(x, \"full_data1\")\n full_data2 <- .subset2(x, \"full_data2\")\n direction <- .subset2(x, \"direction\")\n link_index_list <- .subset2(x, \"link_index\")\n data_index_list <- .subset2(x, \"data_index\")\n obs_size <- .subset2(x, \"obs_size\")\n\n # prepare output for current for loop\n coords <- vector(\"list\", 2L)\n names(coords) <- c(\"hand1\", \"hand2\")\n for (link in names(coords)) {\n link_index <- lapply(link_index_list, .subset2, link)\n data_index <- lapply(data_index_list, .subset2, link)\n # early exit and step into next cycle if no link\n if (all(vapply(link_index, is.null, logical(1L), USE.NAMES = FALSE))) {\n coords[link] <- list(link_index)\n next\n }\n full_breaks <- switch(link,\n hand1 = full_data1,\n hand2 = full_data2\n )\n\n spacing <- .subset2(x, switch(link,\n hand1 = \"spacing1\",\n hand2 = \"spacing2\"\n ))\n\n # each value represent an `observation`, for panel space, we use `NA`\n # obs arranged from left to top, and from bottom to top\n points <- unlist(vec_interleave(full_breaks, list(NA)), FALSE, FALSE)\n # remove the last panel space, shouldn't exist\n points <- points[-length(points)]\n sizes <- numeric(length(points))\n n_spacing <- length(full_breaks) - 1L\n\n # then, we define the link grobs\n if (is_horizontal(direction)) { # the link should be in left or right\n spacing <- convertHeight(spacing, \"mm\", valueOnly = TRUE)\n spacing <- scales::rescale(spacing, c(0, 1), from = c(0, height))\n sizes[is.na(points)] <- spacing\n obs_height <- (1 - spacing * n_spacing) / sum(!is.na(points))\n sizes[!is.na(points)] <- obs_height # nobs\n yend <- cumsum(sizes)\n link_x <- switch(link,\n hand1 = 0,\n hand2 = 1\n )\n # by default, the height for each observation is `1`,\n # if we define obs size, we just re-scale it\n removed <- (1 - obs_size) * obs_height\n link_coord <- data_frame0(\n x = link_x, xend = link_x,\n y = yend - sizes + removed / 2L,\n yend = yend - removed / 2L\n )\n link_coord <- vec_slice(link_coord, !is.na(points))\n } else { # the link should be in top or bottom\n spacing <- convertWidth(spacing, \"mm\", valueOnly = TRUE)\n spacing <- scales::rescale(spacing, c(0, 1), from = c(0, width))\n sizes[is.na(points)] <- spacing\n obs_width <- (1 - spacing * n_spacing) / sum(!is.na(points))\n sizes[!is.na(points)] <- obs_width\n xend <- cumsum(sizes)\n link_y <- switch(link,\n hand1 = 1,\n hand2 = 0\n )\n # by default, the width for each observation is `1`,\n # if we define obs size, we just re-scale it\n removed <- (1 - obs_size) * obs_width\n link_coord <- data_frame0(\n x = xend - sizes + removed / 2L,\n xend = xend - removed / 2L,\n y = link_y, yend = link_y\n )\n link_coord <- vec_slice(link_coord, !is.na(points))\n }\n hand <- switch(link,\n hand1 = switch_direction(direction, \"left\", \"top\"),\n hand2 = switch_direction(direction, \"right\", \"bottom\")\n )\n nms <- names(link_index)\n link_panels <- vec_rep_each(names(full_breaks), list_sizes(full_breaks))\n coords[[link]] <- lapply(seq_along(link_index), function(i) {\n l_index <- .subset2(link_index, i)\n if (is.null(l_index)) return(NULL) # styler: off\n d_index <- .subset2(data_index, i)\n link <- vec_slice(link_coord, l_index)\n link$link_id <- nms[i]\n link$link_panel <- reorder(\n vec_slice(link_panels, l_index), l_index,\n order = FALSE\n )\n link$link_index <- l_index\n link$.hand <- hand\n link$.index <- d_index\n link\n })\n }\n\n # hand1 - hand2\n data <- .mapply(vec_rbind, coords, NULL)\n draw <- .subset2(x, \"draw\")\n if (is.grob(grob <- draw(data))) { # wrap single grob to a gList\n grob <- gList(grob)\n }\n if (is.gList(grob)) {\n setChildren(x, grob)\n } else {\n x\n }\n}\n"], ["/ggalign/R/ggplot-geom-draw.R", "#' Layer with Grid or Function\n#'\n#' Draw a ggplot2 layer using a grob or a function.\n#'\n#' @param draw Either a [grob][grid::grob] object or a function (can be\n#' purrr-style) that accepts at least one argument (a data frame of\n#' transformed coordinates) and returns a [grob][grid::grob].\n#'\n#' @param type A single string of `r oxford_or(c(\"group\", \"panel\"))`, `\"group\"`\n#' draws geoms with `draw_group`, which displays multiple observations as one\n#' geometric object, and `\"panel\"` draws geoms with `draw_panel`, displaying\n#' individual graphical objects for each observation (row). Default:\n#' `\"group\"`.\n#'\n#' @inheritParams ggplot2::layer\n#' @inheritParams ggplot2::geom_point\n#' @details If you want to combine the functionality of multiple geoms, it can\n#' typically be achieved by preparing the data for each geom inside the\n#' `draw_*()` call and sending it off to the different geoms, collecting the\n#' output in a [`grid::gList`] (a list of grobs) for `draw_group()` or a\n#' [`grid::gTree`] (a grob containing multiple child grobs) for\n#' `draw_panel()`.\n#' @seealso \n#' @examples\n#' text <- grid::textGrob(\n#' \"ggdraw\",\n#' x = c(0, 0, 0.5, 1, 1),\n#' y = c(0, 1, 0.5, 0, 1),\n#' hjust = c(0, 0, 0.5, 1, 1),\n#' vjust = c(0, 1, 0.5, 0, 1)\n#' )\n#' ggplot(data.frame(x = 1, y = 2)) +\n#' geom_draw(text)\n#' @importFrom rlang list2 arg_match0\n#' @importFrom ggplot2 ggproto aes\n#' @export\ngeom_draw <- function(draw, mapping = NULL, data = NULL,\n type = \"group\", stat = \"identity\",\n position = \"identity\", ...,\n na.rm = FALSE, show.legend = FALSE, inherit.aes = TRUE) {\n type <- arg_match0(type, c(\"group\", \"panel\"))\n if (!is.grob(draw) && !is.gList(draw)) draw <- rlang::as_function(draw)\n dots <- list2(...)\n ggplot2::layer(\n data = data,\n mapping = mapping,\n stat = stat,\n geom = switch(type,\n panel = ggproto(\n \"GeomDraw\",\n ggplot2::Geom,\n default_aes = GeomGshape$default_aes,\n setup_data = draw_setup_data,\n draw_panel = draw_geom_draw,\n draw_key = ggplot2::draw_key_blank\n ),\n group = ggproto(\n \"GeomDraw\",\n ggplot2::Geom,\n default_aes = GeomGshape$default_aes,\n setup_data = draw_setup_data,\n draw_group = draw_geom_draw,\n draw_key = ggplot2::draw_key_blank\n )\n ),\n position = position,\n show.legend = show.legend,\n inherit.aes = inherit.aes,\n params = c(\n list(na.rm = na.rm, draw = draw, .__draw_dots__ = dots), dots\n )\n )\n}\n\n# GeomTile will respect width and height\ndraw_setup_data <- function(self, data, params) {\n data$x <- data$x %||% 0.5\n data$y <- data$y %||% 0.5\n ggplot2::GeomTile$setup_data(data, params)\n}\n\ndraw_geom_draw <- function(data, panel_params, coord, draw, .__draw_dots__) {\n if (is.function(draw)) {\n data <- coord$transform(data, panel_params)\n # restore colour\n if (!is.null(data$colour) && is.null(data$color)) {\n data$color <- data$colour\n }\n if (!is.null(data$color) && is.null(data$colour)) {\n data$colour <- data$color\n }\n\n # restore width and height\n if (!is.null(data$xmin) && !is.null(data$xmax)) {\n data$width <- data$xmax - data$xmin\n }\n if (!is.null(data$ymin) && !is.null(data$ymax)) {\n data$height <- data$ymax - data$ymin\n }\n }\n make_draw_grob(draw, data, .__draw_dots__)\n}\n\n#' @return A [grob][grid::grob] object.\n#' @importFrom rlang inject\n#' @importFrom methods formalArgs\n#' @importFrom ggplot2 zeroGrob\n#' @keywords internal\n#' @noRd\nmake_draw_grob <- function(draw, data, dots) {\n if (is.function(draw)) {\n args <- formalArgs(draw)\n if (any(args == \"...\")) {\n draw <- inject(draw(!!!data, !!!dots))\n } else {\n draw <- inject(draw(\n !!!.subset(data, intersect(names(data), args)),\n !!!.subset(dots, intersect(\n setdiff(names(dots), names(data)), args\n ))\n ))\n }\n }\n ensure_grob(draw, zeroGrob())\n}\n"], ["/ggalign/R/mark.R", "#' Define the links to connect the marked observations\n#'\n#' @description\n#' This function allows users to define links between marked observations and\n#' plot panel (e.g., for creating visual connections for related data), which\n#' could help explain the observations.\n#'\n#' @param .draw A function used to draw the links. The function must return a\n#' [`grob()`][grid::grob] object. If the function does not return a valid\n#' `grob`, nothing will be drawn. The input data for the function must contain\n#' two arguments: a data frame for the panel side coordinates and a data frame\n#' for the marked observation coordinates.\n#' @inheritParams .mark_draw\n#' @seealso\n#' - [`mark_line()`]\n#' - [`mark_tetragon()`]\n#' - [`mark_triangle()`]\n#' - [`.mark_draw()`]\n#' @importFrom rlang is_empty inject\n#' @importFrom grid gTree gList\n#' @export\nmark_draw <- function(.draw, ...) {\n if (!is.function(draw <- allow_lambda(.draw))) {\n cli_abort(\"{.arg .draw} must be a function\")\n }\n new_draw <- function(data) {\n ans <- lapply(data, function(dd) {\n draw(.subset2(dd, \"panel\"), .subset2(dd, \"link\"))\n })\n ans <- ans[vapply(ans, is.grob, logical(1L), USE.NAMES = FALSE)]\n if (!is_empty(ans)) {\n gTree(children = inject(gList(!!!ans)))\n }\n }\n .mark_draw(new_draw, ...)\n}\n\n#' @inherit mark_draw title\n#'\n#' @description\n#' A base version of [`mark_draw`], designed for performance optimization. This\n#' function is used to build other `mark_*` functions that manage the drawing of\n#' links between marked observations.\n#'\n#' @param .draw A function used to draw the links. The function must return a\n#' [`grob()`][grid::grob] object. If the function does not return a valid\n#' `grob`, nothing will be drawn. The input data for the function contains a\n#' list, where each item is a list of two data frames: one for the panel side\n#' coordinates (`\"panel\"`) and one for the marked observations coordinates\n#' (`\"link\"`).\n#'\n#' @inheritParams pair_links\n#' @seealso [`mark_draw()`]\n#' @export\n.mark_draw <- function(.draw, ...) {\n if (override_call(call <- caller_call())) {\n call <- current_call()\n }\n if (!is.function(draw <- allow_lambda(.draw))) {\n cli_abort(\"{.arg .draw} must be a function\", call = call)\n }\n links <- pair_links(...)\n structure(list(draw = draw, links = links), class = \"ggalign_mark_draw\")\n}\n\n#' @export\nprint.ggalign_mark_draw <- function(x, ...) {\n header <- sprintf(\"<%s>\", vec_ptype_full(x))\n cat(header, sep = \"\\n\")\n obj_print_data(.subset2(x, \"links\"))\n invisible(x)\n}\n\n#' Link the observations and the panel with a line\n#'\n#' @inheritParams .mark_draw\n#' @param .element A [`element_line()`][ggplot2::element_line] object.\n#' Vectorized fields will be recycled to match the total number of groups, or\n#' you can wrap the element with [`I()`] to recycle to match the drawing\n#' groups. The drawing groups typically correspond to the number of\n#' observations, as each observation will be linked with the plot panel.\n#' @importFrom ggplot2 element_line\n#' @export\nmark_line <- function(..., .element = NULL) {\n assert_s3_class(.element, \"element_line\", allow_null = TRUE)\n default <- calc_element(\"ggalign.line\", complete_theme(theme_get()))\n if (is.null(.element)) {\n .element <- default\n } else {\n .element <- ggplot2::merge_element(.element, default)\n }\n .mark_draw(.draw = function(data) {\n data <- lapply(data, function(d) {\n panel <- .subset2(d, \"panel\")\n link <- .subset2(d, \"link\")\n data_frame0(\n # there is only one row for panel, it's safe to use\n # vec_interleave directly\n x = vec_interleave(\n (panel$x + panel$xend) / 2L,\n (link$x + link$xend) / 2L\n ),\n y = vec_interleave(\n (panel$y + panel$yend) / 2L,\n (link$y + link$yend) / 2L\n )\n )\n })\n if (inherits(.element, \"AsIs\")) {\n .element <- element_rep_len(.element,\n length.out = sum(list_sizes(data)) / 2L\n )\n } else {\n .element <- element_rep_len(.element, length.out = length(data))\n .element <- element_vec_rep_each(.element,\n times = list_sizes(data) / 2L\n )\n }\n data <- vec_rbind(!!!data)\n element_grob(\n .element,\n x = data$x, y = data$y,\n id.lengths = vec_rep(2L, vec_size(data) / 2L),\n default.units = \"native\"\n )\n }, ...)\n}\n\n#' Link the observations and the panel with a quadrilateral\n#'\n#' @inheritParams .mark_draw\n#' @param .element A [`element_polygon()`] object. Vectorized fields will be\n#' recycled to match the total number of groups, or you can wrap the element\n#' with [`I()`] to recycle to match the drawing groups. The drawing groups\n#' are usually the same as the defined groups, but they will differ when the\n#' defined group of observations is separated and cannot be linked with a\n#' single quadrilateral. In such cases, the number of drawing groups will be\n#' larger than the number of defined groups.\n#' @export\nmark_tetragon <- function(..., .element = NULL) {\n assert_s3_class(.element, \"element_polygon\", allow_null = TRUE)\n default <- calc_element(\"ggalign.polygon\", complete_theme(theme_get()))\n if (is.null(.element)) {\n .element <- default\n } else {\n .element <- ggplot2::merge_element(.element, default)\n }\n .mark_draw(.draw = function(data) {\n data <- lapply(data, function(d) {\n panel <- .subset2(d, \"panel\")\n link <- .subset2(d, \"link\")\n\n # find the consecutive groups\n index <- .subset2(link, \"link_index\")\n oindex <- order(index)\n group <- cumsum(c(0L, diff(index[oindex])) != 1L)\n\n # restore the order\n group <- group[order(oindex)]\n\n # split link into groups\n link <- vec_split(link, group)\n\n # for each group, we draw a quadrilateral\n vec_rbind(!!!lapply(.subset2(link, \"val\"), function(dd) {\n data_frame0(\n x = vec_c(panel$x, panel$xend, max(dd$xend), min(dd$x)),\n y = vec_c(panel$y, panel$yend, max(dd$yend), min(dd$y))\n )\n }))\n })\n if (inherits(.element, \"AsIs\")) {\n .element <- element_rep_len(.element,\n length.out = sum(list_sizes(data)) / 4L\n )\n } else {\n .element <- element_rep_len(.element, length.out = length(data))\n .element <- element_vec_rep_each(.element,\n times = list_sizes(data) / 4L\n )\n }\n data <- vec_rbind(!!!data)\n if (vec_size(data)) {\n element_grob(\n .element,\n x = data$x, y = data$y,\n id.lengths = vec_rep(4L, nrow(data) / 4L),\n default.units = \"native\"\n )\n }\n }, ...)\n}\n\n#' Link the observations and the panel with a triangle\n#'\n#' @inheritParams .mark_draw\n#' @param orientation A single string, either `\"plot\"` or `\"observation\"`,\n#' indicating the base of the triangle.\n#' @param .element An [`element_polygon()`] object. Vectorized fields will be\n#' recycled to match the total number of groups, or you can wrap the element\n#' with [`I()`] to recycle to match the drawing groups.\n#' - When `orientation` is `\"plot\"`, the drawing groups typically correspond\n#' to the number of observations.\n#' - When `orientation` is `\"observation\"`, the drawing groups usually match\n#' the defined groups, but will differ if the defined group of observations\n#' is separated and cannot be linked with a single triangle. In this case,\n#' the number of drawing groups will be larger than the number of defined\n#' groups.\n#' @importFrom rlang arg_match0\n#' @export\nmark_triangle <- function(..., orientation = \"plot\", .element = NULL) {\n assert_s3_class(.element, \"element_polygon\", allow_null = TRUE)\n default <- calc_element(\"ggalign.polygon\", complete_theme(theme_get()))\n if (is.null(.element)) {\n .element <- default\n } else {\n .element <- ggplot2::merge_element(.element, default)\n }\n orientation <- arg_match0(orientation, c(\"plot\", \"observation\"))\n .mark_draw(.draw = function(data) {\n data <- lapply(data, function(d) {\n panel <- .subset2(d, \"panel\")\n link <- .subset2(d, \"link\")\n if (identical(orientation, \"plot\")) {\n # for each link, we draw a triangle\n triangle_list <- lapply(vec_seq_along(link), function(i) {\n dd <- vec_slice(link, i)\n data_frame0(\n x = vec_c(panel$x, panel$xend, (dd$x + dd$xend) / 2L),\n y = vec_c(panel$y, panel$yend, (dd$y + dd$yend) / 2L),\n )\n })\n } else {\n # find the consecutive groups\n index <- .subset2(link, \"link_index\")\n oindex <- order(index)\n group <- cumsum(c(0L, diff(index[oindex])) != 1L)\n\n # restore the order\n group <- group[order(oindex)]\n\n # split link into groups\n link <- vec_split(link, group)\n\n # for each group, we draw a triangle\n triangle_list <- lapply(.subset2(link, \"val\"), function(dd) {\n data_frame0(\n x = vec_c(\n (panel$x + panel$xend) / 2L,\n max(dd$xend), min(dd$x)\n ),\n y = vec_c(\n (panel$y + panel$yend) / 2L,\n max(dd$yend), min(dd$y)\n )\n )\n })\n }\n vec_rbind(!!!triangle_list)\n })\n if (inherits(.element, \"AsIs\")) {\n .element <- element_rep_len(.element,\n length.out = sum(list_sizes(data)) / 3L\n )\n } else {\n .element <- element_rep_len(.element, length.out = length(data))\n .element <- element_vec_rep_each(.element,\n times = list_sizes(data) / 3L\n )\n }\n data <- vec_rbind(!!!data)\n if (vec_size(data)) {\n element_grob(\n .element,\n x = data$x, y = data$y,\n id.lengths = vec_rep(3L, nrow(data) / 3L),\n default.units = \"native\"\n )\n }\n }, ...)\n}\n\n#####################################################\n#' @export\n`[.ggalignMarkGtable` <- function(x, i, j) {\n # subset will violate the `ggalignMarkGtable` `shape`\n # we always use the next method\n x <- remove_class(x, \"ggalignMarkGtable\")\n x$ggalign_link_data <- NULL\n NextMethod()\n}\n\n#' @importFrom ggplot2 ggproto\n#' @export\nalignpatch.ggalign_mark_plot <- function(x) {\n ggproto(NULL, PatchAlignMark, plot = x)\n}\n\n#' @importFrom ggplot2 ggproto ggproto_parent\n#' @include alignpatch-ggplot2.R\nPatchAlignMark <- ggproto(\n \"PatchAlignMark\", PatchGgplot,\n patch_gtable = function(self, theme, guides, plot = self$plot) {\n ans <- ggproto_parent(PatchGgplot, self)$patch_gtable(plot = plot)\n # re-define the draw method, we assign new class\n ans <- add_class(ans, \"ggalignMarkGtable\")\n ans$ggalign_link_data <- plot$ggalign_link_data\n ans\n },\n add_plot = function(self, gt, plot, t, l, b, r, name, z = 2L) {\n gtable_add_grob(\n gt,\n grobs = plot,\n # t = 8, l = 6, b = 14, r = 12\n # t = t + 7L, l = l + 5L, b = b - 6L, r = r - 5L,\n t = t + TOP_BORDER, l = l + LEFT_BORDER,\n name = name, z = z\n )\n },\n add_background = function(self, gt, bg, t, l, b, r, name, z = 1L) {\n gtable_add_grob(\n gt,\n grobs = bg,\n t = t + TOP_BORDER, l = l + LEFT_BORDER,\n name = name, z = z\n )\n },\n get_sizes = function(self, free = NULL, gt = self$gt) {\n ggproto_parent(PatchGgplot, self)$get_sizes(.tlbr, gt = gt)\n },\n align_border = function(self, t = NULL, l = NULL, b = NULL, r = NULL,\n gt = self$gt) {\n gt # free from alignment\n }\n)\n\n# preDraw:\n# - makeContext\n# - pushvpgp\n# - preDrawDetails: by default, do noting\n# makeContent:\n# drawDetails:\n# postDraw:\n# - postDrawDetails: by default, do noting\n# - popgrobvp\n#' @importFrom grid makeContent unit convertHeight convertWidth viewport\n#' @importFrom stats reorder\n#' @export\nmakeContent.ggalignMarkGtable <- function(x) {\n # Grab viewport information\n width <- convertWidth(unit(1, \"npc\"), \"mm\", valueOnly = TRUE)\n height <- convertHeight(unit(1, \"npc\"), \"mm\", valueOnly = TRUE)\n\n # Grab grob metadata\n plot_widths <- compute_null_width(.subset2(x, \"widths\"),\n valueOnly = TRUE\n )\n plot_widths <- scales::rescale(plot_widths, c(0, 1), from = c(0, width))\n plot_heights <- compute_null_height(.subset2(x, \"heights\"),\n valueOnly = TRUE\n )\n plot_heights <- scales::rescale(plot_heights, c(0, 1), from = c(0, height))\n\n panel_loc <- find_panel(x)\n data <- .subset2(x, \"ggalign_link_data\")\n full_data1 <- .subset2(data, \"full_data1\")\n full_data2 <- .subset2(data, \"full_data2\")\n direction <- .subset2(data, \"direction\")\n link_index_list <- .subset2(data, \"link_index\")\n data_index_list <- .subset2(data, \"data_index\")\n obs_size <- .subset2(data, \"obs_size\")\n\n # prepare output for current for loop\n coords <- vector(\"list\", 2L)\n names(coords) <- c(\"hand1\", \"hand2\")\n for (link in names(coords)) {\n link_index <- lapply(link_index_list, .subset2, link)\n data_index <- lapply(data_index_list, .subset2, link)\n # early exit and step into next cycle if no link\n if (all(vapply(link_index, is.null, logical(1L), USE.NAMES = FALSE))) {\n coords[link] <- list(link_index)\n next\n }\n full_breaks <- switch(link,\n hand1 = full_data1,\n hand2 = full_data2\n )\n\n spacing <- .subset2(data, switch(link,\n hand1 = \"spacing1\",\n hand2 = \"spacing2\"\n ))\n\n # each value represent an `observation`, for panel space, we use `NA`\n # obs arranged from left to top, and from bottom to top\n points <- unlist(vec_interleave(full_breaks, list(NA)), FALSE, FALSE)\n # remove the last panel space, shouldn't exist\n points <- points[-length(points)]\n sizes <- numeric(length(points))\n n_spacing <- length(full_breaks) - 1L\n\n # then, we define the link grobs\n if (is_horizontal(direction)) { # the link should be in left or right\n spacing <- convertHeight(spacing, \"mm\", valueOnly = TRUE)\n spacing <- scales::rescale(spacing, c(0, 1), from = c(0, height))\n sizes[is.na(points)] <- spacing\n obs_height <- (1 - spacing * n_spacing) / sum(!is.na(points))\n sizes[!is.na(points)] <- obs_height # nobs\n yend <- cumsum(sizes)\n link_x <- switch(link,\n hand1 = 0,\n hand2 = 1\n )\n # by default, the height for each observation is `1`,\n # if we define obs size, we just re-scale it\n removed <- (1 - obs_size) * obs_height\n link_coord <- data_frame0(\n x = link_x, xend = link_x,\n y = yend - sizes + removed / 2L,\n yend = yend - removed / 2L\n )\n link_coord <- vec_slice(link_coord, !is.na(points))\n\n # from bottom to the top, following the ordering of the `breaks`\n panel_index <- seq(\n from = .subset2(panel_loc, \"b\"),\n to = .subset2(panel_loc, \"t\"),\n length.out = length(link_index)\n )\n l_border <- plot_widths[seq_len(.subset2(panel_loc, \"l\") - 1L)]\n r_border <- plot_widths[-seq_len(.subset2(panel_loc, \"r\"))]\n\n # for a gtable, heights are from top to the bottom,\n # we reverse the heights\n # we have reversed the `plot_cum_heights`, so the ordering index\n # should also be reversed\n panel_index <- nrow(x) - panel_index + 1L\n panel_yend <- cumsum(rev(plot_heights))\n panel_x <- switch(link,\n hand1 = sum(l_border),\n hand2 = 1 - sum(r_border)\n )\n panel_coord <- data_frame0(\n x = panel_x,\n xend = panel_x,\n y = (panel_yend - rev(plot_heights))[panel_index],\n yend = panel_yend[panel_index]\n )\n } else { # the link should be in top or bottom\n spacing <- convertWidth(spacing, \"mm\", valueOnly = TRUE)\n spacing <- scales::rescale(spacing, c(0, 1), from = c(0, width))\n sizes[is.na(points)] <- spacing\n obs_width <- (1 - spacing * n_spacing) / sum(!is.na(points))\n sizes[!is.na(points)] <- obs_width\n xend <- cumsum(sizes)\n link_y <- switch(link,\n hand1 = 1,\n hand2 = 0\n )\n # by default, the width for each observation is `1`,\n # if we define obs size, we just re-scale it\n removed <- (1 - obs_size) * obs_width\n link_coord <- data_frame0(\n x = xend - sizes + removed / 2L,\n xend = xend - removed / 2L,\n y = link_y, yend = link_y\n )\n link_coord <- vec_slice(link_coord, !is.na(points))\n\n panel_index <- seq(\n from = .subset2(panel_loc, \"l\"),\n to = .subset2(panel_loc, \"r\"),\n length.out = length(link_index)\n )\n t_border <- plot_heights[seq_len(.subset2(panel_loc, \"t\") - 1L)]\n b_border <- plot_heights[-seq_len(.subset2(panel_loc, \"b\"))]\n panel_xend <- cumsum(plot_widths)\n panel_y <- switch(link,\n hand1 = 1 - sum(t_border),\n hand2 = sum(b_border)\n )\n panel_coord <- data_frame0(\n x = (panel_xend - plot_widths)[panel_index],\n xend = panel_xend[panel_index],\n y = panel_y, yend = panel_y\n )\n }\n hand <- switch(link,\n hand1 = switch_direction(direction, \"left\", \"top\"),\n hand2 = switch_direction(direction, \"right\", \"bottom\")\n )\n nms <- names(link_index)\n link_panels <- vec_rep_each(names(full_breaks), list_sizes(full_breaks))\n coords[[link]] <- lapply(seq_along(link_index), function(i) {\n l_index <- .subset2(link_index, i)\n if (is.null(l_index)) return(NULL) # styler: off\n d_index <- .subset2(data_index, i)\n link <- vec_slice(link_coord, l_index)\n link$link_id <- nms[i]\n link$link_panel <- reorder(\n vec_slice(link_panels, l_index), l_index,\n order = FALSE\n )\n link$link_index <- l_index\n link$.hand <- hand\n link$.index <- d_index\n panel <- vec_slice(panel_coord, i)\n list(panel = panel, link = link)\n })\n }\n coords <- vec_interleave(\n .subset2(coords, \"hand1\"),\n .subset2(coords, \"hand2\")\n )\n coords <- list_drop_empty(coords)\n draw <- .subset2(data, \"draw\")\n if (is.gList(grob <- draw(coords))) {\n grob <- gTree(children = grob)\n }\n\n if (is.grob(grob)) {\n layout <- .subset2(x, \"layout\")\n panels <- layout[\n grepl(\"^panel\", .subset2(layout, \"name\")), ,\n drop = FALSE\n ]\n x <- gtable_add_grob(\n x,\n grobs = grob,\n t = 1L, l = 1L, b = -1L, r = -1L,\n # always draw with panel area\n z = min(panels$z)\n )\n }\n NextMethod()\n}\n"], ["/ggalign/R/ggplot-geom-gshape.R", "#' Layer with a customized shape graphic using grid functions.\n#'\n#' @description\n#' `r lifecycle::badge('questioning')`\n#'\n#' `geom_gshape` depends on the new aesthetics `gshape` (shape with grid\n#' functions), which should always be provided with [`scale_gshape_manual()`],\n#' in which, we can provide a list of grobs or functions that define how each\n#' value should be drawn. Any ggplot2 aesthetics can be used as the arguments.\n#'\n#' @inheritParams ggplot2::layer\n#' @inheritParams ggplot2::geom_point\n#' @section Life cycle:\n#' We're unsure whether this function is truly necessary, which is why it is\n#' marked as questioning. So far, we've found that [`geom_subrect()`] and\n#' [`geom_subtile()`] handle most use cases effectively.\n#'\n#' @aesthetics GeomGshape\n#' @examples\n#' library(grid)\n#' ggplot(data.frame(value = letters[seq_len(5)], y = seq_len(5))) +\n#' geom_gshape(aes(x = 1, y = y, gshape = value, fill = value)) +\n#' scale_gshape_manual(values = list(\n#' a = function(x, y, width, height, fill) {\n#' rectGrob(x, y,\n#' width = width, height = height,\n#' gp = gpar(fill = fill),\n#' default.units = \"native\"\n#' )\n#' },\n#' b = function(x, y, width, height, fill) {\n#' rectGrob(x, y,\n#' width = width, height = height,\n#' gp = gpar(fill = fill),\n#' default.units = \"native\"\n#' )\n#' },\n#' c = function(x, y, width, height, fill) {\n#' rectGrob(x, y,\n#' width = width, height = height,\n#' gp = gpar(fill = fill),\n#' default.units = \"native\"\n#' )\n#' },\n#' d = function(x, y, width, height, shape) {\n#' gList(\n#' pointsGrob(x, y, pch = shape),\n#' # To ensure the rectangle color is shown in the legends, you\n#' # must explicitly provide a color argument and include it in\n#' # the `gpar()` of the graphical object\n#' rectGrob(x, y, width, height,\n#' gp = gpar(col = \"black\", fill = NA)\n#' )\n#' )\n#' },\n#' e = function(xmin, xmax, ymin, ymax) {\n#' segmentsGrob(\n#' xmin, ymin,\n#' xmax, ymax,\n#' gp = gpar(lwd = 2)\n#' )\n#' }\n#' )) +\n#' scale_fill_brewer(palette = \"Dark2\") +\n#' theme_void()\n#'\n#' @importFrom rlang list2\n#' @export\ngeom_gshape <- function(mapping = NULL, data = NULL, stat = \"identity\",\n position = \"identity\", ..., na.rm = FALSE,\n show.legend = NA, inherit.aes = TRUE) {\n dots <- list2(...)\n ggplot2::layer(\n data = data,\n mapping = mapping,\n stat = stat,\n geom = GeomGshape,\n position = position,\n show.legend = show.legend,\n inherit.aes = inherit.aes,\n params = c(list(na.rm = na.rm), dots, list(.__gshape_dots__ = dots))\n )\n}\n\n#' @inherit ggplot2::draw_key_point\n#' @description\n#' Each geom has an associated function that draws the key when the geom needs\n#' to be displayed in a legend. These functions are called `draw_key_*()`, where\n#' `*` stands for the name of the respective key glyph. The key glyphs can be\n#' customized for individual geoms by providing a geom with the `key_glyph`\n#' argument. The `draw_key_gshape` function provides this interface for custom\n#' key glyphs used with [`geom_gshape()`].\n#'\n#' @importFrom rlang inject\n#' @importFrom methods formalArgs\n#' @importFrom grid gTree\n#' @export\ndraw_key_gshape <- function(data, params, size) {\n gshape <- .subset2(data$gshape, 1L)\n data$gshape <- NULL\n if (is.function(gshape)) {\n for (d in formalArgs(gshape)) {\n if (is.null(.subset2(data, d))) {\n data[[d]] <- switch(d,\n x = ,\n y = 0.5,\n xmin = ,\n ymin = 0,\n xmax = ,\n ymax = 1,\n width = ,\n height = 1,\n color = data$colour %||% GeomGshape$default_aes[[\"colour\"]],\n fill = data$colour %||% GeomGshape$default_aes[[\"fill\"]],\n GeomGshape$default_aes[[d]]\n )\n }\n }\n }\n make_draw_grob(gshape, data, .subset2(params, \".__gshape_dots__\"))\n}\n\n#' @importFrom ggplot2 ggproto zeroGrob\n#' @importFrom rlang inject\n#' @importFrom grid gList\nGeomGshape <- ggproto(\n \"GeomGshape\",\n ggplot2::Geom,\n required_aes = c(\"x\", \"y\", \"gshape\"),\n default_aes = aes(\n shape = 19,\n colour = \"black\",\n size = 1.5,\n fill = NA,\n alpha = NA,\n stroke = 0.5,\n linewidth = 0.5,\n linetype = 1\n ),\n setup_data = ggplot2::GeomTile$setup_data,\n draw_panel = function(data, panel_params, coord, .__gshape_dots__) {\n coords <- coord$transform(data, panel_params)\n\n if (!is.null(coords$colour) && is.null(coords$color)) {\n coords$color <- coords$colour\n }\n if (!is.null(coords$color) && is.null(coords$colour)) {\n coords$colour <- coords$color\n }\n\n # restore width and height\n if (!is.null(coords$xmin) && !is.null(coords$xmax)) {\n coords$width <- coords$xmax - coords$xmin\n }\n if (!is.null(coords$ymin) && !is.null(coords$ymax)) {\n coords$height <- coords$ymax - coords$ymin\n }\n\n groups <- vec_group_loc(.subset2(coords, \"gshape\"))\n coords$gshape <- NULL\n\n # reordering by drawing order\n ordering <- vapply(\n .subset2(groups, \"key\"),\n function(gshape) {\n attr(gshape, \"gshape_ordering\", exact = TRUE) %||% NA_integer_\n },\n integer(1L),\n USE.NAMES = FALSE\n )\n groups <- vec_slice(groups, order(ordering))\n coords <- vec_chop(coords, indices = .subset2(groups, \"loc\"))\n\n grobs <- .mapply(\n make_draw_grob,\n list(draw = .subset2(groups, \"key\"), data = coords),\n list(dots = .__gshape_dots__)\n )\n grobs <- grobs[vapply(grobs, is.grob, logical(1L), USE.NAMES = FALSE)]\n if (is_empty(grobs)) {\n zeroGrob()\n } else {\n gTree(children = inject(gList(!!!grobs)))\n }\n },\n draw_key = draw_key_gshape\n)\n\n#' Scale for `gshape` aesthetic\n#'\n#' @inheritDotParams ggplot2::discrete_scale -expand -position -aesthetics -palette -scale_name\n#' @param values A list of grobs or functions (including purrr-like lambda\n#' syntax) that define how each cell's grob (graphical object) should be drawn.\n#' @inheritParams ggplot2::scale_discrete_manual\n#' @inherit geom_gshape\n#' @export\nscale_gshape_manual <- function(..., values, breaks = waiver(), na.value = NA) {\n ggplot2::scale_discrete_manual(\n aesthetics = \"gshape\",\n values = .mapply(function(f, i) {\n f <- allow_lambda(f)\n attr(f, \"gshape_ordering\") <- i # save the drawing order\n f\n }, list(values, seq_along(values)), NULL),\n breaks = breaks,\n na.value = na.value,\n ...\n )\n}\n\n# `gshape` should be provided manually\nscale_gshape_discrete <- function(name = waiver(), ...) {\n cli_abort(paste(\n \"You must provide {.fn scale_gshape_manual}\",\n \"to use {.field draw} aesthetic\"\n ))\n}\n\n# `gshape` should be provided manually\nscale_gshape_continuous <- scale_gshape_discrete\n"], ["/ggalign/R/alignpatch-area.R", "# We are removing the patchwork dependency by defining our own version of\n# patchwork::area, as some desired features won't be merged (see this\n# https://github.com/thomasp85/patchwork/issues/379). Therefore, ggalign will\n# retain `alignpatch-*` scripts.\n\n#' Define the plotting areas in `align_plots`\n#'\n#' @inherit patchwork::area\n#' @details\n#' The grid that the areas are specified in reference to enumerate rows from top\n#' to bottom, and coloumns from left to right. This means that `t` and `l`\n#' should always be less or equal to `b` and `r` respectively. Instead of\n#' specifying area placement with a combination of `area()` calls, it is\n#' possible to instead pass in a single string\n#'\n#' ```\n#' areas <- c(area(1, 1, 2, 1),\n#' area(2, 3, 3, 3))\n#' ```\n#'\n#' is equivalent to\n#'\n#' ```\n#' areas < -\"A##\n#' A#B\n#' ##B\"\n#' ```\n#' @return A `ggalign_area` object.\n#' @examples\n#' p1 <- ggplot(mtcars) +\n#' geom_point(aes(mpg, disp))\n#' p2 <- ggplot(mtcars) +\n#' geom_boxplot(aes(gear, disp, group = gear))\n#' p3 <- ggplot(mtcars) +\n#' geom_bar(aes(gear)) +\n#' facet_wrap(~cyl)\n#'\n#' layout <- c(\n#' area(1, 1),\n#' area(1, 3, 3),\n#' area(3, 1, 3, 2)\n#' )\n#'\n#' # Show the layout to make sure it looks as it should\n#' plot(layout)\n#'\n#' # Apply it to a alignpatches\n#' align_plots(p1, p2, p3, design = layout)\n#' @export\narea <- function(t, l, b = t, r = l) {\n if (missing(t) || missing(l)) {\n one_area <- list(\n t = integer(0L),\n l = integer(0L),\n b = integer(0L),\n r = integer(0L)\n )\n } else {\n one_area <- df_list(\n t = vec_cast(t, integer()),\n l = vec_cast(l, integer()),\n b = vec_cast(b, integer()),\n r = vec_cast(r, integer())\n )\n if (any(.subset2(one_area, \"t\") > .subset2(one_area, \"b\"))) {\n cli_abort(\"{.arg t} must be less than {.arg b}\")\n }\n if (any(.subset2(one_area, \"l\") > .subset2(one_area, \"r\"))) {\n cli_abort(\"{.arg l} must be less than {.arg r}\")\n }\n }\n new_areas(one_area)\n}\n\n# Define a custom S3 class `ggalign_area`, without using S7 directly\n# Patchwork expects traditional S3 classes, and S7 classes are not fully\n# interoperable with patchwork layouts.\nS3_area <- S7::new_S3_class(\"ggalign_area\")\n\nnew_areas <- function(x) new_rcrd(x, class = c(\"ggalign_area\", \"patch_area\"))\n\ncreate_area <- function(ncol, nrow, byrow) {\n mat <- matrix(seq_len(ncol * nrow),\n nrow = nrow, ncol = ncol, byrow = byrow\n )\n ind <- as.vector(mat)\n ind <- match(seq_along(ind), ind)\n area(t = row(mat)[ind], l = col(mat)[ind])\n}\n\n#' @export\nobj_print_data.ggalign_area <- function(x, ...) {\n x <- vec_data(x)\n if (vec_size(x) > 0) {\n x <- vec_set_names(x, paste0(vec_seq_along(x), \": \"))\n print(x = x, ..., quote = FALSE)\n } else {\n cat(\" \", names(x), \"\\n\", sep = \" \")\n }\n}\n\n#' @export\nobj_print_footer.ggalign_area <- function(x, ...) {\n if (vec_size(x) == 0) {\n ncols <- 0\n nrows <- 0\n } else {\n ncols <- max(field(x, \"r\"))\n nrows <- max(field(x, \"b\"))\n }\n cat(\"\\n\\n\")\n}\n\n#' @export\nvec_ptype_abbr.ggalign_area <- function(x, ...) \"areas\"\n\ntrim_area <- function(area) {\n area <- vec_data(area)\n w <- min(.subset2(area, \"l\"), .subset2(area, \"r\"))\n h <- min(.subset2(area, \"t\"), .subset2(area, \"b\"))\n area$l <- .subset2(area, \"l\") - w + 1L\n area$r <- .subset2(area, \"r\") - w + 1L\n area$t <- .subset2(area, \"t\") - h + 1L\n area$b <- .subset2(area, \"b\") - h + 1L\n new_areas(area)\n}\n\nas_areas <- function(x) UseMethod(\"as_areas\")\n\n#' @export\nas_areas.default <- function(x) {\n cli_abort(\"Cannot convert {.obj_type_friendly {x}} into a design area\")\n}\n\n#' @export\nas_areas.NULL <- function(x) NULL\n\n#' @export\nas_areas.ggalign_area <- function(x) x\n\n#' @export\nas_areas.character <- function(x) {\n call <- current_call() # used for message only\n # split into rows\n x <- .subset2(strsplit(x, split = \"\\n\"), 1L)\n x <- lapply(x, trimws)\n if (identical(x[[1L]], \"\")) x[[1L]] <- NULL\n if (identical(x[[length(x)]], \"\")) x[[length(x)]] <- NULL\n x <- lapply(x, function(x) .subset2(strsplit(x, split = \"\"), 1L))\n ncols <- list_sizes(x)\n ncol <- .subset(ncols, 1L)\n if (any(ncols != ncol)) {\n cli_abort(\"character layout must be rectangular\", call = call)\n }\n row <- rep(seq_along(x), each = ncol)\n col <- rep(seq_len(ncol), length(x))\n x <- unlist(x, use.names = FALSE)\n # here, area will be reordered by the levels of `x`\n area_list <- imap(split(seq_along(x), x), function(i, name) {\n if (identical(name, \"#\")) {\n return(area())\n }\n area_rows <- range(row[i])\n area_cols <- range(col[i])\n t <- .subset(area_rows, 1L)\n l <- .subset(area_cols, 1L)\n b <- .subset(area_rows, 2L)\n r <- .subset(area_cols, 2L)\n if (!all(x[row >= t & row <= b & col >= l & col <= r] ==\n x[.subset(i, 1L)])) {\n cli_abort(\"Patch areas must be rectangular\", call = call)\n }\n new_areas(list(t = t, l = l, b = b, r = r))\n })\n vec_c(!!!vec_set_names(area_list, NULL))\n}\n\n# For area from patchwork\n#' @export\nas_areas.patch_area <- function(x) add_class(x, \"ggalign_area\")\n\n#' @importFrom grid unit\n#' @importFrom ggplot2 aes margin theme ggplot\n#' @importFrom utils packageVersion\n#' @export\nplot.ggalign_area <- function(x, ...) {\n data <- vec_data(x)\n data$l <- data$l - 0.45\n data$r <- data$r + 0.45\n data$t <- data$t - 0.45\n data$b <- data$b + 0.45\n data$name <- as.factor(vec_seq_along(x))\n b_fun <- function(lim) {\n if (lim[1] < lim[2]) {\n lim <- seq(floor(lim[1]), ceiling(lim[2]), by = 1)\n } else {\n lim <- seq(ceiling(lim[1]), floor(lim[2]), by = -1)\n }\n lim[-c(1, length(lim))]\n }\n ggplot(data) +\n ggplot2::geom_rect(aes(\n xmin = .data$l, xmax = .data$r,\n ymin = .data$t, ymax = .data$b, fill = .data$name\n ), alpha = 0.3) +\n ggplot2::scale_y_reverse(breaks = b_fun, expand = c(0, 0.04)) +\n ggplot2::scale_x_continuous(\n breaks = b_fun, expand = c(0, 0.04), position = \"top\"\n ) +\n ggplot2::labs(fill = \"Patch\") +\n ggplot2::theme_void() +\n theme(\n panel.grid.minor = if (packageVersion(\"ggplot2\") >= \"3.4.0\") {\n ggplot2::element_line(linewidth = 0.5, colour = \"grey\")\n } else {\n ggplot2::element_line(size = 0.5, colour = \"grey\")\n },\n axis.text = ggplot2::element_text(),\n axis.ticks.length = unit(3, \"mm\"),\n plot.margin = margin(10, 10, 10, 10)\n )\n}\n"], ["/ggalign/R/raster-magick.R", "#' Rasterize the ggplot layers\n#'\n#' The function rasterizes input graphical objects (e.g., grob, layer, ggplot)\n#' and optionally processes the resulting raster using magick, a powerful image\n#' manipulation library. This allows for advanced graphical transformations\n#' directly within the plotting pipeline.\n#'\n#' @param x An object to rasterize, can be a [`grob()`][grid::grob],\n#' [`layer()`][ggplot2::layer], [`ggplot()`][ggplot2::ggplot], or a list of such\n#' objects.\n#'\n#' @inheritParams rlang::args_dots_empty\n#' @inheritParams magickGrob\n#' @examples\n#' # Currently, `magick` package require R >= 4.1.0\n#' if (requireNamespace(\"magick\")) {\n#' # data generated code was copied from `ComplexHeatmap`\n#' set.seed(123)\n#' small_mat <- matrix(rnorm(56), nrow = 7)\n#' rownames(small_mat) <- paste0(\"row\", seq_len(nrow(small_mat)))\n#' colnames(small_mat) <- paste0(\"column\", seq_len(ncol(small_mat)))\n#' ggheatmap(small_mat, aes(.x, .y), filling = NULL) +\n#' raster_magick(geom_tile(aes(fill = value)), res = 20)\n#'\n#' ggheatmap(small_mat, aes(.x, .y), filling = NULL) +\n#' # Use `magick::filter_types()` to check available `filter` arguments\n#' raster_magick(\n#' geom_tile(aes(fill = value)),\n#' magick = function(image) {\n#' magick::image_resize(image,\n#' geometry = \"50%x\", filter = \"Lanczos\"\n#' )\n#' }\n#' )\n#' }\n#' @return An object with the same class of the input.\n#' @seealso [`magickGrob()`]\n#' @export\nraster_magick <- function(x, magick = NULL, ...,\n res = NULL, interpolate = FALSE,\n vp = NULL) {\n rlang::check_installed(\"magick\", \"to use `raster_magick()`\")\n if (!is.null(magick) && !is.function(magick <- allow_lambda(magick))) {\n cli_abort(\"{.arg magick} must be a function\")\n }\n assert_number_whole(res, min = 1, allow_null = TRUE)\n assert_bool(interpolate)\n raster_magick0(\n x = x, ..., magick = magick,\n res = res, interpolate = interpolate,\n vp = vp\n )\n}\n\n# Used to do the actual process, but won't check the arguments\n#' @keywords internal\nraster_magick0 <- function(x, ...) {\n UseMethod(\"raster_magick0\")\n}\n\n#' @importFrom ggplot2 ggproto ggproto_parent\n#' @export\nraster_magick0.Layer <- function(x, ...) {\n ggproto(\n NULL, x,\n draw_geom = function(self, data, layout) {\n grobs <- ggproto_parent(x, self)$draw_geom(data, layout)\n if (!inherits(layout$coord, \"CoordCartesian\")) {\n cli_warn(\n \"{.fn raster_magick} only works with {.fn coord_cartesian}.\"\n )\n return(grobs)\n }\n raster_magick0(grobs, ...)\n }\n )\n}\n\n#' @export\nraster_magick0.ggplot <- function(x, ...) {\n x$layers <- lapply(x$layers, raster_magick0, ...)\n x\n}\n\n#' @export\nraster_magick0.list <- function(x, ...) lapply(x, raster_magick0, ...)\n\n#' @export\nraster_magick0.grob <- function(x, magick = NULL, ...,\n res = NULL, interpolate = FALSE,\n vp = NULL) {\n rlang::check_dots_empty()\n magickGrob0(\n grob = x, magick = magick,\n res = res, interpolate = interpolate, vp = vp\n )\n}\n\n#' @export\nraster_magick0.gList <- raster_magick0.grob\n\n#' @export\nraster_magick0.default <- function(x, ...) {\n cli_abort(\"Cannot rasterize {.obj_type_friendly {x}}\")\n}\n"], ["/ggalign/R/craftbox-.R", "# Use S4 to override the double dispatch problem of ggplot2\n# And it's easy to convert a S4 Class to a S7 Class\nmethods::setClass(\n \"CraftBox\",\n list(\n plot = \"ANY\", # To avoid modify in place, we put plot in a slot\n active = \"ANY\",\n size = \"ANY\",\n schemes = \"ANY\",\n craftsman = \"ANY\" # `Craftsman` object\n )\n)\n\n#' Show `CraftBox` information\n#' @param object A `CraftBox` object.\n#' @return The input invisiblely.\n#' @keywords internal\nmethods::setMethod(\"show\", \"CraftBox\", function(object) {\n print(object)\n})\n\n#' @importFrom methods new\nnew_craftbox <- function(craftsman = NULL, ...,\n plot = NULL, active = NULL, size = NULL,\n schemes = NULL, call = caller_call()) {\n assert_active(active, allow_null = FALSE, call = call)\n if (is.null(size)) {\n size <- unit(NA, \"null\")\n } else {\n size <- check_size(size, call = call)\n }\n new(\n \"CraftBox\",\n # `call`: used to provide error message\n craftsman = ggproto(NULL, craftsman %||% Craftsman, ..., call = call),\n schemes = schemes %||% default_schemes(),\n plot = plot, active = active, size = size\n )\n}\n\n#' @export\nprint.CraftBox <- function(x, ...) {\n cat(x@craftsman$summary(x@plot), sep = \"\\n\")\n invisible(x)\n}\n\n#' @export\nplot.CraftBox <- function(x, ...) {\n cli_abort(sprintf(\"Cannot plot %s object directly\", object_name(x)))\n}\n\n#' @importFrom grid grid.draw\n#' @exportS3Method\ngrid.draw.CraftBox <- plot.CraftBox\n\n#' Add custom objects to ggalign plot\n#' @keywords internal\nmethods::setMethod(\"+\", c(\"CraftBox\", \"ANY\"), function(e1, e2) {\n if (missing(e2)) {\n cli_abort(c(\n \"Cannot use {.code {.Generic}} with a single argument.\",\n \"i\" = \"Did you accidentally put {.code {.Generic}} on a new line?\"\n ))\n }\n\n if (is.null(e2)) return(e1) # styler: off\n\n # Get the name of what was passed in as e2, and pass along so that it\n # can be displayed in error messages\n e2name <- paste(deparse(substitute(e2)), collapse = \" \")\n switch(.Generic, # nolint\n `+` = craftbox_add(e2, e1, e2name),\n stop_incompatible_op(.Generic, e1, e2)\n )\n})\n\n#' @importFrom methods is\nis_craftbox <- function(x) is(x, \"CraftBox\")\n\nis_cross_plot <- function(x) is_craftbox(x) && is_cross(x@craftsman)\n\nis_cross <- function(x) inherits(x, \"CraftCross\")\n\n#######################################################\n#' @importFrom ggplot2 ggproto\nCraftsman <- ggproto(\"Craftsman\",\n call = NULL,\n\n # following fields will be added when added to the layout\n in_linear = NULL,\n layout_name = NULL,\n direction = NULL,\n position = NULL, # for stack_layout() in quad_layout()\n labels = NULL,\n\n # A single boolean value indicates whether we should set facet and coord\n free_facet = FALSE,\n free_coord = FALSE,\n free_limits = FALSE,\n\n # we always prevent user from modifying the object in `$build_plot()` and\n # `$finish_plot()` methods\n locked = TRUE,\n lock = function(self) {\n assign(\"locked\", value = TRUE, envir = self)\n },\n unlock = function(self) {\n assign(\"locked\", value = FALSE, envir = self)\n },\n\n ############################################################\n # when added to the `Layout` object, will call following methods\n\n # we usually, define the `nobs` in `interact_layout`, since we can\n # act with the layout data in `interact_layout` method\n interact_layout = function(self, layout) layout,\n\n # we define the `panel` and `index` method in `setup_design` method\n setup_design = function(self, design) design,\n setup_plot = function(self, plot) plot,\n\n ##############################################################\n # Don't change the facet and coord in following methods\n build_plot = function(self, plot, design, extra_design = NULL,\n previous_design = NULL) {\n plot\n },\n finish_plot = function(self, plot, schemes, theme) {\n plot <- plot_add_schemes(plot, schemes)\n ggremove_margin(plot, self$direction) + theme_recycle()\n },\n\n # utils method to print the object, should return a character vector\n summary = function(self, plot) {\n cls <- class(self)\n cls <- cls[seq_len(which(cls == \"Craftsman\"))]\n sprintf(\"\", paste(cls, collapse = \" \"))\n }\n)\n\n# Used to lock the `Craftsman` object\n#' @export\n`$<-.Craftsman` <- function(x, name, value) {\n if (x$locked) {\n cli_abort(c(\n sprintf(\"Cannot modify %s\", object_name(x)),\n i = sprintf(\"%s is locked\", object_name(x))\n ), call = x$call)\n }\n NextMethod()\n}\n\n#################################################################\ncraftbox_add <- function(object, craftbox, object_name) {\n if (is.null(craftbox@plot)) {\n cli_abort(c(\n sprintf(\n \"Cannot add {.var {object_name}} to %s\",\n object_name(craftbox)\n ),\n i = sprintf(\"no plot found for %s\", object_name(craftbox))\n ))\n }\n UseMethod(\"craftbox_add\")\n}\n\n#' @importFrom ggplot2 ggplot_add\n#' @export\ncraftbox_add.default <- function(object, craftbox, object_name) {\n craftbox@plot <- ggplot_add(\n object,\n ggfun(\"plot_clone\")(craftbox@plot),\n object_name\n )\n craftbox\n}\n\n#' @export\ncraftbox_add.ggalign_scheme <- function(object, craftbox, object_name) {\n name <- ggalign_scheme_name(object)\n craftbox@schemes[name] <- list(update_scheme(\n object, .subset2(craftbox@schemes, name), object_name\n ))\n craftbox\n}\n\n######################################################################\nplot_build <- function(align, ..., schemes, theme) {\n plot <- align$build_plot(plot@plot, ...)\n align$finish_plot(plot, schemes, theme)\n}\n"], ["/ggalign/R/layout-chain-stack-switch.R", "#########################################################\n#' Determine the active context of stack layout\n#'\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' `stack_active` is an alias for `stack_switch()`, which sets `what = NULL` by\n#' default.\n#'\n#' @inheritParams rlang::args_dots_empty\n#' @inheritParams quad_switch\n#' @inheritParams stack_discrete\n#' @param what What should get activated for the stack layout?\n#' `r rd_chain_what()`, this is useful when the active context is a\n#' [`quad_layout()`] object, where any `align_*()` will be added to the\n#' [`quad_layout()`]. By removing the active context, we can add `align_*()`\n#' into the [`stack_layout()`].\n#' @return A `stack_switch` object which can be added to [stack_layout()].\n#' @examples\n#' stack_discrete(\"h\", matrix(1:9, nrow = 3L)) +\n#' ggheatmap() +\n#' # ggheamtap will set the active context, directing following addition\n#' # into the heatmap plot area. To remove the heatmap active context,\n#' # we can use `stack_active()` which will direct subsequent addition into\n#' # the stack\n#' stack_active() +\n#' # here we add a dendrogram to the stack.\n#' align_dendro()\n#' @export\nstack_switch <- function(sizes = NULL, what = waiver(), ...) {\n rlang::check_dots_empty()\n if (!is.waive(what)) what <- check_stack_context(what)\n if (!is.null(sizes)) sizes <- check_stack_sizes(sizes)\n structure(list(what = what, sizes = sizes), class = \"stack_switch\")\n}\n\n#' @export\n#' @rdname stack_switch\nstack_active <- function(sizes = NULL, ...) {\n rlang::check_dots_empty()\n stack_switch(sizes, what = NULL)\n}\n"], ["/ggalign/R/grid-grob-channel.R", "#' Create a Grob That Spans Multiple Viewports\n#'\n#' This function initializes a communication channel to share location signals\n#' across different viewports. It returns a `channelSenderGrob` object, which\n#' can transmit multiple signals using its `$signal` method (see the \"Signal\"\n#' section below for details). When drawn, all collected signals are passed to\n#' the `make_content` function to generate the final [`grob`][grid::grob].\n#'\n#' @param make_content A function that accepts the list of signal locations and\n#' returns a [`grob`][grid::grob].\n#' @param ... Additional arguments passed to `make_content`.\n#' @inheritParams grid::grob\n#'\n#' @section Signal:\n#' A `channelSenderGrob` can emit multiple location signals using the `$signal`\n#' method. This method accepts the following arguments:\n#'\n#' - `x`: X-coordinate.\n#' - `y`: Y-coordinate.\n#' - `default.units`: The default units for `x` and `y`.\n#' - `tag`: A character string used to identify the location.\n#' - `name`: A name for the returned grob.\n#' - `vp`: A [`viewport`][grid::viewport] for the returned grob.\n#'\n#' The `$signal` method returns a `channelSignalGrob`.\n#'\n#' @return A `channelSenderGrob` object.\n#' @examples\n#' # we create a new channel, we will emit two singals\n#' # here: we just add a line between the two signals\n#' channel <- channelGrob(function(locations) {\n#' # you can also use `tag` to identify the locations\n#' loc1 <- .subset2(locations, 1L)\n#' loc2 <- .subset2(locations, 2L)\n#' grid::segmentsGrob(loc1$x, loc1$y, loc2$x, loc2$y)\n#' })\n#'\n#' gt <- gtable::gtable(unit(1:2, c(\"cm\")), unit(5, \"cm\"))\n#' gt <- gtable::gtable_add_grob(\n#' gt,\n#' list(\n#' grid::rectGrob(gp = gpar(color = \"black\", fill = NA)),\n#' channel$signal(0.5, 0.5, \"npc\")\n#' ),\n#' t = 1, l = 1, name = c(\"rect1\", \"signal1\")\n#' )\n#' gt <- gtable::gtable_add_grob(\n#' gt,\n#' list(\n#' grid::rectGrob(gp = gpar(color = \"red\", fill = NA)),\n#' channel$signal(0.5, 0.5, \"npc\")\n#' ),\n#' t = 1, l = 2, name = c(\"rect2\", \"signal2\")\n#' )\n#' grid::grid.newpage()\n#' grid::grid.draw(gt)\n#' @importFrom grid unit is.unit grob\n#' @importFrom rlang list2\n#' @export\nchannelGrob <- function(make_content, ..., name = NULL, vp = NULL) {\n make_content <- allow_lambda(make_content)\n if (!is.function(make_content)) {\n cli_abort(\"{.arg make_content} must be a function\")\n }\n # Used to communicate between different signals\n channel <- new.env(parent = emptyenv())\n channel$make_content <- make_content\n channel$dots <- list2(...)\n channel$n <- 0L # total number of signals\n grob(\n channel = channel,\n name = name,\n vp = vp,\n\n # method used to release signal and retutn a new grob\n signal = function(self, x, y, default.units = \"native\",\n tag = NULL, name = NULL, vp = NULL) {\n if (!is.unit(x)) x <- unit(x, default.units)\n if (!is.unit(y)) y <- unit(y, default.units)\n if (length(x) != length(y)) {\n cli_abort(\"{.arg x} and {.arg y} must have the same length\")\n }\n assert_string(tag, allow_empty = FALSE, allow_null = TRUE)\n signal <- list(list(x = x, y = y))\n if (!is.null(tag)) names(signal) <- tag\n channel <- .subset2(self, \"channel\")\n channel$signals <- c(channel$signals, signal)\n i <- channel$n <- channel$n + 1L\n grob(\n channel = channel,\n i = i,\n name = name,\n vp = vp,\n cl = c(\"channelSignalGrob\", \"channelGrob\")\n )\n },\n # Grob used to send signals\n cl = c(\"channelSenderGrob\", \"channelGrob\")\n )\n}\n\n#' @export\n`$.channelGrob` <- function(self, name) {\n field <- .subset2(self, name)\n if (!is.function(field)) {\n return(field)\n }\n args <- formals(field)\n # is.null is a fast path for a common case; the %in% check is slower but\n # also catches the case where there's a `self = NULL` argument.\n has_self <- !is.null(args[[\"self\"]]) || \"self\" %in% names(args)\n\n # We assign the method with its correct name and construct a call to it to\n # make errors reported as coming from the method name rather than `field()`\n assign(name, field, envir = environment())\n args <- list(quote(...))\n if (has_self) {\n args$self <- quote(self)\n }\n rlang::new_function(alist(... = ), rlang::call2(name, !!!args))\n}\n\n#' @export\n`[[.channelGrob` <- `$.channelGrob`\n\n# https://www.stat.auckland.ac.nz/~paul/Reports/CustomGrobs/custom-grob.html\n# preDraw:\n# - makeContext\n# - pushvpgp\n# - preDrawDetails: by default, do noting\n# makeContent:\n# drawDetails:\n# postDraw:\n# - postDrawDetails: by default, do noting\n# - popgrobvp\n#' @importFrom grid makeContent drawDetails viewport is.grob gTree grob\n#' @export\nmakeContent.channelGrob <- function(x) {\n channel <- .subset2(x, \"channel\")\n # If no signals, do nothing\n if (channel$n == 0L) return(x) # styler: off\n\n if (inherits(x, \"channelSenderGrob\")) {\n # we use the viewport from the signals sender\n channel$vp <- grid::current.viewport()\n } else if (inherits(x, \"channelSignalGrob\")) {\n if (is.null(channel$locations)) {\n channel$locations <- vector(\"list\", channel$n)\n names(channel$locations) <- names(channel$signals)\n }\n\n # convert the viewport coordinates to the device coordinates\n i <- .subset2(x, \"i\")\n signal <- .subset2(channel$signals, i)\n channel$locations[[i]] <- grid::deviceLoc(signal$x, signal$y)\n if (all(!vapply(channel$locations, is.null, logical(1L), # styler: off\n USE.NAMES = FALSE))) { # styler: off\n # When all locations have been prepared\n # we output the grob with all device locations\n x <- grob(\n channel = channel,\n vp = .subset2(x, \"vp\"), # Don't change the viewport\n cl = c(\"channelReceiverGrob\", \"channelGrob\")\n )\n }\n }\n x\n}\n\n#' @export\ndrawDetails.channelGrob <- function(x, recording) {\n}\n\n#' @importFrom grid grid.draw viewport gTree is.grob\n#' @export\ndrawDetails.channelReceiverGrob <- function(x, recording) {\n # we always reset the locations after drawing\n old <- grid::current.viewport()$name\n on.exit(grid::seekViewport(old), add = TRUE)\n channel <- .subset2(x, \"channel\")\n locations <- channel$locations\n on.exit(channel$locations <- NULL, add = TRUE)\n if (!is.null(vp <- channel$vp)) {\n grid::seekViewport(vp$name)\n # convert the device cooridnates into the drawing viewport coordinates\n trans <- solve(grid::current.transform())\n locations <- lapply(locations, grid_solve_loc, trans = trans)\n } else { # If no viewport, we use the `ROOT` viewport\n grid::upViewport(0)\n grid::pushViewport(viewport())\n }\n grob <- rlang::inject(channel$make_content(locations, !!!channel$dots))\n if (is.gList(grob)) grob <- gTree(children = grob)\n if (is.grob(grob)) grid.draw(grob, recording = recording)\n}\n"], ["/ggalign/R/craft-cross-mark.R", "#' Add a plot to annotate observations\n#'\n#' @inheritParams cross_none\n#' @inheritParams ggmark\n#'\n#' @section ggplot2 Specification:\n#' The `cross_mark` function initializes a `ggplot` object. The underlying data\n#' contains following columns:\n#'\n#' - `.panel`: the panel for the aligned axis. It means `x-axis` for vertical\n#' stack layout (including top and bottom annotation), `y-axis` for\n#' horizontal stack layout (including left and right annotation).\n#'\n#' - `.names` ([`vec_names()`][vctrs::vec_names]) and `.index`\n#' ([`vec_size()`][vctrs::vec_size()]/[`NROW()`]): a character names (only\n#' applicable when names exists) and an integer of index of the original\n#' data.\n#'\n#' - `.hand`: A factor with levels `c(\"left\", \"right\")` for horizontal stack\n#' layouts, or `c(\"top\", \"bottom\")` for vertical stack layouts, indicating\n#' the position of the linked observations.\n#'\n#' You can use [`scheme_data()`] to modify the internal data if needed.\n#'\n#' @export\ncross_mark <- function(mark, data = waiver(), ...,\n obs_size = 1, inherit_index = NULL, inherit_panel = NULL,\n inherit_nobs = NULL,\n size = NULL, active = NULL) {\n if (!inherits(mark, \"ggalign_mark_draw\")) {\n cli_abort(\"{.arg mark} must be a {.fn mark_draw} object\")\n }\n assert_obs_size(obs_size)\n assert_active(active)\n active <- update_active(active, new_active(use = TRUE))\n cross(CrossMark,\n data = data, data_params = list2(...),\n mark = mark, obs_size = obs_size,\n plot = ggplot(), size = size,\n schemes = default_schemes(th = theme_panel_border()),\n active = active,\n inherit_nobs = inherit_nobs,\n inherit_panel = inherit_panel,\n inherit_index = inherit_index\n )\n}\n\n#' @importFrom ggplot2 ggproto ggproto_parent\n#' @include craft-cross-.R\nCrossMark <- ggproto(\"CrossMark\", CraftCross,\n interact_layout = function(self, layout) {\n if (!self$in_linear) { # only used for linear coordinate\n cli_abort(c(\n sprintf(\n \"Cannot add %s to %s\",\n object_name(self), layout_name\n ),\n i = sprintf(\n \"%s can only be used in linear layout\",\n object_name(self)\n )\n ))\n }\n ggproto_parent(CraftCross, self)$interact_layout(layout)\n },\n build_plot = function(self, plot, design, extra_design = NULL,\n previous_design = NULL) {\n if (is.null(.subset2(previous_design, \"nobs\"))) {\n cli_abort(\n sprintf(\n \"layout {.field nobs} for %s before %s is not initialized \",\n self$layout_name, object_name(self)\n )\n )\n }\n if (is.null(.subset2(design, \"nobs\"))) {\n cli_abort(\n sprintf(\n \"layout {.field nobs} for %s after %s is not initialized \",\n self$layout_name, object_name(self)\n )\n )\n }\n direction <- self$direction\n\n # parse links --------------------------------------------\n mark <- self$mark\n design1 <- previous_design\n design2 <- design\n full_data1 <- split(\n seq_len(.subset2(design1, \"nobs\")),\n .subset2(design1, \"panel\")\n )\n full_data2 <- split(\n seq_len(.subset2(design2, \"nobs\")),\n .subset2(design2, \"panel\")\n )\n link_index <- make_links_data(\n .subset2(mark, \"links\"),\n design1 = design1, design2 = design2,\n labels1 = self$labels0, labels2 = self$labels\n )\n if (vec_duplicate_any(nms <- names(link_index))) { # nolint\n cli_abort(\n c(\n \"panel names must be unique in {.arg mark}\",\n i = \"duplicated names: {.val {nms[vec_duplicate_detect(nms)]}}\"\n ),\n call = self$call\n )\n }\n data_index <- lapply(link_index, function(link) {\n if (is.null(link)) {\n return(NULL)\n }\n hand1 <- .subset2(link, \"hand1\")\n hand2 <- .subset2(link, \"hand2\")\n list(\n hand1 = .subset2(design1, \"index\")[hand1],\n hand2 = .subset2(design2, \"index\")[hand2]\n )\n })\n\n # prepare data for the plot\n plot_data <- lapply(data_index, function(index) {\n if (is.null(index)) {\n return(NULL)\n }\n hand1 <- .subset2(index, \"hand1\")\n hand2 <- .subset2(index, \"hand2\")\n hand <- switch_direction(\n direction,\n c(\"left\", \"right\"),\n c(\"top\", \"bottom\")\n )\n data_frame0(\n .hand = vec_rep_each(hand, c(length(hand1), length(hand2))),\n .names = vec_c(self$labels0[hand1], self$labels[hand2]),\n .index = vec_c(hand1, hand2)\n )\n })\n plot_data <- vec_rbind(!!!plot_data, .names_to = \".panel\")\n plot_data$.panel <- factor(plot_data$.panel, names(data_index))\n plot_data$.hand <- factor(plot_data$.hand, switch_direction(\n direction, c(\"left\", \"right\"), c(\"bottom\", \"top\")\n ))\n\n # prepare data for the plot ------------------------------\n plot <- gguse_data(plot, plot_data)\n\n # set up facets\n if (nlevels(plot_data$.panel) > 1L) {\n if (inherits(plot$facet, \"FacetGrid\")) {\n facet <- switch_direction(\n direction,\n ggplot2::facet_grid(\n rows = ggplot2::vars(.data$.panel),\n scales = \"free_y\", space = \"free\",\n drop = FALSE, as.table = FALSE\n ),\n ggplot2::facet_grid(\n cols = ggplot2::vars(.data$.panel),\n scales = \"free_x\", space = \"free\",\n drop = FALSE, as.table = FALSE\n )\n )\n } else {\n facet <- switch_direction(\n direction,\n ggplot2::facet_wrap(\n facets = ggplot2::vars(.data$.panel),\n ncol = 1L, as.table = FALSE\n ),\n ggplot2::facet_wrap(\n facets = ggplot2::vars(.data$.panel),\n nrow = 1L, as.table = FALSE\n )\n )\n }\n } else {\n facet <- facet_stack(direction, object_name(self))\n }\n # `free_row` and `free_column` have nothing with `facet_stack`\n # it's safe to use it directly\n plot <- ggmelt_facet(plot, facet, free_row = TRUE, free_column = TRUE)\n plot$ggalign_link_data <- list(\n full_data1 = full_data1,\n full_data2 = full_data2,\n link_index = link_index,\n data_index = data_index,\n direction = direction,\n draw = .subset2(mark, \"draw\"),\n obs_size = self$obs_size\n )\n add_class(plot, \"ggalign_mark_plot\", \"patch_ggplot\")\n },\n finish_plot = function(self, plot, schemes, theme) {\n plot <- plot_add_schemes(plot, schemes)\n\n # save spacing for usage\n spacing <- calc_element(\n switch_direction(\n self$direction,\n \"panel.spacing.y\",\n \"panel.spacing.x\"\n ),\n theme\n ) %||% unit(0, \"mm\")\n\n # save spacing for usage\n plot$ggalign_link_data$spacing1 <-\n plot$ggalign_link_data$spacing2 <- spacing\n\n plot + theme_recycle()\n },\n summary = function(self, plot) {\n header <- ggproto_parent(CraftCross, self)$summary(plot)\n c(header, \" Add plot to annotate observations\")\n }\n)\n\nmark_use_facet <- function(plot, facet) {\n\n}\n"], ["/ggalign/R/import-standalone-tibble.R", "# Standalone file: do not edit by hand\n# Source: https://github.com/Yunuuuu/standalone/blob/HEAD/R/standalone-tibble.R\n# Generated by: usethis::use_standalone(\"Yunuuuu/standalone\", \"tibble\")\n# ----------------------------------------------------------------------\n#\n# ---\n# repo: Yunuuuu/standalone\n# file: standalone-tibble.R\n# last-updated: 2024-11-14\n# license: https://unlicense.org\n# imports: [vctrs (>= 0.5.0), rlang]\n# ---\n\n# when developing R package, instead of depending on `dplyr`, `tidyr`, `tibble`.\n# we prefer use the basic function from `vctrs`\n#\n# Note: these functions won't check arguments\n#\n# Since `vctrs` also depends on `rlang` and `cli`, it has no harm to use\n# function from `rlang` and `cli`.\n#\n# Please initialize the package docs and import vctrs\n# 1. run `usethis::use_package_doc()`\n# 2. in package docs, please add #' @import vctrs\n\n# ## Changelog\n# 2025-03-12\n# - Added `case_when()`\n#\n# 2024-11-14\n# - Added `column_to_rownames()`\n#\n# 2024-11-13\n# - fix wrong results in `coalesce()`: we should assign value in the missing\n# index\n#\n# 2024-11-12\n# - Added `rename`\n# - coalesce() now will return value immediately when no missing value exists.\n#\n# 2024-11-11:\n# - Added `inner_join`\n# - Added `left_join`\n# - Added `right_join`\n# - Added `cross_join`\n# - Added `replace_na`\n# - Added `coalesce`\n# - Added `deframe`\n# - Added `enframe`\n# - Added `remove_rownames`\n# - Added `rownames_to_column`\n#\n# 2024-11-10:\n# - Added `full_join`\n# - Added `if_else`\n#\n# nocov start\n\n#' @importFrom rlang set_names\nfull_join <- function(\n x,\n y,\n by = vec_set_intersect(names(x), names(y)),\n by.x = by,\n by.y = by,\n suffix = c(\".x\", \".y\")\n) {\n loc <- vec_locate_matches(x[by.x], set_names(y[by.y], by.x), remaining = NA)\n x_slicer <- .subset2(loc, \"needles\")\n y_slicer <- .subset2(loc, \"haystack\")\n ans <- join_bind(\n vec_slice(x, x_slicer),\n # drop duplicated join column\n vec_slice(y[vec_set_difference(names(y), by.y)], y_slicer),\n suffix = suffix\n )\n new_rows <- which(vec_detect_missing(x_slicer)) # should come from `y`\n if (length(new_rows)) {\n ans[new_rows, by.x] <- vec_slice(y[by.y], y_slicer[new_rows])\n }\n ans\n}\n\n#' @importFrom rlang set_names\ninner_join <- function(\n x,\n y,\n by = vec_set_intersect(names(x), names(y)),\n by.x = by,\n by.y = by,\n suffix = c(\".x\", \".y\")\n) {\n loc <- vec_locate_matches(\n x[by.x],\n set_names(y[by.y], by.x),\n no_match = \"drop\"\n )\n x_slicer <- .subset2(loc, \"needles\")\n y_slicer <- .subset2(loc, \"haystack\")\n join_bind(\n vec_slice(x, x_slicer),\n # drop duplicated join column\n vec_slice(y[vec_set_difference(names(y), by.y)], y_slicer),\n suffix = suffix\n )\n}\n\n#' @importFrom rlang set_names\nleft_join <- function(\n x,\n y,\n by = vec_set_intersect(names(x), names(y)),\n by.x = by,\n by.y = by,\n suffix = c(\".x\", \".y\")\n) {\n loc <- vec_locate_matches(x[by.x], set_names(y[by.y], by.x))\n x_slicer <- .subset2(loc, \"needles\")\n y_slicer <- .subset2(loc, \"haystack\") # can have NA value\n join_bind(\n vec_slice(x, x_slicer),\n # drop duplicated join column\n vec_slice(y[vec_set_difference(names(y), by.y)], y_slicer),\n suffix = suffix\n )\n}\n\n#' @importFrom rlang set_names\nright_join <- function(\n x,\n y,\n by = vec_set_intersect(names(x), names(y)),\n by.x = by,\n by.y = by,\n suffix = c(\".x\", \".y\")\n) {\n loc <- vec_locate_matches(\n x[by.x],\n set_names(y[by.y], by.x),\n no_match = \"drop\",\n remaining = NA\n )\n x_slicer <- .subset2(loc, \"needles\") # can have NA value\n y_slicer <- .subset2(loc, \"haystack\")\n join_bind(\n # drop duplicated join column\n vec_slice(x[vec_set_difference(names(x), by.x)], x_slicer),\n vec_slice(y, y_slicer),\n suffix = suffix\n )\n}\n\ncross_join <- function(x, y, suffix = c(\".x\", \".y\")) {\n x_size <- vec_size(x)\n y_size <- vec_size(y)\n x_out <- vec_rep_each(x, times = y_size)\n y_out <- vec_rep(y, times = x_size)\n join_bind(x_out, y_out, suffix)\n}\n\njoin_bind <- function(x, y, suffix) {\n x_names <- names(x)\n y_names <- names(y)\n common <- vec_set_intersect(x_names, y_names)\n if (length(common)) {\n # add suffix to duplicated names\n index <- vec_match(common, x_names)\n names(x)[index] <- paste0(x_names[index], .subset(suffix, 1L))\n index <- vec_match(common, y_names)\n names(y)[index] <- paste0(y_names[index], .subset(suffix, 2L))\n }\n vec_cbind(x, y, .name_repair = \"check_unique\")\n}\n\n#' Rename elements in a list, data.frame or vector\n#'\n#' This is akin to `dplyr::rename` and `plyr::rename`. It renames elements given\n#' as names in the `replace` vector to the values in the `replace` vector\n#' without touching elements not referenced.\n#'\n#' @param x A data.frame or a named vector or list\n#' @param replace A named character vector. The names identifies the elements in\n#' `x` that should be renamed and the values gives the new names.\n#'\n#' @return `x`, with new names according to `replace`\n#' @noRd\nrename <- function(x, replace) {\n nms <- names(x)\n names(x) <- vec_assign(nms, match(names(replace), nms), replace)\n x\n}\n\nif_else <- function(condition, true, false, na = NULL) {\n # output size from `condition`\n size <- vec_size(condition)\n\n # output type from `true`/`false`/`na`\n ptype <- vec_ptype_common(true = true, false = false, na = na)\n\n args <- vec_recycle_common(\n true = true,\n false = false,\n na = na,\n .size = size\n )\n args <- vec_cast_common(!!!args, .to = ptype)\n\n out <- vec_init(ptype, size)\n\n loc_true <- condition\n loc_false <- !condition\n\n out <- vec_assign(out, loc_true, vec_slice(args$true, loc_true))\n out <- vec_assign(out, loc_false, vec_slice(args$false, loc_false))\n\n if (!is.null(na)) {\n loc_na <- vec_detect_missing(condition)\n out <- vec_assign(out, loc_na, vec_slice(args$na, loc_na))\n }\n\n out\n}\n\ncase_when <- function(.default, ..., .ptype = NULL) {\n if (is.null(.ptype)) {\n .ptype <- vec_ptype(.default)\n } else {\n .default <- vec_cast(.default, .ptype)\n }\n env <- rlang::caller_env()\n dots <- rlang::list2(...)\n unused <- vec_rep(TRUE, times = vec_size(.default))\n for (i in seq_along(dots)) {\n if (!any(unused)) {\n break\n }\n dot <- .subset2(dots, i)\n loc <- unused & rlang::eval_tidy(rlang::f_lhs(dot), env = env)\n value <- rlang::eval_tidy(rlang::f_rhs(dot), env = env)\n value <- vec_cast(value, .ptype, x_arg = sprintf(\"`...` (%d)\", i))\n if (length(value) > 1L) value <- vec_slice(value, loc)\n .default <- vec_assign(\n .default,\n loc,\n value,\n value_arg = sprintf(\"`...` (%d)\", i)\n )\n unused[loc] <- FALSE\n }\n .default\n}\n\n\n#' Replace NAs with specified values\n#' @param value A single value.\n#' @noRd\nreplace_na <- function(x, value) {\n value <- vec_cast(x = value, to = x, x_arg = \"value\", to_arg = \"x\")\n vec_assign(x, vec_detect_missing(x), value)\n}\n\n#' Find the first non-missing element\n#' @param ... A list of atomic vector (You shouldn't input `NULL`).\n#' @noRd\ncoalesce <- function(...) {\n dots <- vec_recycle_common(...)\n out <- .subset2(dots, 1L)\n for (i in 2:length(dots)) {\n if (vec_any_missing(out)) {\n missing <- vec_detect_missing(out)\n out <- vec_assign(\n out,\n missing,\n vec_slice(.subset2(dots, i), missing)\n )\n } else {\n return(out)\n }\n }\n out\n}\n\n#' Convert values to `NA`\n#' @noRd\nna_if <- function(x, y) {\n y <- vec_cast(x = y, to = x, x_arg = \"y\", to_arg = \"x\")\n y <- vec_recycle(y, size = vec_size(x), x_arg = \"y\")\n na <- vec_init(x)\n vec_assign(x, vec_equal(x, y, na_equal = TRUE), na)\n}\n\ndeframe <- function(x) {\n if (ncol(x) == 1L) {\n return(x[[1]])\n }\n vec_set_names(x[[1L]], x[[2]])\n}\n\nenframe <- function(x, name = \"name\", value = \"value\") {\n if (!is.null(names(x))) {\n data <- list(names(x), unname(x))\n } else {\n data <- list(seq_along(x), unname(x))\n }\n new_data_frame(vec_set_names(data, c(name, value)))\n}\n\nremove_rownames <- function(.data) {\n rownames(.data) <- NULL\n .data\n}\n\nrownames_to_column <- function(.data, var = \"rowname\") {\n if (!is.null(var_col <- rownames(.data))) {\n nms <- names(.data)\n .data[[var]] <- var_col\n .data <- .data[c(var, nms)]\n }\n .data\n}\n\ncolumn_to_rownames <- function(.data, var = 1L) {\n rownames(.data) <- .subset2(.data, var)\n .data[[var]] <- NULL\n .data\n}\n\n# nocov end\n"], ["/ggalign/R/ggplot-geom-rect3d.R", "#' Add z-aesthetic for geom_tile\n#'\n#' @section new aesthetics:\n#' - `z`: the third dimention (in the z direction), use\n#' [`scale_z_continuous()`] to control the ranges.\n#' - `theta`: Angle between x-axis and z-axis.\n#' @inheritParams ggplot2::layer\n#' @inheritParams ggplot2::geom_polygon\n#' @inheritParams ggplot2::geom_path\n#' @aesthetics GeomRect3d\n#' @examples\n#' set.seed(123)\n#' small_mat <- matrix(rnorm(81), nrow = 9)\n#' rownames(small_mat) <- paste0(\"row\", seq_len(nrow(small_mat)))\n#' colnames(small_mat) <- paste0(\"column\", seq_len(ncol(small_mat)))\n#' ggheatmap(small_mat,\n#' filling = FALSE,\n#' theme = theme(\n#' legend.box.spacing = unit(10, \"mm\"),\n#' plot.margin = margin(t = 15, unit = \"mm\")\n#' )\n#' ) +\n#' geom_tile3d(\n#' aes(fill = value, z = value, width = 0.8, height = 0.8),\n#' color = \"black\"\n#' ) +\n#' scale_fill_viridis_c(\n#' option = \"plasma\",\n#' breaks = scales::breaks_pretty(3L)\n#' ) +\n#' coord_cartesian(clip = \"off\")\n#'\n#' @export\ngeom_rect3d <- function(mapping = NULL, data = NULL, stat = \"identity\",\n position = \"identity\", ...,\n lineend = \"butt\", linejoin = \"round\", linemitre = 10,\n na.rm = FALSE, show.legend = NA, inherit.aes = TRUE) {\n ggplot2::layer(\n data = data,\n mapping = mapping,\n stat = stat,\n geom = GeomRect3d,\n position = position,\n show.legend = show.legend,\n inherit.aes = inherit.aes,\n params = list(\n lineend = lineend,\n linejoin = linejoin,\n linemitre = linemitre,\n na.rm = na.rm, ...\n )\n )\n}\n\n#' @importFrom ggplot2 ggproto fill_alpha\nGeomRect3d <- ggproto(\n \"GeomRect3d\",\n ggplot2::GeomRect,\n required_aes = c(ggplot2::GeomRect$required_aes, \"z\"),\n non_missing_aes = c(ggplot2::GeomRect$non_missing_aes, \"z\", \"theta\"),\n setup_data = function(self, data, params) {\n theta <- data$theta %||% .subset2(params, \"theta\")\n if (!is.null(theta) && any(theta <= 0 || theta >= 90)) {\n cli_abort(\n \"value mapped to {.field theta} aesthetic must > 0 and < 90.\"\n )\n }\n data$theta <- theta %||% 60\n ggproto_parent(ggplot2::GeomRect, self)$setup_data(data, params)\n },\n draw_panel = function(self, data, panel_params, coord, lineend = \"butt\",\n linejoin = \"round\", linemitre = 10) {\n data <- setup_3d_data(data)\n # Transform to viewport coords\n coords <- coord$transform(data, panel_params)\n\n # collapse the gpar value\n data <- .subset2(\n vec_split(\n data[setdiff(names(data), c(\"x\", \"y\", \"width\", \"height\"))],\n .subset2(data, \"polygon_id\")\n ),\n \"val\"\n )\n data <- vec_rbind(!!!lapply(data, vec_unique))\n\n # Draw as grob\n grid::polygonGrob(\n x = coords$x,\n y = coords$y,\n id = coords$polygon_id,\n default.units = \"native\",\n gp = gpar(\n col = data$colour,\n fill = fill_alpha(data$fill, data$alpha),\n lwd = data$linewidth,\n lty = data$linetype,\n lineend = lineend,\n linejoin = linejoin,\n linemitre = linemitre\n )\n )\n }\n)\n\nsetup_3d_data <- function(data) {\n data <- vec_slice(\n data,\n order(\n .subset2(data, \"xmin\"),\n .subset2(data, \"ymin\"),\n decreasing = TRUE\n )\n )\n coords <- .mapply(\n function(xmin, xmax, ymin, ymax, z, theta, ...) {\n if (z == 0L) {\n # fallback to tile\n data_frame0(\n x = vec_c(xmin, xmax, xmax, xmin),\n y = vec_rep_each(c(ymin, ymax), 2L)\n )\n } else {\n offset_x <- z * cos(theta / 180 * pi)\n z_xmin <- xmin + offset_x\n z_xmax <- xmax + offset_x\n offset_y <- z * sin(theta / 180 * pi)\n z_ymin <- ymin + offset_y\n z_ymax <- ymax + offset_y\n data_frame0(\n x = vec_c(\n xmin, z_xmin, z_xmax, xmax, xmin, xmin,\n z_xmin, z_xmin, z_xmin, z_xmax, z_xmax, z_xmin\n ),\n y = vec_c(\n ymin, z_ymin, z_ymin, ymin, ymin, ymax,\n z_ymax, z_ymin, z_ymax, z_ymax, z_ymin, z_ymin\n )\n )\n }\n },\n data,\n MoreArgs = NULL\n )\n vec_cbind(\n vec_rbind(!!!coords),\n vec_rep_each(\n data[\n vec_set_difference(\n names(data),\n c(\"x\", \"xmin\", \"xmax\", \"y\", \"ymin\", \"ymax\", \"z\")\n )\n ],\n list_sizes(coords)\n ),\n polygon_id = vec_rep_each(seq_along(coords), list_sizes(coords))\n )\n}\n\n#' @aesthetics GeomTile3d\n#' @importFrom rlang list2\n#' @export\n#' @rdname geom_rect3d\ngeom_tile3d <- function(mapping = NULL, data = NULL, stat = \"identity\",\n position = \"identity\", ...,\n lineend = \"butt\", linejoin = \"round\", linemitre = 10,\n na.rm = FALSE, show.legend = NA, inherit.aes = TRUE) {\n ggplot2::layer(\n data = data,\n mapping = mapping,\n stat = stat,\n geom = GeomTile3d,\n position = position,\n show.legend = show.legend,\n inherit.aes = inherit.aes,\n params = list(\n lineend = lineend,\n linejoin = linejoin,\n linemitre = linemitre,\n na.rm = na.rm, ...\n )\n )\n}\n\n#' @importFrom ggplot2 ggproto ggproto_parent\nGeomTile3d <- ggproto(\n \"GeomTile3d\",\n ggplot2::GeomTile,\n required_aes = c(ggplot2::GeomTile$required_aes, \"z\"),\n non_missing_aes = c(ggplot2::GeomTile$non_missing_aes, \"z\", \"theta\"),\n setup_data = function(self, data, params) {\n theta <- data$theta %||% .subset2(params, \"theta\")\n if (!is.null(theta) && any(theta <= 0 || theta >= 90)) {\n cli_abort(\n \"value mapped to {.field theta} aesthetic must > 0 and < 90.\"\n )\n }\n data$theta <- theta %||% 60\n ggproto_parent(ggplot2::GeomTile, self)$setup_data(data, params)\n },\n draw_panel = function(self, data, panel_params, coord, lineend = \"butt\",\n linejoin = \"round\", linemitre = 10) {\n ggproto_parent(GeomRect3d, self)$draw_panel(\n data = data, panel_params = panel_params, coord = coord,\n lineend = lineend, linejoin = linejoin, linemitre = linemitre\n )\n }\n)\n\n#' z scales\n#'\n#' @param ... Other arguments passed on to\n#' [`continuous_scale()`][ggplot2::continuous_scale],\n#' [`binned_scale()`][ggplot2::binned_scale], or\n#' [`discrete_scale()`][ggplot2::discrete_scale] as appropriate, to control\n#' name, limits, breaks, labels and so forth.\n#' @param range Output range of z values. Must larger than 0.\n#' @inheritParams ggplot2::continuous_scale\n#' @seealso [`geom_tile3d()`]/[`geom_rect3d()`]\n#' @export\n#' @examples\n#'\n#' set.seed(7)\n#' mat <- matrix(runif(100), 10)\n#' rownames(mat) <- LETTERS[1:10]\n#' colnames(mat) <- letters[1:10]\n#' ggheatmap(mat,\n#' filling = FALSE,\n#' theme = theme(\n#' legend.box.spacing = unit(10, \"mm\"),\n#' plot.margin = margin(t = 15, unit = \"mm\")\n#' )\n#' ) +\n#' geom_tile3d(aes(fill = value, z = value, width = 0.8, height = 0.8)) +\n#' scale_z_continuous(range = c(0.2, 1)) +\n#' coord_cartesian(clip = \"off\")\n#' @export\nscale_z_continuous <- function(name = waiver(), ..., range = c(0.1, 1),\n guide = \"none\") {\n if (min(range) < 0) {\n cli_abort(\"{.arg range} must contain only positive values\")\n }\n ggplot2::continuous_scale(\"z\",\n name = name, palette = scales::pal_rescale(range), ...,\n guide = guide\n )\n}\n\n#' @rdname scale_z_continuous\n#' @export\nscale_z_binned <- function(name = waiver(), ..., range = c(0.1, 1),\n guide = \"none\") {\n if (min(range) < 0) {\n cli_abort(\"{.arg range} must contain only positive values\")\n }\n ggplot2::binned_scale(\"z\",\n name = name, palette = scales::pal_rescale(range), ...,\n guide = guide\n )\n}\n\n#' @rdname scale_z_continuous\n#' @export\nscale_z_discrete <- function(...) {\n cli_warn(\"Using {z} for a discrete variable is not advised.\")\n args <- list2(...)\n args$call <- args$call %||% current_call()\n rlang::exec(scale_z_ordinal, !!!args)\n}\n\n#' @rdname scale_z_continuous\n#' @export\nscale_z_ordinal <- function(name = waiver(), ..., range = c(0.1, 1),\n guide = \"none\") {\n if (min(range) < 0) {\n cli_abort(\"{.arg range} must contain only positive values\")\n }\n ggplot2::discrete_scale(\n \"z\",\n name = name,\n palette = function(n) seq(range[1], range[2], length.out = n),\n ...,\n gudie = guide\n )\n}\n\n#' @rdname scale_z_continuous\n#' @export\n#' @usage NULL\nscale_z_datetime <- function(name = waiver(), ..., range = c(0.1, 1),\n guide = \"none\") {\n if (min(range) < 0) {\n cli_abort(\"{.arg range} must contain only positive values\")\n }\n ggplot2::datetime_scale(\n aesthetics = \"z\", transform = \"time\", name = name,\n palette = scales::pal_rescale(range),\n ..., guide = guide\n )\n}\n\n#' @rdname scale_z_continuous\n#' @export\n#' @usage NULL\nscale_z_date <- function(name = waiver(), ..., range = c(0.1, 1),\n guide = \"none\") {\n if (min(range) < 0) {\n cli_abort(\"{.arg range} must contain only positive values\")\n }\n ggplot2::datetime_scale(\n aesthetics = \"z\", transform = \"date\", name = name,\n palette = scales::pal_rescale(range),\n ..., guide = guide\n )\n}\n"], ["/ggalign/R/import-standalone-pkg.R", "# Standalone file: do not edit by hand\n# Source: https://github.com/Yunuuuu/standalone/blob/HEAD/R/standalone-pkg.R\n# Generated by: usethis::use_standalone(\"Yunuuuu/standalone\", \"pkg\")\n# ----------------------------------------------------------------------\n#\n# ---\n# repo: Yunuuuu/standalone\n# file: standalone-pkg.R\n# last-updated: 2025-04-10\n# license: https://unlicense.org\n# imports: [utils]\n# ---\n\n# This file contains various helper utilities, including common functions\n# used across multiple packages I have developed. Some functions depend on\n# other packages that are not listed in Imports, so use them with caution.\n\n# ## Changelog\n# 2025-04-10\n# - simplify `from_namespace`\n#\n# 2025-03-30\n# - Add `use_github_release`\n#\n# 2025-03-12\n# - Add `from_namespace`\n#\n# 2025-03-10:\n# - Add `on_exit`\n#\n# 2025-03-08:\n# - Add `pkg_extdata`\n# - Add `defer`\n#\n# 2025-03-04:\n# - Add `%||%`\n#\n# 2025-03-03:\n# - Add `rd_collect_family`\n# - Add `oxford_and`\n# - Add `oxford_or`\n# - Add `code_quote`\n# - Add `oxford_comma`\n#\n# 2025-02-26:\n# - Add `is_installed`\n# - Add `install_pkgs`\n# - Add `pkg_nm`\n# - Add `pkg_namespace`\n#\n# nocov start\n\n`%||%` <- function(x, y) if (is.null(x)) y else x\n\nis_installed <- local({\n cache <- new.env(parent = emptyenv())\n function(pkg, version = NULL) {\n id <- if (is.null(version)) pkg else paste(pkg, version, sep = \":\")\n out <- cache[[id]]\n if (is.null(out)) {\n if (is.null(version)) {\n out <- requireNamespace(pkg, quietly = TRUE)\n } else {\n out <- requireNamespace(pkg, quietly = TRUE) &&\n utils::packageVersion(pkg) >= version\n }\n assign(id, out, envir = cache, inherits = FALSE)\n }\n out\n }\n})\n\ninstall_pkgs <- function(pkgs) {\n if (is_installed(\"pak\")) {\n getExportedValue(\"pak\", \"pkg_install\")(pkgs, ask = FALSE)\n } else {\n utils::install.packages(pkgs)\n }\n}\n\npkg_nm <- function() utils::packageName(environment())\n\npkg_namespace <- function() topenv(environment())\n\npkg_extdata <- function(..., mustWork = TRUE) {\n system.file(\"extdata\", ..., package = pkg_nm(), mustWork = mustWork)\n}\n\n############################################################\n# I’m having trouble connecting to GitHub, and it seems that `gert` does not\n# respect the proxy settings in my Git config. To work around this, I modified\n# `usethis::use_github_release()` to skip the check that relies on the `gert`\n# package.\nuse_github_release <- function(publish = TRUE) {\n usethis_ns <- getNamespace(\"usethis\")\n usethis <- function(fun, ...) {\n get(x = fun, envir = usethis_ns, inherits = FALSE, ...)\n }\n usethis(\"check_is_package\")(\"use_github_release()\")\n tr <- usethis(\"target_repo\")(\n github_get = TRUE,\n ok_configs = c(\"ours\", \"fork\")\n )\n usethis(\"check_can_push\")(tr = tr, \"to create a release\")\n dat <- usethis(\"get_release_data\")(tr)\n release_name <- paste(dat$Package, dat$Version)\n tag_name <- sprintf(\"v%s\", dat$Version)\n usethis(\"kv_line\")(\"Release name\", release_name)\n usethis(\"kv_line\")(\"Tag name\", tag_name)\n usethis(\"kv_line\")(\"SHA\", dat$SHA)\n usethis(\"check_github_has_SHA\")(SHA = dat$SHA, tr = tr)\n on_cran <- !is.null(usethis(\"cran_version\")())\n news <- usethis(\"get_release_news\")(\n SHA = dat$SHA, tr = tr, on_cran = on_cran\n )\n gh <- usethis(\"gh_tr\")(tr)\n usethis(\"ui_bullets\")(\"Publishing {tag_name} release to GitHub\")\n release <- gh( # nolint\n \"POST /repos/{owner}/{repo}/releases\",\n name = release_name,\n tag_name = tag_name,\n target_commitish = dat$SHA,\n body = news,\n draft = !publish\n )\n usethis(\"ui_bullets\")(\"Release at {.url {release$html_url}}\")\n if (!is.null(dat$file)) {\n usethis(\"ui_bullets\")(\"Deleting {.path {dat$file}}\")\n getExportedValue(\"fs\", \"file_delete\")(dat$file)\n }\n invisible()\n}\n\n############################################################\nfrom_namespace <- local({\n namespace <- NULL\n function(package, name, mode = \"any\") {\n if (is.null(namespace)) namespace <<- getNamespace(package)\n get(x = name, envir = namespace, inherits = FALSE, mode = mode)\n }\n})\n\n# Need `rlang` package, can support `quosure`\non_exit <- function(expr, envir = parent.frame(), after = TRUE, add = TRUE) {\n expr <- getExportedValue(\"rlang\", \"enquo\")(expr)\n defer(\n getExportedValue(\"rlang\", \"eval_tidy\")(expr),\n envir = envir,\n after = after,\n add\n )\n}\n\n# Just like `withr::defer()`, don't depend on `rlang` package\ndefer <- function(expr, envir = parent.frame(), after = TRUE, add = TRUE) {\n thunk <- as.call(list(function() expr))\n do.call(base::on.exit, list(thunk, add = add, after = after), envir = envir)\n}\n\n# utils function to collapse characters ---------------------------\noxford_and <- function(x, code = TRUE, quote = TRUE, sep = \", \") {\n oxford_comma(code_quote(x, code, quote), sep = sep, final = \"and\")\n}\n\noxford_or <- function(x, code = TRUE, quote = TRUE, sep = \", \") {\n oxford_comma(code_quote(x, code, quote), sep = sep, final = \"or\")\n}\n\ncode_quote <- function(x, code = TRUE, quote = TRUE) {\n if (quote) x <- paste0(\"\\\"\", x, \"\\\"\")\n if (code) x <- paste0(\"`\", x, \"`\")\n x\n}\n\noxford_comma <- function(x, sep = \", \", final = \"and\") {\n n <- length(x)\n\n if (n < 2L) return(x) # styler: off\n\n head <- x[seq_len(n - 1L)]\n last <- x[n]\n\n head <- paste(head, collapse = sep)\n\n # Write a or b. But a, b, or c.\n if (n > 2L) {\n paste0(head, sep, final, \" \", last)\n } else {\n paste0(head, \" \", final, \" \", last)\n }\n}\n\n# Need `roxygen2` package\n#' @description add `@eval rd_collect_family(\"myfamily\")` to the functions in\n#' your package. This will automatically generate a section listing all\n#' functions tagged with `@family myfamily`.\n#' @param family A string specifying the family name.\n#' @param section_title A string specifying the section title.\n#' @param code_style A boolean indicating whether to apply code formatting\n#' to function names.\n#' @noRd\nrd_collect_family <- function(\n family,\n section_title = paste(family, \"family\"),\n code_style = TRUE) {\n # get blocks objects from the roxygenize function\n blocks <- NULL\n pos <- sys.nframe()\n while (pos > 0L) {\n if (!is.null(call <- sys.call(-pos))) {\n fn <- eval(.subset2(call, 1L), sys.frame(-(pos + 1L)))\n env <- sys.frame(-pos)\n if (\n identical(fn, getExportedValue(\"roxygen2\", \"roxygenize\")) &&\n exists(\"blocks\", envir = env, inherits = FALSE)\n ) {\n blocks <- get(\"blocks\", envir = env, inherits = FALSE)\n break\n }\n }\n pos <- pos - 1L\n }\n\n # identify the blocks with family of the same tag specified in `family`\n blocks <- blocks[\n vapply(\n blocks,\n function(block) {\n getExportedValue(\"roxygen2\", \"block_has_tags\")(\n block,\n \"family\"\n ) &&\n identical(\n getExportedValue(\"roxygen2\", \"block_get_tag_value\")(\n block,\n \"family\"\n ),\n family\n )\n },\n logical(1L),\n USE.NAMES = FALSE\n )\n ]\n if (length(blocks) == 0L) return(character()) # styler: off\n\n # extracted the function name\n funs <- vapply(\n blocks,\n function(block) {\n as.character(.subset2(block$call, 2L))\n },\n character(1L),\n USE.NAMES = FALSE\n )\n if (code_style) {\n items <- sprintf(\"\\\\code{\\\\link[=%s]{%s()}}\", funs, funs)\n } else {\n items <- sprintf(\"\\\\link[=%s]{%s()}\", funs, funs)\n }\n c(\n sprintf(\"@section %s:\", section_title),\n \"\\\\itemize{\",\n sprintf(\" \\\\item %s\", items),\n \"}\"\n )\n}\n\n# nocov end\n"], ["/ggalign/R/layout-chain-circle-switch.R", "#########################################################\n#' Determine the active context of circle layout\n#'\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' @inheritParams rlang::args_dots_empty\n#' @inheritParams circle_discrete\n#' @param what What should get activated for the [`circle_layout()`]?\n#' `r rd_chain_what()`.\n#' @return A `circle_switch` object which can be added to [`circle_layout()`].\n#' @examples\n#' set.seed(123)\n#' small_mat <- matrix(rnorm(56), nrow = 7)\n#' rownames(small_mat) <- paste0(\"row\", seq_len(nrow(small_mat)))\n#' colnames(small_mat) <- paste0(\"column\", seq_len(ncol(small_mat)))\n#' circle_discrete(small_mat) +\n#' ggalign() +\n#' geom_tile(aes(y = .column_index, fill = value)) +\n#' scale_fill_viridis_c() +\n#' align_dendro(aes(color = branch), k = 3L) +\n#' scale_color_brewer(palette = \"Dark2\")\n#' @export\ncircle_switch <- function(radial = waiver(), direction = NULL,\n what = waiver(), ...) {\n rlang::check_dots_empty()\n if (!is.waive(radial) && !is.null(radial)) {\n assert_s3_class(radial, \"CoordRadial\")\n if (abs(diff(radial$arc)) < pi / 2L) {\n cli_abort(\"Cannot use circle of acute angle < 90 in {.arg radial}\")\n }\n }\n if (!is.null(direction)) {\n direction <- arg_match0(direction, c(\"inward\", \"outward\"))\n }\n if (!is.waive(what)) what <- check_stack_context(what)\n structure(list(what = what, radial = radial, direction = direction),\n class = \"circle_switch\"\n )\n}\n"], ["/ggalign/R/ggplot-geom-pie.R", "#' Pie charts\n#' @section new aesthetics:\n#' - `angle`: the pie circle angle.\n#' - `angle0`: the initial pie circle angle.\n#' - `radius`: the circle radius.\n#' @inheritParams ggplot2::layer\n#' @inheritParams ggplot2::geom_polygon\n#' @inheritParams ggplot2::geom_path\n#' @param steps An integer indicating the number of steps to generate the pie\n#' chart radian. Increasing this value results in a smoother pie circular.\n#' @param clockwise A single boolean value indicates clockwise or not.\n#' @aesthetics GeomPie\n#' @examples\n#' ggplot(data.frame(x = 1:10, y = 1:10, value = 1:10 / sum(1:10))) +\n#' geom_pie(aes(x, y, angle = value * 360))\n#' @export\ngeom_pie <- function(mapping = NULL, data = NULL, stat = \"identity\",\n position = \"identity\", ...,\n clockwise = TRUE, steps = 100,\n lineend = \"butt\", linejoin = \"round\", linemitre = 10,\n na.rm = FALSE,\n show.legend = NA, inherit.aes = TRUE) {\n ggplot2::layer(\n data = data,\n mapping = mapping,\n stat = stat,\n geom = GeomPie,\n position = position,\n show.legend = show.legend,\n inherit.aes = inherit.aes,\n params = list(\n lineend = lineend,\n linejoin = linejoin,\n linemitre = linemitre,\n clockwise = clockwise,\n na.rm = na.rm, steps = steps, ...\n )\n )\n}\n\n#' @importFrom grid gpar\n#' @importFrom ggplot2 ggproto aes resolution fill_alpha\n#' @importFrom rlang set_names\nGeomPie <- ggproto(\"GeomPie\",\n ggplot2::GeomPolygon,\n default_aes = aes(\n !!!set_names(\n ggplot2::GeomPolygon$default_aes,\n function(nms) {\n nms <- set_names(nms)\n vec_slice(nms, \"subgroup\") <- \"radius\"\n nms\n }\n ),\n angle0 = 0\n ),\n non_missing_aes = c(\"x\", \"y\", \"angle\", \"angle0\", \"radius\"),\n required_aes = c(\"x\", \"y\", \"angle\"),\n handle_na = ggplot2::Geom$handle_na,\n setup_params = function(self, data, params) {\n steps <- vec_cast(.subset2(params, \"steps\"), integer(),\n x_arg = \"steps\",\n call = call(snake_class(self))\n )\n assert_bool(.subset2(params, \"clockwise\"),\n arg = \"clockwise\", call = call(snake_class(self))\n )\n params$steps <- max(steps, 1L) + 1L\n params\n },\n setup_data = function(data, params) {\n # use the same strategy of geom_bar\n data$radius <- data$radius %||%\n params$radius %||% (\n min(\n vapply(\n split(data$x, data$PANEL, drop = TRUE),\n resolution, numeric(1),\n zero = FALSE,\n USE.NAMES = FALSE\n ),\n vapply(\n split(data$y, data$PANEL, drop = TRUE),\n resolution, numeric(1),\n zero = FALSE,\n USE.NAMES = FALSE\n )\n ) * 0.45)\n data\n },\n draw_panel = function(data, panel_params, coord, steps = 100L,\n clockwise = TRUE, lineend = \"butt\",\n linejoin = \"round\", linemitre = 10) {\n # Expand x, y, radius data to points along circle\n circular_data <- .mapply(\n function(x, y, radius, ang, ang0) {\n if (clockwise) {\n ang0 <- 90 - ang0\n radians <- seq(ang0, ang0 - ang, length.out = steps)[-1L]\n } else {\n ang0 <- 90 + ang0\n radians <- seq(ang0, ang0 + ang, length.out = steps)[-1L]\n }\n radians <- radians / 180 * pi\n data_frame0(\n x = c(x, cos(radians) * radius + x),\n y = c(y, sin(radians) * radius + y)\n )\n },\n list(\n x = data$x, y = data$y,\n radius = data$radius, ang = data$angle, ang0 = data$angle0\n ),\n MoreArgs = NULL\n )\n circular_data <- vec_rbind(!!!circular_data)\n\n # Transform to viewport coords\n circular_data <- coord$transform(circular_data, panel_params)\n\n # Draw as grob\n grid::polygonGrob(\n x = circular_data$x,\n y = circular_data$y,\n id.lengths = rep_len(steps, nrow(data)),\n default.units = \"native\",\n gp = gpar(\n col = data$colour,\n fill = fill_alpha(data$fill, data$alpha),\n lwd = data$linewidth,\n lty = data$linetype,\n lineend = lineend,\n linejoin = linejoin,\n linemitre = linemitre\n )\n )\n }\n)\n"], ["/ggalign/R/layout-quad-build.R", "#' @importFrom grid unit.c\n#' @export\nggalign_build.QuadLayout <- function(x) {\n x <- default_layout(x)\n patches <- quad_build(x)\n plots <- .subset2(patches, \"plots\")\n sizes <- .subset2(patches, \"sizes\")\n design <- list(\n top = area(1, 2),\n left = area(2, 1),\n main = area(2, 2),\n bottom = area(3, 2),\n right = area(2, 3)\n )\n sizes <- imap(list(\n height = c(\"top\", \"main\", \"bottom\"),\n width = c(\"left\", \"main\", \"right\")\n ), function(x, name) {\n out <- .subset(sizes, x)\n out$main <- .subset2(.subset2(out, \"main\"), name)\n out <- .subset(\n out,\n !vapply(.subset(plots, x), is.null, logical(1L), USE.NAMES = FALSE)\n )\n do.call(unit.c, out)\n })\n keep <- !vapply(plots, is.null, logical(1L), USE.NAMES = FALSE)\n design <- trim_area(vec_c(!!!vec_set_names(vec_slice(design, keep), NULL)))\n titles <- x@titles\n align_plots(\n !!!.subset(plots, keep),\n design = design,\n heights = .subset2(sizes, \"height\"),\n widths = .subset2(sizes, \"width\"),\n guides = .subset2(.subset2(x@schemes, \"scheme_align\"), \"guides\"),\n theme = x@theme\n ) + layout_title(\n title = .subset2(titles, \"title\"),\n subtitle = .subset2(titles, \"subtitle\"),\n caption = .subset2(titles, \"caption\")\n )\n}\n\nquad_build <- function(quad, schemes = NULL, theme = NULL,\n direction = NULL) {\n UseMethod(\"quad_build\")\n}\n\n#######################################################################\n#' @param schemes,theme Parameters from parent layout\n#' @importFrom ggplot2 aes\n#' @importFrom rlang is_empty\n#' @importFrom grid unit is.unit unit.c\n#' @export\n#' @noRd\nquad_build.QuadLayout <- function(quad, schemes = NULL, theme = NULL,\n direction = NULL) {\n data <- quad@data\n row_design <- setup_design(quad@horizontal)\n column_design <- setup_design(quad@vertical)\n if (is.function(data)) {\n cli_abort(c(\n \"{.arg data} cannot be a {.cls function}\",\n i = sprintf(\n \"Did you want to add %s to a {.fn stack_layout}?\",\n object_name(quad)\n )\n ))\n }\n if (is_discrete_design(row_design) &&\n is.null(.subset2(row_design, \"nobs\"))) {\n cli_abort(sprintf(\n \"you must initialize %s before drawing the main plot\",\n object_name(quad),\n ))\n }\n if (is_discrete_design(column_design) &&\n is.null(.subset2(column_design, \"nobs\"))) {\n cli_abort(sprintf(\n \"you must initialize %s before drawing the main plot\",\n object_name(quad),\n ))\n }\n schemes <- inherit_parent_layout_schemes(quad, schemes)\n if (is.null(direction)) {\n spacing <- NULL\n } else if (is_horizontal(direction)) {\n spacing <- \"y\"\n } else {\n spacing <- \"x\"\n }\n theme <- inherit_parent_layout_theme(quad, theme, spacing = spacing)\n\n # prepare action for vertical and horizontal stack layout\n vertical_align <- horizontal_align <- the_align <-\n .subset2(schemes, \"scheme_align\")\n if (!is.null(layout_labs <- .subset2(the_align, \"free_labs\")) &&\n !is.waive(layout_labs)) {\n # prepare labs for child stack layout\n horizontal_align$free_labs <- gsub(\"[lr]\", \"\", layout_labs)\n vertical_align$free_labs <- gsub(\"[tb]\", \"\", layout_labs)\n if (!nzchar(horizontal_align$free_labs)) {\n horizontal_align[\"free_labs\"] <- list(NULL)\n }\n if (!nzchar(vertical_align$free_labs)) {\n vertical_align[\"free_labs\"] <- list(NULL)\n }\n }\n\n # inherit from the parent stack layout\n if (!is.null(layout_spaces <- .subset2(the_align, \"free_spaces\")) &&\n !is.waive(layout_spaces)) {\n horizontal_align$free_spaces <- gsub(\"[lr]\", \"\", layout_spaces)\n vertical_align$free_spaces <- gsub(\"[tb]\", \"\", layout_spaces)\n if (!nzchar(horizontal_align$free_spaces)) {\n horizontal_align[\"free_spaces\"] <- list(NULL)\n }\n if (!nzchar(vertical_align$free_spaces)) {\n vertical_align[\"free_spaces\"] <- list(NULL)\n }\n }\n\n # plot annotations ----------------------------\n stack_list <- lapply(.TLBR, function(position) {\n if (is_empty(stack <- slot(quad, position))) {\n return(list(plot = NULL, size = NULL))\n }\n pschemes <- schemes\n # inherit from horizontal align or vertical align\n if (is_horizontal(to_direction(position))) {\n extra_design <- column_design\n pschemes$scheme_align <- horizontal_align\n } else {\n extra_design <- row_design\n pschemes$scheme_align <- vertical_align\n }\n plot <- stack_build(\n stack,\n schemes = pschemes,\n theme = theme,\n extra_design = extra_design\n )\n if (is.null(plot)) {\n size <- NULL\n } else {\n size <- stack@sizes\n }\n list(plot = plot, size = size)\n })\n names(stack_list) <- .TLBR\n stack_list <- list_transpose(stack_list)\n plots <- .subset2(stack_list, 1L) # the annotation plot itself\n sizes <- .subset2(stack_list, 2L) # annotation size\n\n # read the plot ---------------------------------------\n p <- quad@plot\n\n # setup the facet -----------------------------------\n do_row_facet <- is_discrete_design(row_design) &&\n nlevels(.subset2(row_design, \"panel\")) > 1L\n do_column_facet <- is_discrete_design(column_design) &&\n nlevels(.subset2(column_design, \"panel\")) > 1L\n\n if (do_row_facet && do_column_facet) {\n default_facet <- ggplot2::facet_grid(\n rows = ggplot2::vars(.data$.panel_y),\n cols = ggplot2::vars(.data$.panel_x),\n scales = \"free\", space = \"free\",\n drop = FALSE, as.table = FALSE\n )\n free_row <- FALSE\n free_column <- FALSE\n } else if (do_row_facet) {\n default_facet <- ggplot2::facet_grid(\n rows = ggplot2::vars(.data$.panel_y),\n scales = \"free_y\", space = \"free\",\n drop = FALSE, as.table = FALSE\n )\n free_row <- FALSE\n free_column <- is_continuous_design(column_design)\n } else if (do_column_facet) {\n default_facet <- ggplot2::facet_grid(\n cols = ggplot2::vars(.data$.panel_x),\n scales = \"free_x\", space = \"free\",\n drop = FALSE, as.table = FALSE\n )\n free_row <- is_continuous_design(row_design)\n free_column <- FALSE\n } else {\n default_facet <- facet_quad(object_name(quad))\n free_row <- is_continuous_design(row_design)\n free_column <- is_continuous_design(column_design)\n }\n\n # set the facets and coord ---------------------------\n # we don't align observations for `quad_free()`\n # add default data ----------------------------------\n p <- gguse_data(p, quad_build_data(data, row_design, column_design))\n p <- gguse_linear_coord(p, object_name(quad))\n p <- ggmelt_facet(p, default_facet,\n free_row = free_row, free_column = free_column\n )\n p <- p +\n ggalign_design(\n x = column_design, y = row_design,\n xlabels = .subset(\n colnames(data),\n .subset2(column_design, \"index\")\n ),\n ylabels = .subset(\n vec_names(data),\n .subset2(row_design, \"index\")\n )\n )\n\n # add action ----------------------------------------\n p <- plot_add_schemes(p, inherit_schemes(quad@body_schemes, schemes))\n if (do_row_facet) {\n p <- p + theme(panel.spacing.y = calc_element(\"panel.spacing.y\", theme))\n }\n if (do_column_facet) {\n p <- p + theme(panel.spacing.x = calc_element(\"panel.spacing.x\", theme))\n }\n p <- p + theme_recycle()\n\n # collect all plots and sizes ----------------------\n plots <- append(plots, list(main = p), 2L)\n sizes <- append(\n sizes,\n list(main = list(width = quad@width, height = quad@height)),\n 3L\n )\n list(plots = plots, sizes = sizes)\n}\n\n#' @importFrom stats reorder\nquad_build_data <- function(data, row_design, column_design) {\n if (is.null(data) ||\n (is_continuous_design(row_design) &&\n is_continuous_design(column_design))) {\n return(data)\n }\n if (is_discrete_design(row_design)) {\n row_panel <- .subset2(row_design, \"panel\")\n row_index <- .subset2(row_design, \"index\")\n row_data <- data_frame0(\n .panel_y = row_panel,\n .index_y = row_index,\n .y = seq_along(row_index)\n )\n }\n if (is_discrete_design(column_design)) {\n column_panel <- .subset2(column_design, \"panel\")\n column_index <- .subset2(column_design, \"index\")\n column_data <- data_frame0(\n .panel_x = column_panel,\n .index_x = column_index,\n .x = seq_along(column_index)\n )\n }\n if (is_discrete_design(row_design) && is_discrete_design(column_design)) {\n panel_data <- cross_join(row_data, column_data)\n by.x <- c(\".column_index\", \".row_index\")\n by.y <- c(\".index_x\", \".index_y\")\n } else if (is_discrete_design(column_design)) {\n panel_data <- column_data\n by.x <- \".column_index\"\n by.y <- \".index_x\"\n } else {\n panel_data <- row_data\n by.x <- \".row_index\"\n by.y <- \".index_y\"\n }\n ans <- fortify_data_frame.matrix(data)\n ans <- full_join(ans, panel_data, by.x = by.x, by.y = by.y)\n if (!is.null(.subset2(ans, \".row_names\")) &&\n is_discrete_design(row_design)) {\n ans$.discrete_y <- reorder(\n .subset2(ans, \".row_names\"),\n .subset2(ans, \".y\"),\n order = FALSE\n )\n }\n if (!is.null(.subset2(ans, \".column_names\")) &&\n is_discrete_design(column_design)) {\n ans$.discrete_x <- reorder(\n .subset2(ans, \".column_names\"),\n .subset2(ans, \".x\"),\n order = FALSE\n )\n }\n ggalign_data_restore(ans, data)\n}\n"], ["/ggalign/R/ggcross.R", "#' Connect two layout crosswise\n#'\n#' @description\n#' `ggcross` resets the layout ordering index of a [`stack_cross()`]. This\n#' allows you to add other `align_*` objects to define a new layout ordering\n#' index. Any objects added after `ggcross` will use this updated layout\n#' ordering index. This feature is particularly useful for creating `tanglegram`\n#' visualizations. `ggcross()` is an alias of `ggcross()`.\n#'\n#' @inheritParams ggalign\n#' @section ggplot2 specification:\n#' `ggcross()` initializes a ggplot `data` and `mapping`.\n#'\n#' `ggcross()` always applies a default mapping for the axis of the data index\n#' in the layout. This mapping is `aes(y = .data$.y)` for horizontal stack\n#' layout (including left and right annotation) and `aes(x = .data$.x)` for\n#' vertical stack layout (including top and bottom annotation).\n#'\n#' The data in the underlying `ggplot` object will contain following columns:\n#'\n#' - `.panel`: The panel for the aligned axis. Refers to the `x-axis` for\n#' vertical `stack_layout()` (including top and bottom annotations), and the\n#' `y-axis` for horizontal `stack_layout()` (including left and right\n#' annotations).\n#'\n#' - `.names` ([`vec_names()`][vctrs::vec_names]) and `.index`\n#' ([`vec_size()`][vctrs::vec_size()]/[`NROW()`]): Character names (if\n#' available) and the integer index of the original data.\n#'\n#' - `.hand`: a factor indicates the index groups.\n#'\n#' - `.x`/`.y` and `.discrete_x`/`.discrete_y`: Integer indices for `x`/`y`\n#' coordinates, and a factor of the data labels (only applicable when names\n#' exist).\n#'\n#' It is recommended to use `.x`/`.y`, or `.discrete_x`/`.discrete_y` as the\n#' `x`/`y` mapping.\n#'\n#' @importFrom ggplot2 ggplot aes\n#' @export\nggcross <- function(mapping = aes(), size = NULL,\n no_axes = NULL, active = NULL) {\n active <- update_active(active, new_active(use = TRUE))\n no_axes <- no_axes %||%\n getOption(sprintf(\"%s.align_no_axes\", pkg_nm()), default = TRUE)\n cross(\n CrossGg,\n plot = ggplot(mapping = mapping),\n schemes = default_schemes(th = theme_no_strip()),\n size = size, no_axes = no_axes, active = active\n )\n}\n\n#' @importFrom ggplot2 ggproto\nCrossGg <- ggproto(\"CrossGg\", \n CraftCross,\n interact_layout = function(self, layout) {\n if (!is_cross_layout(layout)) {\n cli_abort(c(\n sprintf(\n \"Cannot add %s to %s\",\n object_name(self), self$layout_name\n ),\n i = sprintf(\n \"%s can only be used in {.fn stack_cross}\",\n object_name(self)\n )\n ))\n }\n\n # udpate cross_points\n layout@cross_points <- c(layout@cross_points, length(layout@plot_list))\n\n # update old design list\n layout@odesign <- c(layout@odesign, list(layout@design))\n\n # we keep the names from the layout data for usage\n self$labels <- vec_names(layout@data)\n layout\n },\n setup_design = function(self, design) {\n design[\"index\"] <- list(NULL) # always reset the index\n design\n },\n setup_plot = function(self, plot) {\n ggadd_default(plot, mapping = switch_direction(\n self$direction, aes(y = .data$.y), aes(x = .data$.x)\n ))\n },\n #' @importFrom stats reorder\n build_plot = function(self, plot, design, extra_design = NULL,\n previous_design = NULL) {\n if (is.null(.subset2(design, \"nobs\"))) {\n cli_abort(sprintf(\n \"you must initialize %s before drawing %s\",\n self$layout_name, object_name(self)\n ), call = self$call)\n }\n direction <- self$direction\n index <- vec_c(\n .subset2(previous_design, \"index\"),\n .subset2(design, \"index\")\n )\n data <- data_frame0(\n .panel = vec_c(\n .subset2(previous_design, \"panel\"),\n .subset2(design, \"panel\")\n ),\n .index = index,\n # ggcross() only reset ordering index, labels should be the same\n .names = .subset(self$labels, index),\n .hand = if (is_horizontal(direction)) {\n factor(\n vec_rep_each(\n c(\"left\", \"right\"),\n c(\n .subset2(previous_design, \"nobs\"),\n .subset2(design, \"nobs\")\n )\n ),\n c(\"left\", \"right\")\n )\n } else {\n factor(\n vec_rep_each(\n c(\"top\", \"bottom\"),\n c(\n .subset2(previous_design, \"nobs\"),\n .subset2(design, \"nobs\")\n )\n ),\n c(\"bottom\", \"top\")\n )\n }\n )\n axis <- to_coord_axis(direction)\n coord_name <- paste0(\".\", axis)\n data[[coord_name]] <- vec_c(\n seq_len(.subset2(previous_design, \"nobs\")),\n seq_len(.subset2(design, \"nobs\"))\n )\n if (!is.null(.subset2(data, \".names\"))) {\n data[[paste0(\".discrete_\", axis)]] <- reorder(\n .subset2(data, \".names\"),\n .subset2(data, coord_name),\n order = FALSE\n )\n }\n plot <- gguse_data(plot, data)\n plot + switch_direction(\n direction,\n default_expansion(x = expansion()),\n default_expansion(y = expansion())\n )\n },\n finish_plot = function(self, plot, schemes, theme) {\n direction <- self$direction\n # remove axis titles, text, ticks used for alignment\n if (isTRUE(self$no_axes)) {\n schemes$scheme_theme <- .subset2(schemes, \"scheme_theme\") +\n theme_no_axes(switch_direction(direction, \"y\", \"x\"))\n }\n plot <- plot_add_schemes(plot, schemes)\n if (is_horizontal(direction)) {\n theme <- theme(\n panel.spacing.y = calc_element(\"panel.spacing.y\", theme)\n )\n } else {\n theme <- theme(\n panel.spacing.x = calc_element(\"panel.spacing.x\", theme)\n )\n }\n plot <- plot + theme\n ggremove_margin(plot, direction) + theme_recycle()\n },\n summary = function(self, plot) {\n header <- ggproto_parent(Craftsman, self)$summary(plot)\n c(header, \" Reset the ordering index and Add plot\")\n }\n)\n"], ["/ggalign/R/alignpatch-title.R", "#' Add patch titles to plot borders\n#'\n#' This function extends ggplot2's title functionality, allowing you to add\n#' titles to each border of the plot: top, left, bottom, and right.\n#'\n#' @details\n#'\n#' The appearance and alignment of these patch titles can be customized using\n#' [theme()][ggplot2::theme]:\n#' - `plot.patch_title`/`plot.patch_title.*`: Controls the text appearance of\n#' patch titles. By default, `plot.patch_title` inherit from `plot.title`, and\n#' settings for each border will inherit from `plot.patch_title`, with the\n#' exception of the `angle` property, which is not inherited.\n#' - `plot.patch_title.position`/`plot.patch_title.position.*`: Determines the\n#' alignment of the patch titles. By default, `plot.patch_title.position`\n#' inherit from `plot.title.position`, and settings for each border will\n#' inherit from `plot.patch_title`. The value `\"panel\"` aligns the patch\n#' titles with the plot panels. Setting this to `\"plot\"` aligns the patch\n#' title with the entire plot (excluding margins and plot tags).\n#'\n#' @param top,left,bottom,right A string specifying the title to be added to the\n#' top, left, bottom, and right border of the plot.\n#' @return A [`labels`][ggplot2::labs] object to be added to ggplot.\n#' @examples\n#' ggplot(mtcars) +\n#' geom_point(aes(mpg, disp)) +\n#' patch_titles(\n#' top = \"I'm top patch title\",\n#' left = \"I'm left patch title\",\n#' bottom = \"I'm bottom patch title\",\n#' right = \"I'm right patch title\"\n#' )\n#' @export\n#' @importFrom ggplot2 waiver\npatch_titles <- function(top = waiver(), left = waiver(), bottom = waiver(),\n right = waiver()) {\n structure(\n list(top = top, left = left, bottom = bottom, right = right),\n class = \"ggalign_patch_labels\"\n )\n}\n\n#' @importFrom ggplot2 find_panel calc_element zeroGrob element_grob merge_element\n#' @importFrom rlang arg_match0\n#' @importFrom grid grobName\nsetup_patch_titles <- function(table, patch_titles, theme) {\n # complete_theme() will ensure `plot_title` exists\n old_text <- calc_element(\"plot.title\", theme)\n # always justification by center for patch title\n old_text$hjust <- 0.5\n if (is.null(text <- .subset2(theme, \"plot.patch_title\"))) {\n text <- old_text\n } else if (inherits(text, \"element_text\")) {\n text <- merge_element(text, old_text)\n } else {\n cli_abort(paste(\n \"Theme element {.var plot.patch_title} must be a\",\n \"{.cls element_text}.\"\n ), call = quote(theme()))\n }\n # inherit from plot.title.position, default use \"panel\"\n position <- .subset2(theme, \"plot.patch_title.position\") %||%\n .subset2(theme, \"plot.title.position\") %||% \"panel\"\n for (border in .TLBR) {\n panel_pos <- find_panel(table)\n patch_title <- .subset2(patch_titles, border)\n name <- paste(\"plot.patch_title\", border, sep = \".\")\n if (is.null(patch_title)) {\n title <- zeroGrob()\n } else {\n # set the default angle\n text$angle <- switch(border,\n top = 0L,\n left = 90L,\n bottom = 0L,\n right = -90L\n )\n # we merge the element with `plot.patch_title`\n if (is.null(el <- .subset2(theme, name))) {\n el <- text\n } else if (inherits(el, \"element_text\")) {\n el <- merge_element(el, text)\n } else {\n cli_abort(paste(\n \"Theme element {.var {name}} must have\",\n \"class {.cls element_text}.\"\n ), call = quote(theme()))\n }\n # render the patch title grob\n title <- element_grob(el, patch_title,\n margin_y = TRUE, margin_x = TRUE\n )\n title$name <- grobName(title, name)\n }\n\n name <- paste(\"plot.patch_title.position\", border, sep = \".\")\n pos <- arg_match0(\n .subset2(theme, name) %||% position,\n c(\"panel\", \"plot\"),\n arg_nm = name,\n error_call = quote(theme())\n )\n if (border == \"top\") {\n height <- grobHeight(title)\n if (pos == \"panel\") {\n l <- panel_pos$l\n r <- panel_pos$r\n } else {\n l <- 1L\n r <- ncol(table)\n }\n h <- .subset2(panel_pos, \"t\") - 4L # above original xlab\n table <- gtable_add_rows(table, height, pos = h)\n table <- gtable_add_grob(table, title,\n name = \"patch-title-top\",\n t = h + 1L, b = h + 1L, l = l, r = r,\n clip = \"off\"\n )\n } else if (border == \"left\") {\n width <- grobWidth(title)\n if (pos == \"panel\") {\n t <- panel_pos$t\n b <- panel_pos$b\n } else {\n t <- 1L\n b <- nrow(table)\n }\n v <- .subset2(panel_pos, \"l\") - 4L # left of the ylab\n table <- gtable_add_cols(table, width, pos = v)\n table <- gtable_add_grob(table, title,\n name = \"patch-title-left\",\n t = t, b = b, l = v + 1L, r = v + 1L,\n clip = \"off\"\n )\n } else if (border == \"bottom\") {\n height <- grobHeight(title)\n if (pos == \"panel\") {\n l <- panel_pos$l\n r <- panel_pos$r\n } else {\n l <- 1L\n r <- ncol(table)\n }\n h <- .subset2(panel_pos, \"b\") + 3L # below original xlab\n table <- gtable_add_rows(table, height, pos = h)\n table <- gtable_add_grob(table, title,\n name = \"patch-title-bottom\",\n t = h + 1L, b = h + 1L, l = l, r = r,\n clip = \"off\"\n )\n } else if (border == \"right\") {\n width <- grobWidth(title)\n if (pos == \"panel\") {\n t <- panel_pos$t\n b <- panel_pos$b\n } else {\n t <- 1L\n b <- nrow(table)\n }\n v <- .subset2(panel_pos, \"r\") + 3L # right of the ylab\n table <- gtable_add_cols(table, width, pos = v)\n table <- gtable_add_grob(table, title,\n name = \"patch-title-right\",\n t = t, b = b, l = v + 1L, r = v + 1L,\n clip = \"off\"\n )\n }\n }\n table\n}\n\n#' @importFrom ggplot2 ggplot_add\n#' @export\nggplot_add.ggalign_patch_labels <- function(object, plot, object_name, ...) {\n plot$ggalign_patch_labels <- update_non_waive(\n plot$ggalign_patch_labels %||% list(), object\n )\n if (!inherits(plot, \"patch_ggplot\")) {\n plot <- add_class(plot, \"patch_ggplot\")\n }\n plot\n}\n"], ["/ggalign/R/layout-operator.R", "#' Layout operator\n#'\n#' @description\n#' `r lifecycle::badge('experimental')`\n#'\n#' - `+`: Adds elements to the active plot in the active layout.\n#' - `&`: Applies elements to all plots in the layout.\n#' - `-`: Adds elements to multiple plots in the layout.\n#'\n#' @details\n#' The `+` operator is straightforward and should be used as needed.\n#'\n#' In order to reduce code repetition `ggalign` provides two operators for\n#' adding ggplot elements (geoms, themes, facets, etc.) to multiple/all plots in\n#' `r rd_layout()`: `-` and `&`.\n#'\n#' @param e1 A `r rd_layout()`.\n#' @param e2 An object to be added to the plot.\n#' @return A modified `Layout` object.\n#' @examples\n#' set.seed(123)\n#' small_mat <- matrix(rnorm(56), nrow = 7)\n#' ggheatmap(small_mat) +\n#' anno_top() +\n#' ggalign() +\n#' geom_point(aes(y = value))\n#'\n#' # `&` operator apply it to all plots\n#' ggheatmap(small_mat) +\n#' anno_top() +\n#' align_dendro() &\n#' theme(panel.border = element_rect(\n#' colour = \"red\", fill = NA, linewidth = unit(2, \"mm\")\n#' ))\n#'\n#' # If the active layout is the annotation stack, the `-` operator will only\n#' # add the elements to all plots in the active annotation stack:\n#' ggheatmap(small_mat) +\n#' anno_left(size = 0.2) +\n#' align_dendro(aes(color = branch), k = 3L) +\n#' align_dendro(aes(color = branch), k = 3L) -\n#' # Modify the the color scales of all plots in the left annotation\n#' scale_color_brewer(palette = \"Dark2\")\n#'\n#' # If the active layout is the `stack_layout()` itself, `-`\n#' # applies the elements to all plots in the layout except the nested\n#' # `ggheatmap()`/`quad_layout()`.\n#' stack_alignv(small_mat) +\n#' align_dendro() +\n#' ggtitle(\"I'm from the parent stack\") +\n#' ggheatmap() +\n#' # remove any active context\n#' stack_active() +\n#' align_dendro() +\n#' ggtitle(\"I'm from the parent stack\") -\n#' # Modify the the color scales of all plots in the stack layout except the\n#' # heatmap layout\n#' scale_color_brewer(palette = \"Dark2\") -\n#' # set the background of all plots in the stack layout except the heatmap\n#' # layout\n#' theme(plot.background = element_rect(fill = \"red\"))\n#'\n#' @name layout-operator\nNULL\n\nutils::globalVariables(\".Generic\")\n\nmethods::setMethod(\"Ops\", c(\"LayoutProto\", \"ANY\"), function(e1, e2) {\n if (missing(e2)) {\n cli_abort(c(\n \"Cannot use {.code {.Generic}} with a single argument.\",\n \"i\" = \"Did you accidentally put {.code {.Generic}} on a new line?\"\n ))\n }\n\n if (is.null(e2)) return(e1) # styler: off\n\n # Get the name of what was passed in as e2, and pass along so that it\n # can be displayed in error messages\n e2name <- deparse(substitute(e2))\n switch(.Generic, # nolint\n `+` = layout_add(e1, e2, e2name),\n `-` = layout_subtract(e1, e2, e2name),\n `&` = layout_and_add(e1, e2, e2name),\n stop_incompatible_op(.Generic, e1, e2)\n )\n})\n\n#################################################################\nlayout_add <- function(layout, object, object_name) {\n UseMethod(\"layout_add\")\n}\n\n#' @export\nlayout_add.QuadLayout <- function(layout, object, object_name) {\n quad_layout_add(object, layout, object_name)\n}\n\n#' @export\nlayout_add.ChainLayout <- function(layout, object, object_name) {\n chain_layout_add(object, layout, object_name)\n}\n\n#################################################################\nlayout_subtract <- function(layout, object, object_name) {\n UseMethod(\"layout_subtract\")\n}\n\n#' @export\nlayout_subtract.QuadLayout <- function(layout, object, object_name) {\n quad_layout_subtract(object, layout, object_name)\n}\n\n#' @export\nlayout_subtract.ChainLayout <- function(layout, object, object_name) {\n chain_layout_subtract(object, layout, object_name)\n}\n\n#################################################################\n# we use and_add suffix here, since `and` is very similar with `add`.\nlayout_and_add <- function(layout, object, object_name) {\n UseMethod(\"layout_and_add\")\n}\n\n#' @export\nlayout_and_add.QuadLayout <- function(layout, object, object_name) {\n quad_layout_and_add(object, layout, object_name)\n}\n\n#' @export\nlayout_and_add.ChainLayout <- function(layout, object, object_name) {\n chain_layout_and_add(object, layout, object_name)\n}\n\n# For objects cannot be used with `-` or `&`\n#' @include layout-quad-operator.R\n#' @include layout-chain-operator.R\nlapply(\n c(\n \"quad_layout_subtract\", \"chain_layout_subtract\",\n \"quad_layout_and_add\", \"chain_layout_and_add\"\n ),\n function(genname) {\n params <- .subset2(strsplit(genname, \"_\"), 1L)\n\n # function argument list\n pairlist <- rlang::pairlist2(object = , layout = , object_name = )\n names(pairlist) <- c(\"object\", .subset(params, 1L), \"object_name\")\n operator <- switch(.subset(params, 3L),\n subtract = \"-\",\n and = \"&\"\n )\n # styler: off\n for (class in c(\"ggplot\", \"quad_active\", \"quad_anno\", \"layout_title\",\n \"layout_theme\", \"CraftBox\", \"ChainLayout\",\n \"QuadLayout\", \"continuous_limits\")) {\n # styler: on\n registerS3method(\n genname, class,\n rlang::new_function(pairlist, substitute(\n {\n cli_abort(c(\n sprintf(\n \"Cannot add %s with {.code %s}\",\n name, operator\n ),\n i = \"Try to use {.code +} instead\"\n ))\n },\n list(\n name = switch(class,\n CraftBox = ,\n ChainLayout = ,\n QuadLayout = quote(object_name(object)),\n # for all others\n \"{.var {object_name}}\"\n ),\n operator = operator\n )\n ))\n )\n }\n }\n)\n"], ["/ggalign/R/with_quad.R", "#' Modify operated Context in `quad_layout()`\n#'\n#' @description\n#' `r lifecycle::badge('experimental')`\n#'\n#' The `with_quad()` function modifies the application context of elements in\n#' `ggheatmap()`/`quad_layout()`. It controls how objects like themes, scales,\n#' or other plot modifications apply to specific annotation stacks or the main\n#' plot without altering the currently active layout or plot.\n#'\n#' @param x An object which can be added to the ggplot, including\n#' **schemes**. See [`scheme_align()`], [`scheme_data()`], and\n#' [`scheme_theme()`]\n#' @param position A string specifying one or more positions-\n#' `r oxford_and(.tlbr)`- to indicate the annotation stack context for `x`. If\n#' `NULL`, will change the operated context to the `quad_layout()` itself. For\n#' default behaivours, see `details` section.\n#' @param main A single boolean value indicating whether `x` should apply to the\n#' main plot, used only when `position` is not `NULL`. By default, if `position`\n#' is `waiver()` and the active context of `quad_layout()` is an annotation\n#' stack or the active context of `stack_layout()` is itself, `main` will be set\n#' to `TRUE`; otherwise, it defaults to `FALSE`.\n#' @return The original object with an added attribute that sets the specified\n#' context.\n#' @details\n#' Default Behavior when adding object wrapped with `with_quad()`:\n#'\n#' For `quad_layout()` object:\n#'\n#' - When `ggheatmap()`/`quad_layout()` has no active annotation stack, objects\n#' added via `+` or `-` operate normally without `with_quad()`.\n#' - When the active annotation stack is set, `with_quad()` ensures the applied\n#' object also modifies:\n#' * The main plot (by default).\n#' * Opposite annotation stacks when using `-`.\n#'\n#' For `stack_layout()` object:\n#'\n#' - When the active layout is the `stack_layout()` itself:\n#' * `-` operator will apply changes to all plots along the\n#' `stack_layout()`, which means if the stack layout is in `horizontal`,\n#' `-` operator will also add the element to the `left` and `right`\n#' annotation, if the stack layout is in `vertical`, `-` operator will\n#' also add element to the `top` and `bottom` annotation.\n#' * `+` operator won't do anything special.\n#' - When the active layout is the nested `ggheatmap()`/`quad_layout()`, the\n#' `+`/`-` operator applies the elements to this nested layout, following the\n#' same principles as for `ggheatmap()`/`quad_layout()`.\n#'\n#' @examples\n#' set.seed(123)\n#' small_mat <- matrix(rnorm(56), nrow = 7)\n#'\n#' # By wrapping object with `with_quad()`, the `+` operator will apply the\n#' # object not only to the active plot in the annotation stack, but also to\n#' # the main plot unless specified by `main` argument otherwise.\n#' ggheatmap(small_mat) +\n#' # initialize the left annotation\n#' anno_left(size = 0.2) +\n#' align_dendro() +\n#' # apply the object not only to the active plot in the annotation stack,\n#' # but also to the main plot\n#' with_quad(theme(plot.background = element_rect(fill = \"red\")))\n#'\n#' # the `-` operator will apply changes not only to the active annotation\n#' # stack but also to the opposite one (i.e., bottom if top is active, and\n#' # vice versa). The same principle applies to the left and right annotation.\n#' ggheatmap(small_mat) +\n#' anno_left(size = 0.2) +\n#' align_dendro(aes(color = branch), k = 3L) +\n#' # Change the active layout to the left annotation\n#' anno_top(size = 0.2) +\n#' align_dendro(aes(color = branch), k = 3L) +\n#' anno_bottom(size = 0.2) +\n#' align_dendro(aes(color = branch), k = 3L) -\n#' # Modify the color scale of all plots in the bottom and the opposite\n#' # annotation, in this way, the `main` argument by default would be `TRUE`\n#' with_quad(scale_color_brewer(palette = \"Dark2\", name = \"Top and bottom\"))\n#'\n#' # When the `position` argument is manually set, the\n#' # default value of the `main` argument will be `FALSE`.\n#' ggheatmap(small_mat) +\n#' anno_left(size = 0.2) +\n#' align_dendro(aes(color = branch), k = 3L) +\n#' anno_top(size = 0.2) +\n#' align_dendro(aes(color = branch), k = 3L) +\n#' anno_bottom(size = 0.2) +\n#' align_dendro(aes(color = branch), k = 3L) -\n#' # Modify the background of all plots in the left and top annotation\n#' with_quad(theme(plot.background = element_rect(fill = \"red\")), \"tl\")\n#' @export\nwith_quad <- function(x, position = waiver(), main = NULL) {\n UseMethod(\"with_quad\")\n}\n\n#' @export\nwith_quad.default <- function(x, position = waiver(), main = NULL) {\n assert_layout_position(position)\n assert_bool(main, allow_null = TRUE)\n structure(\n list(\n object = x,\n object_name = paste(deparse(substitute(x)), collapse = \" \"),\n position = position, main = main\n ),\n class = \"ggalign_with_quad\"\n )\n}\n\n#' @export\nprint.ggalign_with_quad <- function(x, ...) {\n print(.subset2(x, \"object\"))\n invisible(x)\n}\n\n#' @export\nwith_quad.CraftBox <- function(x, position = waiver(), main = NULL) {\n cli_abort(sprintf(\"Cannot used with %s\", object_name(x)))\n}\n\n#' @export\nwith_quad.layout_title <- function(x, position = waiver(), main = NULL) {\n cli_abort(\"Cannot used with {.obj_type_friendly {x}}\")\n}\n\n#' @export\nwith_quad.layout_theme <- with_quad.layout_title\n\n#' @export\nwith_quad.layout_annotation <- with_quad.layout_title\n\n#' @export\nwith_quad.quad_active <- with_quad.layout_title\n\n#' @export\nwith_quad.quad_anno <- with_quad.layout_title\n\n#' @export\nwith_quad.stack_switch <- with_quad.layout_title\n\nquad_operated_context <- function(with, active, operator) {\n if (is.waive(ans <- .subset2(with, \"position\"))) {\n if (operator == \"-\") {\n # if wrap with `with_quad`\n # we determine the `context` from current actual active position\n if (is.null(active)) {\n ans <- NULL\n } else {\n ans <- c(active, opposite_pos(active))\n if (is.null(main <- .subset2(with, \"main\")) || main) {\n ans <- c(ans, list(NULL))\n }\n }\n } else if (operator == \"+\") {\n ans <- active\n if (!is.null(ans)) {\n if (is.null(main <- .subset2(with, \"main\")) || main) {\n ans <- c(ans, list(NULL))\n }\n }\n } else {\n cli_abort(\"Not implement for {operator}\")\n }\n } else if (!is.null(ans)) { # if set manually\n ans <- setup_pos(ans)\n if (!is.null(main <- .subset2(with, \"main\")) && main) {\n ans <- c(ans, list(NULL))\n }\n }\n ans\n}\n\n#' @importFrom ggplot2 ggplot_add\n#' @export\nggplot_add.ggalign_with_quad <- function(object, plot, object_name, ...) {\n object <- .subset2(object, \"object\")\n object_name <- .subset2(object, \"object_name\")\n ggplot_add(object, plot, object_name)\n}\n"], ["/ggalign/R/ggplot-helper.R", "# Exported function for ggplot2\n# Usually a quick shortcuts to define something\n#\n#' Remove axis elements\n#'\n#' @param axes Which axes elements should be removed? A string containing\n#' one or more of `r oxford_and(c(.tlbr, \"x\", \"y\"))`.\n#' @param text If `TRUE`, will remove the axis labels.\n#' @param ticks If `TRUE`, will remove the axis ticks.\n#' @param title If `TRUE`, will remove the axis title.\n#' @param line If `TRUE`, will remove the axis line.\n#' @return A [`theme()`][ggplot2::theme] object.\n#' @examples\n#' p <- ggplot() +\n#' geom_point(aes(x = wt, y = qsec), data = mtcars)\n#' p + theme_no_axes()\n#' p + theme_no_axes(\"b\")\n#' p + theme_no_axes(\"l\")\n#' @importFrom rlang inject\n#' @importFrom ggplot2 theme element_blank\n#' @export\ntheme_no_axes <- function(axes = \"xy\", text = TRUE, ticks = TRUE,\n title = TRUE, line = FALSE) {\n assert_string(axes, empty_ok = FALSE)\n if (grepl(\"[^tlbrxy]\", axes)) {\n cli_abort(sprintf(\n \"{.arg axes} can only contain the %s characters\",\n oxford_and(c(.tlbr, \"x\", \"y\"))\n ))\n }\n axes <- split_position(axes)\n el <- list(text = text, ticks = ticks, title = title, line = line)\n el <- names(el)[vapply(el, isTRUE, logical(1L), USE.NAMES = FALSE)]\n el_axis <- el_pos <- NULL\n if (length(positions <- vec_set_intersect(axes, .tlbr))) {\n positions <- .subset(\n c(t = \"top\", l = \"left\", b = \"bottom\", r = \"right\"),\n positions\n )\n el_pos <- vec_expand_grid(pos = positions, el = el)\n el_pos <- paste(\"axis\",\n .subset2(el_pos, \"el\"),\n if_else(.subset2(el_pos, \"pos\") %in% c(\"top\", \"bottom\"), \"x\", \"y\"),\n .subset2(el_pos, \"pos\"),\n sep = \".\"\n )\n }\n if (length(axes <- vec_set_intersect(axes, c(\"x\", \"y\")))) {\n el_axis <- vec_expand_grid(axes = axes, el = el)\n el_axis <- paste(\"axis\",\n .subset2(el_axis, \"el\"), .subset2(el_axis, \"axes\"),\n sep = \".\"\n )\n }\n el <- c(el_axis, el_pos)\n el <- vec_set_names(vec_rep(list(element_blank()), length(el)), el)\n inject(theme(!!!el, validate = FALSE))\n}\n\n##########################################################################\n#' Theme Polygon elements\n#'\n#' Draw polygon.\n#'\n#' @inheritParams ggplot2::element_rect\n#' @inheritParams geom_rect3d\n#' @inheritParams ggplot2::fill_alpha\n#' @param linewidth Line size in `mm`.\n#' @param linetype Line type for lines. An integer (0:8), a name (blank, solid,\n#' dashed, dotted, dotdash, longdash, twodash), or a string with an even number\n#' (up to eight) of hexadecimal digits which give the lengths in consecutive\n#' positions in the string.\n#' @seealso [`element_rect`][ggplot2::element_rect]\n#' @return A `element_polygon` object\n#' @export\nelement_polygon <- function(fill = NULL, colour = NULL, linewidth = NULL,\n linetype = NULL, alpha = NULL, lineend = NULL,\n linejoin = NULL, linemitre = NULL, color = NULL,\n inherit.blank = FALSE) {\n if (!is.null(color)) colour <- color\n structure(\n list(\n fill = fill, colour = colour, alpha = alpha,\n linewidth = linewidth, linetype = linetype,\n lineend = lineend, linejoin = linejoin, linemitre = linemitre,\n inherit.blank = inherit.blank\n ),\n class = c(\"ggalign_element_polygon\", \"element_polygon\", \"element\")\n )\n}\n\n#' @importFrom utils packageVersion\n#' @importFrom grid gpar\n#' @importFrom ggplot2 element_grob fill_alpha\n#' @export\nelement_grob.ggalign_element_polygon <- function(element,\n x = c(0, 0.5, 1, 0.5),\n y = c(0.5, 1, 0.5, 0),\n fill = NULL,\n colour = NULL,\n linewidth = NULL,\n linetype = NULL, ...) {\n if (packageVersion(\"ggplot2\") > \"3.5.2\") {\n gp <- ggfun(\"gg_par\")(\n lwd = linewidth, col = colour, fill = fill, lty = linetype\n )\n element_gp <- ggfun(\"gg_par\")(\n lwd = element$linewidth,\n col = element$colour,\n fill = fill_alpha(element$fill, element$alpha %||% NA),\n lty = element$linetype,\n lineend = element$lineend,\n linejoin = element$linejoin,\n linemitre = element$linemitre\n )\n } else {\n gp <- gpar(\n lwd = ggfun(\"len0_null\")(linewidth * .pt),\n col = colour,\n fill = fill,\n lty = linetype\n )\n element_gp <- gpar(\n lwd = ggfun(\"len0_null\")(element$linewidth * .pt),\n col = element$colour,\n fill = fill_alpha(element$fill, element$alpha %||% NA),\n lty = element$linetype,\n lineend = element$lineend,\n linejoin = element$linejoin,\n linemitre = element$linemitre\n )\n }\n grid::polygonGrob(\n x = x, y = y,\n gp = ggfun(\"modify_list\")(element_gp, gp), ...\n )\n}\n\n#' Theme curve elements\n#'\n#' Draw curve.\n#'\n#' @inheritParams element_polygon\n#' @inheritParams grid::curveGrob\n#' @param arrow.fill Fill colour for arrows.\n#' @return A `element_curve` object\n#' @export\nelement_curve <- function(colour = NULL, linewidth = NULL, linetype = NULL,\n lineend = NULL, color = NULL, curvature = NULL,\n angle = NULL, ncp = NULL, shape = NULL,\n arrow = NULL, arrow.fill = NULL,\n inherit.blank = FALSE) {\n colour <- color %||% colour\n arrow.fill <- arrow.fill %||% colour\n arrow <- arrow %||% FALSE\n structure(\n list(\n colour = colour, linewidth = linewidth, linetype = linetype,\n lineend = lineend, curvature = curvature, angle = angle,\n ncp = ncp, shape = shape, arrow = arrow, arrow.fill = arrow.fill,\n inherit.blank = inherit.blank\n ),\n class = c(\"ggalign_element_curve\", \"element_curve\", \"element\")\n )\n}\n\n#' @importFrom grid gpar gTree gList\n#' @importFrom ggplot2 element_grob\n#' @export\nelement_grob.ggalign_element_curve <- function(element, x = 0:1, y = 0:1,\n colour = NULL, linewidth = NULL, linetype = NULL, lineend = NULL,\n arrow.fill = NULL,\n default.units = \"npc\",\n id = NULL,\n id.lengths = NULL, ...) {\n arrow <- if (is.logical(element$arrow) && !element$arrow) {\n NULL\n } else {\n element$arrow\n }\n if (is.null(arrow)) {\n arrow.fill <- colour\n element$arrow.fill <- element$colour\n }\n # The gp settings can override element_gp\n gp <- gpar(\n col = colour,\n fill = arrow.fill %||% colour,\n lwd = ggfun(\"len0_null\")(linewidth * .pt),\n lty = linetype,\n lineend = lineend\n )\n element_gp <- gpar(\n col = element$colour,\n fill = element$arrow.fill %||% element$colour,\n lwd = ggfun(\"len0_null\")(element$linewidth * .pt),\n lty = element$linetype,\n lineend = element$lineend\n )\n gp <- ggfun(\"modify_list\")(element_gp, gp)\n if (is.null(id)) {\n if (is.null(id.lengths)) {\n id <- vec_rep(1L, length(x))\n } else {\n id <- vec_rep_each(seq_along(id.lengths), id.lengths)\n }\n }\n index_list <- .subset2(vec_split(seq_along(x), id), \"val\")\n ans <- lapply(index_list, function(index) {\n grid::curveGrob(\n vec_slice(x, index),\n vec_slice(y, index),\n default.units = default.units,\n gp = gp[index],\n curvature = element$curvature,\n angle = element$angle,\n ncp = element$ncp,\n shape = element$shape,\n arrow = arrow,\n square = FALSE, squareShape = 1,\n inflect = FALSE, open = TRUE,\n ...\n )\n })\n gTree(children = inject(gList(!!!ans)))\n}\n\n##########################################################################\nelement_lengths <- function(.el, .fn, ...) {\n fields <- element_vec_fields(.el)\n if (is.null(fields)) 0L\n lengths(.el[fields])\n}\n\n#' Apply a function to the fields of an element object\n#'\n#' @description\n#' For an [`element`][ggplot2::element_blank] object, some fields are\n#' vectorized, while others are not. This function allows you to apply a\n#' function to the vectorized fields.\n#'\n#' The following helper functions are available:\n#'\n#' - `element_rep`: Applies [`rep()`].\n#' - `element_rep_len`: Applies [`rep_len()`].\n#' - `element_vec_recycle`: Applies [`vec_recycle()`][vctrs::vec_recycle].\n#' - `element_vec_rep`: Applies [`vec_rep()`][vctrs::vec_rep].\n#' - `element_vec_rep_each`: Applies [`vec_rep_each()`][vctrs::vec_rep_each].\n#' - `element_vec_slice`: Applies [`vec_slice()`][vctrs::vec_slice].\n#'\n#' @param .el An [`element`][ggplot2::element_blank] object.\n#' @param .fn The function to be applied to the vectorized fields of the element\n#' object.\n#' @param ... Additional arguments passed on to `fn`.\n#' @export\nelement_vec <- function(.el, .fn, ...) {\n fields <- element_vec_fields(.el)\n if (is.null(fields)) {\n return(.el)\n }\n .el[fields] <- lapply(.el[fields], function(value) {\n if (!is.null(value)) value <- .fn(value, ...)\n value\n })\n .el\n}\n\n#' @export\n#' @rdname element_vec\nelement_rep <- function(.el, ...) element_vec(.el, rep, ...)\n\n#' @param length.out Non-negative integer. The desired length of the output\n#' vector. Other inputs will be coerced to a double vector and the first element\n#' taken. Ignored if `NA` or invalid.\n#' @export\n#' @rdname element_vec\nelement_rep_len <- function(.el, length.out, ...) {\n element_vec(.el, rep_len, ..., length.out = length.out)\n}\n\n#' @inheritParams vctrs::vec_recycle\n#' @export\n#' @rdname element_vec\nelement_vec_recycle <- function(.el, size, ...) {\n element_vec(.el, vec_recycle, size = size, ...)\n}\n\n#' @inheritParams vctrs::vec_rep\n#' @export\n#' @rdname element_vec\nelement_vec_rep <- function(.el, times, ...) {\n element_vec(.el, vec_rep, times = times, ...)\n}\n\n#' @export\n#' @rdname element_vec\nelement_vec_rep_each <- function(.el, times, ...) {\n element_vec(.el, vec_rep_each, times = times, ...)\n}\n\n#' @inheritParams vctrs::vec_slice\n#' @importFrom grid is.unit\n#' @export\n#' @rdname element_vec\nelement_vec_slice <- function(.el, i, ...) {\n element_vec(.el, function(x) {\n if (is.unit(x)) x[i, ...] else vec_slice(x, i, ...)\n })\n}\n\nelement_vec_fields <- function(el) UseMethod(\"element_vec_fields\")\n\n#' @export\nelement_vec_fields.ggalign_element_polygon <- function(el) {\n c(\n \"fill\", \"colour\", \"linewidth\", \"linetype\",\n \"lineend\", \"linejoin\", \"linemitre\", \"alpha\"\n )\n}\n\n#' @export\nelement_vec_fields.element_blank <- function(el) NULL\n\n#' @export\nelement_vec_fields.element_polygon <- function(el) {\n c(\"fill\", \"colour\", \"linewidth\", \"linetype\")\n}\n\n#' @export\nelement_vec_fields.element_point <- function(el) {\n c(\"colour\", \"shape\", \"size\", \"fill\", \"stroke\")\n}\n\n#' @export\nelement_vec_fields.element_rect <- function(el) {\n c(\"fill\", \"colour\", \"linewidth\", \"linetype\")\n}\n\n#' @export\nelement_vec_fields.element_line <- function(el) {\n c(\"colour\", \"linewidth\", \"linetype\", \"lineend\")\n}\n\n#' @export\nelement_vec_fields.element_text <- function(el) {\n c(\n \"family\", \"face\", \"colour\", \"size\", \"hjust\", \"vjust\",\n \"angle\", \"lineheight\"\n )\n}\n\n#' @export\nelement_vec_fields.default <- function(el) stop_input_type(el, \"an element\")\n\n######################################################\n#' Remove scale expansion\n#'\n#' @param borders Which border should be removed? A string containing\n#' one or more of `r oxford_and(c(.tlbr, \"x\", \"y\"))`.\n#' @return An object which can be added to ggplot.\n#' @export\nno_expansion <- function(borders = \"tlbr\") {\n assert_string(borders, empty_ok = FALSE)\n if (grepl(\"[^tlbrxy]\", borders)) {\n cli_abort(sprintf(\n \"{.arg borders} can only contain the %s characters\",\n oxford_and(c(.tlbr, \"x\", \"y\"))\n ))\n }\n borders <- .subset(list(\n t = \"top\", l = \"left\", b = \"bottom\", r = \"right\",\n x = c(\"left\", \"right\"), y = c(\"bottom\", \"top\")\n ), split_position(borders))\n borders <- vec_unique(unlist(borders, recursive = FALSE, use.names = FALSE))\n # expansion in x-axis\n structure(list(borders = borders), class = c(\"ggalign_no_expansion\"))\n}\n\n#' @importFrom ggplot2 ggplot_add ggproto ggproto_parent\n#' @export\nggplot_add.ggalign_no_expansion <- function(object, plot, object_name, ...) {\n borders <- .subset2(object, \"borders\")\n ParentLayout <- plot$layout\n\n # tricks to ensure remove `coord` won't remove `no_expansion()`\n plot$layout <- ggproto(NULL, ParentLayout,\n setup_panel_params = function(self) {\n ParentCoord <- self$coord\n self$coord <- ggproto(NULL, ParentCoord,\n setup_panel_params = function(self, scale_x, scale_y,\n params = list()) {\n if (!is.null(scale_x)) {\n expansion <- scale_x$expand %|w|%\n if (packageVersion(\"ggplot2\") > \"3.5.2\") {\n ggfun(\"default_expansion\")(\n scale_y,\n # for ggplot2 > 3.5.2, expand was passed by\n # params\n expand = params$expand[c(4, 2)]\n )\n } else {\n ggfun(\"default_expansion\")(\n scale_y,\n # for ggplot2 > 3.5.2, expand was passed by\n # params\n expand = self$expand\n )\n }\n if (any(borders == \"left\")) {\n expansion[1:2] <- 0\n }\n if (any(borders == \"right\")) {\n expansion[3:4] <- 0\n }\n scale_x$expand <- expansion\n }\n if (!is.null(scale_y)) {\n expansion <- scale_y$expand %|w|%\n if (packageVersion(\"ggplot2\") > \"3.5.2\") {\n ggfun(\"default_expansion\")(\n scale_y,\n # for ggplot2 > 3.5.2, expand was passed by\n # params\n expand = params$expand[c(3, 1)]\n )\n } else {\n ggfun(\"default_expansion\")(\n scale_y,\n # for ggplot2 > 3.5.2, expand was passed by\n # params\n expand = self$expand\n )\n }\n if (any(borders == \"bottom\")) {\n expansion[1:2] <- 0\n }\n if (any(borders == \"top\")) {\n expansion[3:4] <- 0\n }\n scale_y$expand <- expansion\n }\n ggproto_parent(ParentCoord, self)$setup_panel_params(\n scale_x = scale_x, scale_y = scale_y, params = params\n )\n }\n )\n ggproto_parent(ParentLayout, self)$setup_panel_params()\n }\n )\n plot\n}\n"], ["/ggalign/R/layout-.R", "# Will ensure serialisation includes a link to the ggalign namespace\n# Copied from patchwork\nnamespace_link <- function() NULL\n\n# https://stackoverflow.com/questions/65817557/s3-methods-extending-ggplot2-gg-function\n# Here we use S4 object to override the double dispatch of `+.gg` method\n# TO-DO: use S7\n#' A `Layout` object\n#'\n#' A `Layout` object defines how to place the plots.\n#'\n#' @keywords internal\n# add suffix \"Proto\" to avoid conflict with ggplot2\nmethods::setClass(\"LayoutProto\",\n list(\n active = \"ANY\", # current active plot\n schemes = \"list\", # used to provide global parameters for all plots\n # control the layout, `theme` will also be used by `ggsave`\n titles = \"list\",\n annotation = \"list\", # To-Do add `pacth_titles` for layout\n theme = \"ANY\",\n `_namespace` = \"ANY\"\n ),\n prototype = list(\n active = NULL, titles = list(),\n annotation = list(), theme = NULL,\n `_namespace` = namespace_link\n )\n)\n\n#' @export\nprint.LayoutProto <- print.alignpatches\n\n#' @importFrom grid grid.draw\n#' @exportS3Method\ngrid.draw.LayoutProto <- grid.draw.alignpatches\n\n#' @export\nalignpatch.LayoutProto <- function(x) alignpatch(ggalign_build(x))\n\n#' Print Layout object\n#'\n#' @param object A `r rd_layout()`.\n#' @return The input invisiblely.\n#' @importFrom methods show\n#' @export\n#' @keywords internal\nmethods::setMethod(\"show\", \"LayoutProto\", function(object) {\n print(object)\n})\n\n#' Subset a `Layout` object\n#'\n#' Used by [`ggplot_build`][ggplot2::ggplot_build] and\n#' [`ggsave`][ggplot2::ggsave]\n#'\n#' @param x A `Layout` object\n#' @param name A string of slot name in `Layout` object.\n#' @return The slot value.\n#' @importFrom methods slot\n#' @export\n#' @keywords internal\nmethods::setMethod(\"$\", \"LayoutProto\", function(x, name) {\n slot(x, name)\n})\n\n###########################################################\ndefault_layout <- function(layout) { # setup default value for the layout\n layout@theme <- complete_theme(default_theme() + layout@theme)\n\n # we by default, collect all guides\n layout@schemes$scheme_align[\"guides\"] <- list(\n .subset2(.subset2(layout@schemes, \"scheme_align\"), \"guides\") %|w|% \"tlbr\"\n )\n\n # we by default, use `default_theme()`\n layout@schemes$scheme_theme <- update_scheme(\n .subset2(layout@schemes, \"scheme_theme\"),\n new_scheme_theme(complete_theme(default_theme()))\n )\n layout\n}\n\nis_linear <- function(layout) UseMethod(\"is_linear\")\n\n#' @export\nis_linear.StackLayout <- function(layout) TRUE\n\n#' @export\nis_linear.CircleLayout <- function(layout) FALSE\n\n###########################################################\ninherit_parent_layout_schemes <- function(layout, schemes) {\n if (is.null(schemes)) {\n return(layout@schemes)\n }\n inherit_schemes(layout@schemes, schemes)\n}\n\ninherit_parent_layout_theme <- function(layout, theme, spacing = NULL) {\n if (is.null(theme)) return(layout@theme) # styler: off\n # parent theme, set the global panel spacing,\n # so that every panel aligns well\n if (is.null(layout@theme)) return(theme) # styler: off\n ans <- theme + layout@theme\n if (is.null(spacing)) return(ans) # styler: off\n switch(spacing,\n x = ans + theme(\n panel.spacing.x = calc_element(\"panel.spacing.x\", theme)\n ),\n y = ans + theme(\n panel.spacing.y = calc_element(\"panel.spacing.y\", theme)\n )\n )\n}\n\n############################################################\n#' Get the statistics from the layout\n#'\n#' @param x A `r rd_layout()`.\n#' @inheritParams rlang::args_dots_used\n#' @return The statistics\n#' @export\nggalign_stat <- function(x, ...) {\n UseMethod(\"ggalign_stat\")\n}\n\n#' @param position A string of `r oxford_or(.TLBR)`.\n#' @export\n#' @rdname ggalign_stat\nggalign_stat.QuadLayout <- function(x, position, ...) {\n ggalign_stat(x = slot(x, position), ...)\n}\n\n#' @param what A single number or string of the plot elements in the stack\n#' layout.\n#' @export\n#' @rdname ggalign_stat\nggalign_stat.StackLayout <- function(x, what, ...) {\n plot_list <- x@plot_list\n index <- vec_as_location2(\n what,\n n = length(plot_list),\n names = names(plot_list),\n missing = \"error\"\n )\n ggalign_stat(x = .subset2(plot_list, index), ...)\n}\n\n#' @export\nggalign_stat.CraftBox <- function(x, ...) {\n ggalign_stat(x@craftsman, ...)\n}\n\n#' @export\nggalign_stat.CraftAlign <- function(x, ...) {\n rlang::check_dots_empty()\n .subset2(x, \"statistics\")\n}\n\n#' @export\nggalign_stat.default <- function(x, ...) {\n cli_abort(sprintf(\"no statistics found for %s\", object_name(x)))\n}\n\n#############################################################\n#' Reports whether `x` is layout object\n#'\n#' @param x An object to test.\n#' @return A single boolean value.\n#' @examples\n#' is_layout(ggheatmap(1:10))\n#'\n#' @importFrom methods is\n#' @export\nis_layout <- function(x) is(x, \"LayoutProto\")\n\n#' @examples\n#' # for quad_layout()\n#' is_quad_layout(quad_alignb(1:10))\n#' is_quad_layout(quad_alignh(1:10))\n#' is_quad_layout(quad_alignv(1:10))\n#' is_quad_layout(quad_free(mtcars))\n#'\n#' @export\n#' @rdname is_layout\nis_quad_layout <- function(x) is(x, \"QuadLayout\")\n\n#' @examples\n#' # for stack_layout()\n#' is_stack_layout(stack_discrete(\"h\", 1:10))\n#' is_stack_layout(stack_continuous(\"h\", 1:10))\n#'\n#' @export\n#' @rdname is_layout\nis_stack_layout <- function(x) is(x, \"StackLayout\")\n\n#' @export\n#' @rdname is_layout\nis_stack_cross <- function(x) is(x, \"StackCross\")\n\n#' @export\n#' @rdname is_layout\nis_circle_layout <- function(x) is(x, \"CircleLayout\")\n\n#' @examples\n#' # for heatmap_layout()\n#' is_heatmap_layout(ggheatmap(1:10))\n#' @export\n#' @rdname is_layout\nis_heatmap_layout <- function(x) is(x, \"HeatmapLayout\")\n\n#' @examples\n#' is_ggheatmap(ggheatmap(1:10))\n#' @export\n#' @rdname is_layout\nis_ggheatmap <- is_heatmap_layout\n\nis_cross_layout <- function(x) is_stack_cross(x)\n"], ["/ggalign/R/alignpatch-build.R", "#' @importFrom grid grid.draw\n#' @importFrom rlang try_fetch cnd_signal\n#' @export\nprint.alignpatches <- function(x, newpage = is.null(vp), vp = NULL, ...) {\n ggplot2::set_last_plot(x)\n if (newpage) {\n grid::grid.newpage()\n if (is.character(vp)) {\n cli_abort(c(\n \"{.arg vp} cannot be a character string when {.arg newpage} is TRUE.\",\n i = \"Please provide a viewport object or set {.arg newpage} to FALSE.\"\n ))\n }\n }\n if (!is.null(vp)) {\n if (is.character(vp)) {\n cur <- grid::current.viewport()$name\n grid::seekViewport(vp)\n if (!identical(cur, \"ROOT\")) on.exit(grid::seekViewport(cur))\n } else {\n grid::pushViewport(vp)\n on.exit(grid::upViewport())\n }\n }\n\n # render the plot\n try_fetch(\n grid.draw(x, ...),\n error = function(e) {\n if (inherits(e, \"simpleError\") &&\n deparse(conditionCall(e)[[1L]]) == \"grid.Call\") {\n error_name <- obj_type_friendly(x)\n if (Sys.getenv(\"RSTUDIO\") == \"1\") {\n cli_abort(c(paste(\n \"The RStudio {.field Plots} window may be\",\n \"too small to show\", error_name\n ), i = \"Please make the window larger.\"), parent = e)\n } else {\n cli_abort(c(\n \"The viewport may be too small to show {error_name}.\",\n i = \"Please make the window larger.\"\n ), parent = e)\n }\n }\n cnd_signal(e)\n }\n )\n invisible(x)\n}\n\n#' @importFrom grid grid.draw\n#' @exportS3Method\ngrid.draw.alignpatches <- function(x, recording = TRUE) {\n grid.draw(ggalignGrob(x), recording = recording)\n}\n\n#' @export\nggalign_build.alignpatches <- function(x) x\n\n#' @importFrom ggplot2 find_panel element_render theme theme_get\n#' @importFrom gtable gtable_add_grob gtable_add_rows gtable_add_cols\n#' @importFrom rlang arg_match0\n#' @importFrom S7 prop\n#' @export\nggalign_gtable.alignpatches <- function(x) {\n titles <- prop(x, \"titles\")\n\n # ensure theme has no missing value\n theme <- prop(x, \"theme\") %||% theme_get()\n\n # `TO-DO`: use `complete_theme()` from ggplot2 release\n theme <- complete_theme(theme)\n attr(x, \"theme\") <- theme # bypass the setter function\n table <- alignpatch(x)$patch_gtable(top_level = TRUE)\n\n fix_respect <- is.matrix(.subset2(table, \"respect\"))\n\n # Add title, subtitle, and caption -------------------\n # https://github.com/tidyverse/ggplot2/blob/2e08bba0910c11a46b6de9e375fade78b75d10dc/R/plot-build.R#L219C3-L219C9\n title <- element_render(\n theme = theme, \"plot.title\", .subset2(titles, \"title\"),\n margin_y = TRUE, margin_x = TRUE\n )\n title_height <- grobHeight(title)\n\n # Subtitle\n subtitle <- element_render(\n theme, \"plot.subtitle\", .subset2(titles, \"subtitle\"),\n margin_y = TRUE, margin_x = TRUE\n )\n subtitle_height <- grobHeight(subtitle)\n\n # caption\n caption <- element_render(\n theme, \"plot.caption\", .subset2(titles, \"caption\"),\n margin_y = TRUE, margin_x = TRUE\n )\n caption_height <- grobHeight(caption)\n\n # positioning of title and subtitle is governed by plot.title.position\n # positioning of caption is governed by plot.caption.position\n # \"panel\" means align to the panel(s)\n # \"plot\" means align to the entire plot (except margins and tag)\n panel_pos <- find_panel(table)\n title_pos <- arg_match0(\n theme$plot.title.position %||% \"panel\",\n c(\"panel\", \"plot\"),\n arg_nm = \"plot.title.position\",\n error_call = quote(theme())\n )\n\n caption_pos <- arg_match0(\n theme$plot.caption.position %||% \"panel\",\n values = c(\"panel\", \"plot\"),\n arg_nm = \"plot.caption.position\",\n error_call = quote(theme())\n )\n if (title_pos == \"panel\") {\n title_l <- panel_pos$l\n title_r <- panel_pos$r\n } else {\n title_l <- 1L\n title_r <- ncol(table)\n }\n if (caption_pos == \"panel\") {\n caption_l <- panel_pos$l\n caption_r <- panel_pos$r\n } else {\n caption_l <- 1L\n caption_r <- ncol(table)\n }\n\n table <- gtable_add_rows(table, subtitle_height, pos = 0)\n table <- gtable_add_grob(table, subtitle,\n name = \"subtitle\",\n t = 1, b = 1, l = title_l, r = title_r, clip = \"off\"\n )\n\n table <- gtable_add_rows(table, title_height, pos = 0)\n table <- gtable_add_grob(table, title,\n name = \"title\",\n t = 1, b = 1, l = title_l, r = title_r, clip = \"off\"\n )\n\n table <- gtable_add_rows(table, caption_height, pos = -1)\n table <- gtable_add_grob(table, caption,\n name = \"caption\",\n t = -1, b = -1, l = caption_l, r = caption_r, clip = \"off\"\n )\n if (fix_respect) {\n table$respect <- rbind(0L, 0L, table$respect, 0L)\n }\n\n # add margins --------------------------------------\n plot_margin <- calc_element(\"plot.margin\", theme)\n\n table <- gtable_add_rows(table, plot_margin[1L], 0L)\n table <- gtable_add_rows(table, plot_margin[3L])\n if (fix_respect) table$respect <- rbind(0L, table$respect, 0L)\n table <- gtable_add_cols(table, plot_margin[2L], 0L)\n table <- gtable_add_cols(table, plot_margin[4L])\n if (fix_respect) table$respect <- cbind(0L, table$respect, 0L)\n\n # add background -----------------------------------\n if (inherits(theme$plot.background, \"element\")) {\n table <- gtable_add_grob(table,\n element_render(theme, \"plot.background\"),\n t = 1L, l = 1L, b = -1L, r = -1L, name = \"background\", z = -Inf\n )\n table$layout <- table$layout[\n c(nrow(table$layout), 1:(nrow(table$layout) - 1L)),\n ]\n table$grobs <- table$grobs[\n c(nrow(table$layout), 1:(nrow(table$layout) - 1L))\n ]\n }\n table\n}\n"], ["/ggalign/R/craft-cross-link.R", "#' Add a plot to connect selected observations\n#'\n#' @param link A [`link_draw()`] object that defines how to draw the links,\n#' such as [`link_line()`].\n#' @param on_top A boolean value indicating whether to draw the link on top of\n#' the plot panel (`TRUE`) or below (`FALSE`).\n#' @inheritParams cross_none\n#' @inheritParams ggmark\n#'\n#' @section ggplot2 Specification:\n#' The `cross_link` function initializes a `ggplot` object but does not\n#' initialize any data. Using [`scheme_data()`] to change the internal data if\n#' needed.\n#'\n#' @export\ncross_link <- function(link, data = waiver(), ...,\n on_top = TRUE, obs_size = 1,\n inherit_index = NULL, inherit_panel = NULL,\n inherit_nobs = NULL,\n size = NULL, active = NULL) {\n if (!inherits(link, \"ggalign_link_draw\")) {\n cli_abort(\"{.arg link} must be a {.fn link_draw} object\")\n }\n assert_obs_size(obs_size)\n assert_active(active)\n active <- update_active(active, new_active(use = TRUE))\n cross(CrossLink,\n data = data, data_params = list2(...),\n link = link, obs_size = obs_size,\n plot = ggplot(), size = size,\n schemes = default_schemes(),\n active = active,\n on_top = on_top,\n inherit_nobs = inherit_nobs,\n inherit_panel = inherit_panel,\n inherit_index = inherit_index\n )\n}\n\n#' @importFrom ggplot2 ggproto ggproto_parent\n#' @importFrom grid gTree\n#' @include craft-cross-.R\nCrossLink <- ggproto(\"CrossLink\", CraftCross,\n interact_layout = function(self, layout) {\n if (!self$in_linear) { # only used for linear coordinate\n cli_abort(c(\n sprintf(\n \"Cannot add %s to %s\",\n object_name(self), layout_name\n ),\n i = sprintf(\n \"%s can only be used in linear layout\",\n object_name(self)\n )\n ))\n }\n ggproto_parent(CraftCross, self)$interact_layout(layout)\n },\n build_plot = function(self, plot, design, extra_design = NULL,\n previous_design = NULL) {\n if (is.null(.subset2(previous_design, \"nobs\"))) {\n cli_abort(\n sprintf(\n \"layout {.field nobs} for %s before %s is not initialized \",\n self$layout_name, object_name(self)\n )\n )\n }\n if (is.null(.subset2(design, \"nobs\"))) {\n cli_abort(\n sprintf(\n \"layout {.field nobs} for %s after %s is not initialized \",\n self$layout_name, object_name(self)\n )\n )\n }\n\n direction <- self$direction\n position <- self$position\n\n # parse links --------------------------------------------\n link <- self$link\n design1 <- previous_design\n design2 <- design\n full_data1 <- split(\n seq_len(.subset2(design1, \"nobs\")),\n .subset2(design1, \"panel\")\n )\n full_data2 <- split(\n seq_len(.subset2(design2, \"nobs\")),\n .subset2(design2, \"panel\")\n )\n links <- .subset2(link, \"links\")\n # set default links for link_line()\n if (is_empty(links) &&\n inherits(link, \"ggalign_link_line\") &&\n identical(.subset2(design1, \"nobs\"), .subset2(design2, \"nobs\"))) {\n links <- lapply(seq_len(.subset2(design1, \"nobs\")), function(i) {\n rlang::new_formula(i, i)\n })\n links <- pair_links(!!!links)\n }\n link_index <- make_links_data(\n links,\n design1 = design1, design2 = design2,\n labels1 = self$labels0, labels2 = self$labels\n )\n data_index <- lapply(link_index, function(index) {\n if (is.null(index)) {\n return(NULL)\n }\n hand1 <- .subset2(index, \"hand1\")\n hand2 <- .subset2(index, \"hand2\")\n list(\n hand1 = .subset2(design1, \"index\")[hand1],\n hand2 = .subset2(design2, \"index\")[hand2]\n )\n })\n plot$ggalign_link_data <- list(\n full_data1 = full_data1,\n full_data2 = full_data2,\n link_index = link_index,\n data_index = data_index,\n direction = direction,\n draw = .subset2(link, \"draw\"),\n obs_size = self$obs_size\n )\n plot\n },\n finish_plot = function(self, plot, schemes, theme) {\n plot <- plot_add_schemes(plot, schemes)\n\n # save spacing for usage\n spacing <- calc_element(\n switch_direction(\n self$direction,\n \"panel.spacing.y\",\n \"panel.spacing.x\"\n ),\n theme\n ) %||% unit(0, \"mm\")\n\n # setup the grob\n grob <- inject(gTree(\n !!!plot$ggalign_link_data,\n spacing1 = spacing,\n spacing2 = spacing,\n cl = \"ggalignLinkTree\"\n ))\n plot$ggalign_link_data <- NULL\n\n # insert the grob\n plot <- plot + inset(grob, on_top = self$on_top)\n ggremove_margin(plot, self$direction) + theme_recycle()\n },\n summary = function(self, plot) {\n header <- ggproto_parent(CraftCross, self)$summary(plot)\n c(header, \" Add plot to connect selected observations\")\n }\n)\n"], ["/ggalign/R/alignpatch-alignpatches.R", "#' @importFrom ggplot2 ggproto\n#' @export\nalignpatch.alignpatches <- function(x) {\n ggproto(NULL, PatchAlignpatches, plot = x)\n}\n\n#' @noRd\nPatchAlignpatches <- ggproto(\"PatchAlignpatches\", Patch,\n set_guides = function(self, guides) guides,\n #' @importFrom gtable gtable gtable_add_grob\n #' @importFrom grid unit\n #' @importFrom ggplot2 wrap_dims calc_element zeroGrob theme_get\n #' @importFrom S7 prop\n patch_gtable = function(self, theme = theme_get(), guides = NULL,\n top_level = FALSE, plot = self$plot) {\n patches <- lapply(prop(plot, \"plots\"), alignpatch)\n layout <- prop(plot, \"layout\")\n\n # get the design areas and dims ------------------\n panel_widths <- .subset2(layout, \"widths\")\n panel_heights <- .subset2(layout, \"heights\")\n if (is.null(area <- .subset2(layout, \"area\"))) {\n if (is.null(layout$ncol) && length(panel_widths) > 1L) {\n layout$ncol <- length(panel_widths)\n }\n if (is.null(layout$nrow) && length(panel_heights) > 1L) {\n layout$nrow <- length(panel_heights)\n }\n dims <- wrap_dims(\n length(patches),\n .subset2(layout, \"nrow\"),\n .subset2(layout, \"ncol\")\n )\n area <- create_area(\n dims[2L], dims[1L],\n .subset2(layout, \"byrow\")\n )\n } else {\n dims <- c(max(field(area, \"b\")), max(field(area, \"r\")))\n }\n\n # filter `plots` based on the design areas --------------------\n if (vec_size(area) < vec_size(patches)) {\n cli_warn(\n \"Too few patch areas to hold all plots. Dropping plots\"\n )\n plots <- vec_slice(patches, vec_seq_along(area))\n } else {\n area <- vec_slice(area, seq_along(patches))\n }\n\n # remove NULL patch -----------------------------------\n keep <- !vapply(patches, is.null, logical(1L), USE.NAMES = FALSE)\n patches <- vec_slice(patches, keep)\n\n # if no plots, we return empty gtable -----------------\n if (is_empty(patches)) return(make_patch_table()) # styler: off\n self$patches <- patches\n\n # add borders to patch --------------------------------\n area <- vec_slice(area, keep)\n for (i in seq_along(patches)) {\n patches[[i]]$borders <- c(\n if (field(area, \"t\")[i] == 1L) \"top\" else NULL,\n if (field(area, \"l\")[i] == 1L) \"left\" else NULL,\n if (field(area, \"b\")[i] == .subset(dims, 1L)) {\n \"bottom\"\n } else {\n NULL\n },\n if (field(area, \"r\")[i] == .subset(dims, 2L)) {\n \"right\"\n } else {\n NULL\n }\n )\n }\n\n # we inherit parameters from the parent --------------------\n # by default, we won't collect any guide legends\n parent_guides <- guides\n guides <- .subset2(layout, \"guides\") %|w|% parent_guides\n\n # by default, we use ggplot2 default theme\n if (!is.null(prop(plot, \"theme\"))) theme <- theme + prop(plot, \"theme\")\n self$theme <- theme\n\n #######################################################\n # 1. patch_gtable: create the gtable for the patch, will set internal\n # `gt`\n # 2. `collect_guides`, can change the internal `gt`\n # 3. set_sizes:\n # - (To-Do) align_panel_spaces: can change the internal `gt`\n # - align_panel_sizes, can change the internal `gt`\n # - get_sizes, the widths and heights for the internal `gt`\n # 4. set_grobs: will call `align_border` and `split_gt`, return the\n # final gtable\n # setup gtable list ----------------------------------\n # Let each patch to determine whether to collect guides\n collected <- lapply(patches, function(patch) patch$set_guides(guides))\n collected_guides <- vector(\"list\", length(patches))\n\n # Always ensure that plots placed in a border collect their guides, if\n # any guides are to be collected in that border. This prevents overlap,\n # unless the guides will be collected by the parent layout.\n border_with_guides <- unique(unlist(collected, FALSE, FALSE))\n border_with_guides <- setdiff(border_with_guides, parent_guides)\n for (i in seq_along(patches)) {\n patch <- .subset2(patches, i)\n g <- union(\n .subset2(collected, i),\n intersect(border_with_guides, patch$borders)\n )\n patch$gt <- patch$patch_gtable(theme = theme, guides = g)\n collected_guides[i] <- list(patch$collect_guides(g))\n }\n\n # collect guides ---------------------------------------\n self$collected_guides <- collect_guides_list(collected_guides)\n\n # prepare the output ----------------------------------\n gt <- gtable(\n unit(rep(0L, TABLE_COLS * dims[2L]), \"null\"),\n unit(rep(0L, TABLE_ROWS * dims[1L]), \"null\")\n )\n\n # setup sizes for each row/column -----------------------\n gt <- self$set_sizes(\n area, dims, panel_widths, panel_heights,\n patches = patches, gt = gt\n )\n\n # add the panel position --------------------------------\n panel_pos <- list(\n t = TOP_BORDER + 1L,\n l = LEFT_BORDER + 1L,\n b = TABLE_ROWS * dims[1L] - BOTTOM_BORDER,\n r = TABLE_COLS * dims[2L] - RIGHT_BORDER\n )\n\n # add guides into the final gtable ----------------------\n if (top_level) {\n gt <- self$attach_guide_list(\n guide_list = self$collected_guides,\n theme = theme,\n panel_pos = panel_pos,\n gt = gt\n )\n }\n\n # setup grobs -------------------------------------------\n # For z in the gtable layout\n # 0L: layout background\n # 1L: background of the plot\n # 2L: plot table\n # 3L: foreground of the panel area\n # 4L: legends\n gt <- self$set_grobs(area, patches = patches, gt = gt)\n\n # add panel area ---------------------------------------\n gt <- gtable_add_grob(\n gt, list(zeroGrob()),\n t = .subset2(panel_pos, \"t\"),\n l = .subset2(panel_pos, \"l\"),\n b = .subset2(panel_pos, \"b\"),\n r = .subset2(panel_pos, \"r\"),\n z = 0L,\n name = \"panel-area\"\n )\n gt <- gtable_add_grob(\n gt,\n # foreground\n list(element_render(theme, \"panel.border\", fill = NA)),\n t = .subset2(panel_pos, \"t\"),\n l = .subset2(panel_pos, \"l\"),\n b = .subset2(panel_pos, \"b\"),\n r = .subset2(panel_pos, \"r\"),\n z = 3L,\n name = \"panel-foreground\"\n )\n\n # add background -----------------------------------\n if (!top_level && inherits(theme$plot.background, \"element\")) {\n gt <- gtable_add_grob(gt,\n element_render(theme, \"plot.background\"),\n t = 1L, l = 1L, b = -1L, r = -1L,\n name = \"background\", z = 0L\n )\n }\n\n # arrange the grobs\n idx <- order(.subset2(.subset2(gt, \"layout\"), \"z\"))\n gt$layout <- vec_slice(.subset2(gt, \"layout\"), idx)\n gt$grobs <- .subset(.subset2(gt, \"grobs\"), idx)\n gt\n },\n align_border = function(self, t = NULL, l = NULL, b = NULL, r = NULL,\n gt = self$gt, patches = self$patches) {\n if (is.null(t) && is.null(l) && is.null(b) && is.null(r)) {\n return(gt)\n }\n gt <- Patch$align_border(t = t, l = l, b = b, r = r, gt = gt)\n self$recurse_lapply(function(patch, grob, t, l, b, r) {\n # For each plot grob, we reuse it's method to set the border\n # sizes we only set the border sizes for plot in the border\n patch$align_border(t = t, l = l, b = b, r = r, gt = grob)\n }, t = t, l = l, b = b, r = r, gt = gt, patches = patches)\n },\n collect_guides = function(self, guides, gt = self$gt) {\n collected_guides <- self$collected_guides\n # for guides not collected by the top-level alignpatches, we attach the\n # guides\n self$gt <- self$attach_guide_list(\n collected_guides[\n vec_set_difference(names(collected_guides), guides)\n ],\n gt = gt\n )\n # return guides to be collected\n .subset(collected_guides, guides)\n },\n #' @importFrom grid is.unit unit\n set_sizes = function(self, area, dims,\n panel_widths, panel_heights,\n patches, gt = self$gt) {\n panel_widths <- rep(panel_widths, length.out = dims[2L])\n panel_heights <- rep(panel_heights, length.out = dims[1L])\n if (!is.unit(panel_widths)) panel_widths <- unit(panel_widths, \"null\")\n if (!is.unit(panel_heights)) {\n panel_heights <- unit(panel_heights, \"null\")\n }\n\n # For gtable with fixed aspect ratio -------------\n # if it cannot be fixed and aligned, the strip, axis and labs will be\n # attached into the panel\n # the plot to be fixed must in only one square of the area\n need_fix <- field(area, \"l\") == field(area, \"r\") &\n field(area, \"t\") == field(area, \"b\") &\n vapply(\n patches,\n function(patch) patch$respect(),\n logical(1L),\n USE.NAMES = FALSE\n )\n\n # here we respect the aspect ratio when necessary -----\n # if the width or height is NA, we will guess the panel widths or\n # heights based on the fixed aspect ratio\n guess_widths <- which(is.na(as.numeric(panel_widths)))\n guess_heights <- which(is.na(as.numeric(panel_heights)))\n cols <- field(area, \"l\")\n rows <- field(area, \"t\")\n patch_index <- order(\n # we first set the widths for the fixed plot with heights set by\n # user\n cols %in% guess_widths & !rows %in% guess_heights,\n # we then set the heights for the fixed plot with widths set by user\n !cols %in% guess_widths & rows %in% guess_heights,\n # we set widths and heights for remaning plots\n # based on the number of plots in each row/column in the descending\n # order\n c(table(rows[need_fix]))[as.character(rows)],\n c(table(cols[need_fix]))[as.character(cols)],\n decreasing = TRUE\n )\n respect_dims <- vector(\"list\", length(patches))\n\n # For plot cannot be fixed, we always attach strips, axes and labels\n # into the panel area\n for (i in patch_index) {\n row <- .subset(rows, i)\n col <- .subset(cols, i)\n # we always build a standard gtable layout from the gtable\n panel_sizes <- .subset2(patches, i)$align_panel_sizes(\n panel_width = panel_widths[col],\n panel_height = panel_heights[row]\n )\n panel_widths[col] <- .subset2(panel_sizes, \"width\")\n panel_heights[row] <- .subset2(panel_sizes, \"height\")\n if (.subset2(panel_sizes, \"respect\")) {\n respect_dims[[i]] <- matrix(c(\n (row - 1L) * TABLE_ROWS + TOP_BORDER + 1L,\n (col - 1L) * TABLE_COLS + LEFT_BORDER + 1L\n ), nrow = 1L)\n }\n }\n if (!is.null(respect_dims <- do.call(base::rbind, respect_dims))) {\n respect <- matrix(\n 0L, TABLE_ROWS * dims[1L],\n TABLE_COLS * dims[2L]\n )\n respect[respect_dims] <- 1L\n gt$respect <- respect\n }\n\n # we set the widths/heights with no fixed plots to be 1 null\n if (any(guess_widths <- is.na(as.numeric(panel_widths)))) {\n panel_widths[guess_widths] <- unit(1L, \"null\")\n }\n if (any(guess_heights <- is.na(as.numeric(panel_heights)))) {\n panel_heights[guess_heights] <- unit(1L, \"null\")\n }\n\n # setup sizes for non-panel rows/columns --------------\n sizes <- table_sizes(\n lapply(patches, function(patch) patch$get_sizes()),\n area, dims[2L], dims[1L]\n )\n widths <- .subset2(sizes, \"widths\")\n heights <- .subset2(sizes, \"heights\")\n\n # restore the panel sizes ----------------------------\n width_ind <- seq(LEFT_BORDER + 1L,\n by = TABLE_COLS, length.out = dims[2L]\n )\n height_ind <- seq(TOP_BORDER + 1L,\n by = TABLE_ROWS, length.out = dims[1L]\n )\n widths[width_ind] <- panel_widths\n heights[height_ind] <- panel_heights\n\n # setup the widths and heights -----------------------\n gt$widths <- widths\n gt$heights <- heights\n gt\n },\n\n #' @importFrom gtable gtable_add_grob\n set_grobs = function(self, area, patches, gt = self$gt) {\n widths <- .subset2(gt, \"widths\")\n heights <- .subset2(gt, \"heights\")\n for (i in seq_along(patches)) {\n loc <- vec_slice(area, i)\n # We must align the borders for the gtable grob with the\n # final plot area sizes\n l <- (field(loc, \"l\") - 1L) * TABLE_COLS + 1L\n l_widths <- widths[seq(l, l + LEFT_BORDER - 1L)]\n r <- field(loc, \"r\") * TABLE_COLS\n r_widths <- widths[seq(r - RIGHT_BORDER + 1L, r)]\n t <- (field(loc, \"t\") - 1L) * TABLE_ROWS + 1L\n t_heights <- heights[seq(t, t + TOP_BORDER - 1L)]\n b <- field(loc, \"b\") * TABLE_ROWS\n b_heights <- heights[seq(b - BOTTOM_BORDER + 1L, b)]\n patch <- .subset2(patches, i)\n\n grobs <- patch$split_gt(patch$align_border(\n t = t_heights, l = l_widths,\n b = b_heights, r = r_widths\n ))\n\n # then we add the plot ---------------------------------\n gt <- patch$add_plot(\n gt, .subset2(grobs, \"plot\"), t, l, b, r,\n name = paste(\"plot\", i, sep = \"-\")\n )\n\n # add background grob ----------------------------------\n if (!is.null(bg <- .subset2(grobs, \"bg\"))) {\n # we always add background in the beginning --------\n gt <- patch$add_background(\n gt, bg, t, l, b, r,\n name = paste(\"plot\", i, \"background\", sep = \"-\")\n )\n }\n\n # remove the grob from the patch, we wont' use it anymore\n patch$gt <- NULL\n }\n gt\n },\n attach_guide_list = function(self, guide_list, theme = self$theme,\n panel_pos = find_panel(gt),\n gt = self$gt) {\n if (length(guide_list)) {\n # https://github.com/tidyverse/ggplot2/blob/57ba97fa04dadc6fd73db1904e39a09d57a4fcbe/R/guides-.R#L512\n theme$legend.spacing <- theme$legend.spacing %||% unit(0.5, \"lines\")\n theme$legend.spacing.y <- calc_element(\"legend.spacing.y\", theme)\n theme$legend.spacing.x <- calc_element(\"legend.spacing.x\", theme)\n theme$legend.box.spacing <- calc_element(\n \"legend.box.spacing\", theme\n ) %||% unit(0.2, \"cm\")\n for (guide_pos in names(guide_list)) {\n gt <- self$attach_guides(\n guide_pos = guide_pos,\n guides = .subset2(guide_list, guide_pos),\n theme = theme, panel_pos = panel_pos,\n clip = \"off\", z = 4L, gt = gt\n )\n }\n }\n gt\n },\n #' @importFrom gtable gtable_width gtable_height\n #' @importFrom grid unit.c grobWidth grobHeight\n #' @importFrom ggplot2 find_panel zeroGrob\n attach_guides = function(self, guide_pos, guides, theme,\n panel_pos = find_panel(gt), ...,\n gt = self$gt) {\n guide_box <- assemble_guides(guides, guide_pos, theme = theme)\n name <- sprintf(\"guide-box-collected-%s\", guide_pos)\n if (guide_pos == \"inside\") {\n gt <- gtable_add_grob(\n x = gt,\n grobs = guide_box,\n t = panel_pos$t,\n l = panel_pos$l,\n b = panel_pos$b,\n r = panel_pos$r,\n name = name,\n ...\n )\n return(gt)\n }\n spacing <- .subset2(theme, \"legend.box.spacing\")\n if (guide_pos == \"left\") {\n if (is.gtable(guide_box)) {\n legend_width <- gtable_width(guide_box)\n widths <- unit.c(spacing, legend_width)\n } else {\n legend_width <- grobWidth(guide_box)\n widths <- unit(c(0, 0), \"mm\")\n }\n gt <- gtable_add_grob(\n x = gt,\n grobs = guide_box,\n t = panel_pos$t,\n l = panel_pos$l - 6L,\n b = panel_pos$b,\n name = name,\n ...\n )\n gt$widths[.subset2(panel_pos, \"l\") - 5:6] <- widths\n } else if (guide_pos == \"right\") {\n if (is.gtable(guide_box)) {\n legend_width <- gtable_width(guide_box)\n widths <- unit.c(spacing, legend_width)\n } else {\n legend_width <- grobWidth(guide_box)\n widths <- unit(c(0, 0), \"mm\")\n }\n gt <- gtable_add_grob(\n x = gt,\n grobs = guide_box,\n t = panel_pos$t,\n l = panel_pos$r + 6L,\n b = panel_pos$b,\n name = name,\n ...\n )\n gt$widths[.subset2(panel_pos, \"r\") + 5:6] <- widths\n } else if (guide_pos == \"bottom\") {\n location <- .subset2(theme, \"legend.location\") %||% \"panel\"\n place <- switch(location,\n panel = panel_pos,\n list(l = 1L, r = ncol(gt))\n )\n if (is.gtable(guide_box)) {\n legend_height <- gtable_height(guide_box)\n heights <- unit.c(spacing, legend_height)\n } else {\n legend_height <- grobHeight(guide_box)\n heights <- unit(c(0, 0), \"mm\")\n }\n gt <- gtable_add_grob(\n x = gt,\n grobs = guide_box,\n t = panel_pos$b + 6L,\n l = place$l,\n r = place$r,\n name = name,\n ...\n )\n gt$heights[.subset2(panel_pos, \"b\") + 5:6] <- heights\n } else if (guide_pos == \"top\") {\n location <- .subset2(theme, \"legend.location\") %||% \"panel\"\n place <- switch(location,\n panel = panel_pos,\n list(l = 1L, r = ncol(gt))\n )\n if (is.gtable(guide_box)) {\n legend_height <- gtable_height(guide_box)\n heights <- unit.c(spacing, legend_height)\n } else {\n legend_height <- grobHeight(guide_box)\n heights <- unit(c(0, 0), \"mm\")\n }\n gt <- gtable_add_grob(\n x = gt,\n grobs = guide_box,\n t = panel_pos$t - 6L,\n l = place$l,\n r = place$r,\n name = name,\n ...\n )\n gt$heights[.subset2(panel_pos, \"t\") - 5:6] <- heights\n }\n gt\n },\n\n #' @importFrom rlang is_empty\n free_border = function(self, borders, gt = self$gt,\n patches = self$patches) {\n gt <- self$recurse_lapply(\n function(patch, grob, t, l, b, r) {\n borders <- intersect(borders, c(t, l, b, r))\n if (is_empty(borders)) return(grob) # styler: off\n patch$free_border(borders = borders, gt = grob)\n },\n t = \"top\", l = \"left\", b = \"bottom\", r = \"right\",\n gt = gt, patches = patches\n )\n # for the collected guides, we should also liberate them\n guide_index <- sprintf(\"guide-box-collected-%s\", borders) %in%\n .subset2(.subset2(gt, \"layout\"), \"name\")\n if (any(guide_index)) {\n gt <- PatchGgplot$free_border(\n borders = borders[guide_index], gt = gt\n )\n }\n gt\n },\n align_free_border = function(self, borders,\n t = NULL, l = NULL, b = NULL, r = NULL,\n gt = self$gt, patches = self$patches) {\n gt <- self$recurse_lapply(\n function(patch, grob, t, l, b, r) {\n patch$align_free_border(\n borders = borders,\n t = t, l = l, b = b, r = r, gt = grob\n )\n },\n t = t, l = l, b = b, r = r,\n gt = gt, patches = patches\n )\n PatchGgplot$align_free_border(\n borders = borders,\n t = t, l = l, b = b, r = r, gt = gt\n )\n },\n\n #' @importFrom rlang is_empty\n free_lab = function(self, labs, gt = self$gt, patches = self$patches) {\n self$recurse_lapply(\n function(patch, grob, t, l, b, r) {\n labs <- intersect(labs, c(t, l, b, r))\n if (is_empty(labs)) return(grob) # styler: off\n patch$free_lab(labs = labs, gt = grob)\n },\n t = \"top\", l = \"left\", b = \"bottom\", r = \"right\",\n gt = gt, patches = patches\n )\n },\n # we apply function in each plot gtable in `gt`.\n #' @importFrom rlang is_empty\n recurse_lapply = function(self, .fn, t, l, b, r,\n gt = self$gt, patches = self$patches) {\n # if no plot provided, we'll do nothing\n if (is_empty(patches)) return(gt) # styler: off\n patch_index <- seq_along(patches)\n grobs <- .subset2(gt, \"grobs\")\n layout_index <- match(\n paste0(\"plot-\", patch_index),\n .subset2(.subset2(gt, \"layout\"), \"name\")\n )\n # For each grob, we reuse the method from the patch\n gt$grobs[layout_index] <- .mapply(function(layout_idx, patch_idx) {\n patch <- .subset2(patches, patch_idx)\n borders <- .subset2(patch, \"borders\")\n .fn(\n patch = patch,\n grob = .subset2(grobs, layout_idx),\n t = if (any(borders == \"top\")) t else NULL,\n l = if (any(borders == \"left\")) l else NULL,\n b = if (any(borders == \"bottom\")) b else NULL,\n r = if (any(borders == \"right\")) r else NULL\n )\n }, list(layout_idx = layout_index, patch_idx = patch_index), NULL)\n gt\n }\n)\n\n#' @importFrom grid convertHeight convertWidth unit\ntable_sizes <- function(sizes, area, ncol, nrow) {\n # `null` unit of the panel area will be converted into 0\n # we'll set the panel width and height afterward\n widths <- lapply(sizes, function(size) {\n convertWidth(.subset2(size, \"widths\"), \"mm\", valueOnly = TRUE)\n })\n widths <- vapply(seq_len(ncol * TABLE_COLS), function(i) {\n area_col <- (i - 1L) %/% TABLE_COLS + 1L\n col_loc <- i %% TABLE_COLS\n if (col_loc == 0L) col_loc <- TABLE_COLS\n area_side <- if (col_loc <= LEFT_BORDER + 1L) \"l\" else \"r\"\n idx <- field(area, area_side) == area_col\n if (any(idx)) {\n max(\n vapply(.subset(widths, idx), .subset, numeric(1L), col_loc),\n 0L\n )\n } else {\n 0L\n }\n }, numeric(1L), USE.NAMES = FALSE)\n heights <- lapply(sizes, function(size) {\n convertHeight(.subset2(size, \"heights\"), \"mm\", valueOnly = TRUE)\n })\n heights <- vapply(seq_len(nrow * TABLE_ROWS), function(i) {\n area_row <- recycle_each(i, TABLE_ROWS)\n row_loc <- recycle_whole(i, TABLE_ROWS)\n area_side <- if (row_loc <= TOP_BORDER + 1L) \"t\" else \"b\"\n idx <- field(area, area_side) == area_row\n if (any(idx)) {\n max(\n vapply(\n .subset(heights, idx), .subset, numeric(1L),\n row_loc,\n USE.NAMES = FALSE\n ),\n 0L\n )\n } else {\n 0L\n }\n }, numeric(1L), USE.NAMES = FALSE)\n list(widths = unit(widths, \"mm\"), heights = unit(heights, \"mm\"))\n}\n"], ["/ggalign/R/scheme-theme.R", "#' Plot default theme\n#'\n#' @description\n#' `r lifecycle::badge('experimental')`\n#'\n#' `scheme_theme()` serves as the default theme and will always be overridden by\n#' any `theme()` settings applied directly to the plot. The default theme\n#' (`scheme_theme()`) is applied first, followed by any specific `theme()`\n#' settings, even if `theme()` is added before `scheme_theme()`.\n#'\n#' @inherit ggplot2::theme\n#' @param ... A [`theme()`][ggplot2::theme] object or additional element\n#' specifications not part of base ggplot2. In general, these should also be\n#' defined in the `element tree` argument. [`Splicing`][rlang::splice] a list\n#' is also supported.\n#' @examples\n#' set.seed(123)\n#' small_mat <- matrix(rnorm(56), nrow = 8)\n#' ggheatmap(small_mat) +\n#' scheme_theme(plot.background = element_rect(fill = \"red\"))\n#'\n#' # `scheme_theme()` serves as the default theme and will always be\n#' # overridden by any `theme()` settings applied directly to the plot\n#' ggheatmap(small_mat) +\n#' theme(plot.background = element_rect(fill = \"blue\")) +\n#' scheme_theme(plot.background = element_rect(fill = \"red\"))\n#'\n#' @importFrom ggplot2 theme\n#' @importFrom rlang inject\n#' @export\nscheme_theme <- rlang::new_function(\n # We utilize editor completion by listing all `theme()` arguments here.\n # By placing `...` at the beginning, we can check if the first\n # following argument is a `theme()` object rather than individual theme\n # elements.\n c(\n rlang::exprs(... = ),\n .subset(\n rlang::fn_fmls(theme),\n vec_set_difference(names(rlang::fn_fmls(theme)), \"...\")\n )\n ),\n quote({\n elements <- ggfun(\"find_args\")(..., complete = NULL, validate = NULL)\n ans <- theme(!!!elements)\n th <- NULL\n for (i in seq_len(...length())) {\n if (inherits(t <- ...elt(i), \"theme\")) {\n th <- ggfun(\"add_theme\")(th, t)\n }\n }\n new_scheme_theme(ggfun(\"add_theme\")(th, ans))\n })\n)\n\n#' @importFrom ggplot2 theme\nnew_scheme_theme <- function(th = theme()) {\n # I don't know why, if I omit the `object = th` argument, it won't work\n UseMethod(\"new_scheme_theme\", th)\n}\n\n#' @importFrom rlang inject\n#' @export\nnew_scheme_theme.theme <- function(th = theme()) {\n attrs <- attributes(th)\n attrs <- vec_slice(\n attrs, vec_set_difference(names(attrs), c(\"names\", \"class\"))\n )\n inject(new_scheme(\n name = \"scheme_theme\", th, !!!attrs,\n class = c(\"scheme_theme\", class(th))\n ))\n}\n\n#' @export\nnew_scheme_theme.scheme_theme <- function(th = theme()) th\n\n###############################################################\n#' @export\nupdate_scheme.scheme_theme <- function(new, old, object_name) {\n ggfun(\"add_theme\")(old, new, object_name)\n}\n\n#' @export\ninherit_scheme.scheme_theme <- function(scheme, pscheme) {\n pscheme + scheme\n}\n\n#' @export\nplot_add_scheme.scheme_theme <- function(plot, scheme) {\n # setup plot theme\n plot$theme <- scheme + plot$theme\n plot\n}\n"], ["/ggalign/R/scheme-align.R", "#' Align Specifications in the Layout\n#'\n#' @description\n#' `r lifecycle::badge('experimental')`\n#'\n#' The `scheme_align()` function defines the align Specifications for plots.\n#'\n#' @param guides A string with one or more of `r oxford_and(c(.tlbr, \"i\"))`\n#' indicating which side of guide legends should be collected. Defaults to\n#' [`waiver()`][ggplot2::waiver()], which inherits from the parent layout. If no\n#' parent layout, all guides will be collected. If `NULL`, no guides will be\n#' collected.\n#'\n#' @param free_spaces A string with one or more of `r oxford_and(.tlbr)`\n#' indicating which border spaces should be removed. Defaults to\n#' [`waiver()`][ggplot2::waiver()], which inherits from the parent layout. If no\n#' parent, the default is `NULL`, meaning no spaces are removed.\n#'\n#' Usually you want to apply this with the whole layout, instead of individual\n#' plots.\n#'\n#' @param free_labs A string with one or more of `r oxford_and(.tlbr)`\n#' indicating which axis titles should be free from alignment. Defaults to\n#' [`waiver()`][ggplot2::waiver()], which inherits from the parent layout. If no\n#' parent layout, no axis titles will be aligned. If `NULL`, all axis titles\n#' will be aligned.\n#'\n#' @return A `scheme_align` object.\n#' @examples\n#' set.seed(123)\n#' mat <- matrix(rnorm(72), nrow = 8)\n#' # used in the layout, define the default action for all plots in the layout\n#' ggheatmap(mat) -\n#' scheme_align(guides = NULL) +\n#' anno_right() +\n#' align_dendro(aes(color = branch), k = 3)\n#'\n#' # You can also add it for a single plot\n#' ggheatmap(mat) -\n#' # for all plots in the layout, we default won't collect any guide legends\n#' scheme_align(guides = NULL) +\n#' # for the heatmap body, we collect guide legends in the right\n#' # note, the guide legends will be collected to the right side of the\n#' # layout which will overlap the legends in the right annotation\n#' scheme_align(guides = \"r\") +\n#' anno_right() +\n#' align_dendro(aes(color = branch), k = 3)\n#'\n#' # to avoid overlapping, we can also collect the guide legends in the\n#' # right annotation\n#' ggheatmap(mat) -\n#' scheme_align(guides = NULL) +\n#' scheme_align(guides = \"r\") +\n#' anno_right() +\n#' align_dendro(aes(color = branch), k = 3) +\n#' scheme_align(guides = \"r\")\n#' @export\nscheme_align <- function(guides = NA, free_spaces = NA, free_labs = NA) {\n if (!identical(guides, NA)) assert_layout_guides(guides)\n if (!identical(free_spaces, NA)) assert_layout_position(free_spaces)\n if (!identical(free_labs, NA)) assert_layout_position(free_labs)\n new_scheme_align(\n free_spaces = free_spaces,\n free_labs = free_labs,\n guides = guides\n )\n}\n\nnew_scheme_align <- function(guides = waiver(), free_spaces = waiver(),\n free_labs = waiver()) {\n new_scheme(\n name = \"scheme_align\",\n list(free_spaces = free_spaces, free_labs = free_labs, guides = guides),\n class = \"scheme_align\"\n )\n}\n\n#' @importFrom utils modifyList\n#' @export\nupdate_scheme.scheme_align <- function(new, old, object_name) {\n modifyList(old,\n new[!vapply(new, identical, logical(1L), y = NA, USE.NAMES = FALSE)],\n keep.null = TRUE\n )\n}\n\n#' @export\ninherit_scheme.scheme_align <- function(scheme, pscheme) {\n # `align_plots` control how to inherit `guides` from the layout\n # we don't need to inherit it here\n scheme[\"free_spaces\"] <- list(.subset2(scheme, \"free_spaces\") %|w|%\n .subset2(pscheme, \"free_spaces\"))\n scheme[\"free_labs\"] <- list(.subset2(scheme, \"free_labs\") %|w|%\n .subset2(pscheme, \"free_labs\"))\n scheme\n}\n\n#' @param theme Additional default theme elements to be added for the plot\n#' @noRd\nplot_add_scheme.scheme_align <- function(plot, scheme) {\n if (!is.waive(free_guides <- .subset2(scheme, \"guides\"))) {\n plot <- free_guide(plot, free_guides)\n }\n # by default, we'll attach all labs to the axis\n if (!is.null(free_labs <- .subset2(scheme, \"free_labs\") %|w|% \"tlbr\")) {\n plot <- free_lab(plot, free_labs)\n }\n # by default, we won't remove any spaces\n if (!is.null(free_spaces <- .subset2(scheme, \"free_spaces\") %|w|% NULL)) {\n plot <- free_space(free_border(plot, free_spaces), free_spaces)\n }\n plot\n}\n"], ["/ggalign/R/layout-chain-circle-build.R", "#' @export\nggalign_build.CircleLayout <- function(x) {\n x <- default_layout(x)\n circle_build(x)\n}\n\n#' @importFrom utils packageVersion\n#' @importFrom ggplot2 find_panel calc_element ggproto ggplotGrob theme\n#' @importFrom gtable gtable_add_grob gtable_add_padding is.gtable\n#' @importFrom grid unit viewport editGrob\n#' @importFrom rlang is_empty arg_match0\ncircle_build <- function(circle, schemes = NULL, theme = NULL) {\n schemes <- inherit_parent_layout_schemes(circle, schemes)\n theme <- inherit_parent_layout_theme(circle, theme)\n # for empty plot\n base <- ggplot() +\n theme +\n ggplot2::labs(\n title = .subset2(circle@titles, \"title\"),\n subtitle = .subset2(circle@titles, \"subtitle\"),\n caption = .subset2(circle@titles, \"caption\")\n )\n if (is_empty(plot_list <- circle@plot_list)) {\n return(ggplotGrob(base))\n }\n\n # we remove the plot without actual plot area\n keep <- vapply(plot_list, function(plot) {\n !is.null(plot@plot)\n }, logical(1L), USE.NAMES = FALSE)\n plot_list <- .subset(plot_list, keep)\n if (is_empty(plot_list)) return(ggplotGrob(base)) # styler: off\n\n # we reorder the plots based on the `order` slot\n plot_order <- vapply(plot_list, function(plot) {\n .subset2(plot@active, \"order\")\n }, integer(1L), USE.NAMES = FALSE)\n plot_list <- .subset(plot_list, make_order(plot_order))\n\n # plot coordinate\n if (is.null(input_radial <- circle@radial)) {\n radial <- coord_circle(theta = \"x\", r.axis.inside = TRUE)\n } else {\n radial <- ggproto(NULL, input_radial, theta = \"x\", r_axis_inside = TRUE)\n }\n\n sizes <- vapply(plot_list, function(plot) {\n # for circular layout, we only support relative size\n if (is.na(size <- as.numeric(plot@size))) {\n size <- 1\n }\n size\n }, numeric(1L), USE.NAMES = FALSE)\n\n # For each plot track, relative to the total radius (1):\n # 1. total radius: 1\n # 2. total radius for the plot area (for each plot track): 1 - inner_radius\n if (inherits(radial, \"CoordCircle\")) {\n inner_radius <- radial$inner_radius[1L] / 0.5\n outer_radius <- radial$inner_radius[2L] / 0.5\n } else {\n # For `CoordRadial`\n # `0.4` is coord_radial used for scale size in ggplot2 to add extra\n # spaces for axis labels\n # https://github.com/tidyverse/ggplot2/issues/6284\n inner_radius <- radial$inner_radius[1L] / 0.4\n outer_radius <- radial$inner_radius[2L] / 0.4\n }\n plot_track <- sizes / sum(sizes) * (outer_radius - inner_radius)\n\n # For each plot, the plot size is calculated by adding the space for the\n # inner radius of each track.\n N <- length(plot_list)\n index <- seq_len(N)\n direction <- circle@direction\n if (identical(direction, \"outward\")) {\n plot_sizes <- inner_radius + cumsum(plot_track)\n } else {\n plot_sizes <- outer_radius -\n cumsum(c(0, utils::head(plot_track, -1L)))\n # The plots are always build outward, so the order is reversed.\n index <- rev(index)\n }\n\n # For each plot, the inner radius is calculated as the difference between\n # the plot size and its track size.\n plot_inner <- plot_sizes - plot_track\n guides <- vector(\"list\", N)\n plot_table <- NULL\n design <- setup_design(circle@design)\n for (i in index) {\n plot_size <- plot_sizes[[i]]\n plot <- .subset2(plot_list, i)\n craftsman <- plot@craftsman # `Craftsman` object\n plot_schemes <- inherit_schemes(plot@schemes, schemes)\n # the actual plot\n plot <- plot@plot\n\n # we always use `null` facet\n # we won't respect `free_facet` and `free_coord`\n plot_coord <- gguse_circle_coord(\n plot,\n coord = radial,\n # https://github.com/tidyverse/ggplot2/issues/6284\n # Use `0.5` to remove the extra spaces for axis label\n inner_radius = c(\n plot_inner[[i]] / plot_size,\n # for the outmost plot, we respect the outer radius defined by\n # the users, for others, we alway use 1 to remove any spacing\n # between two tracks\n if (i == N) outer_radius else 1\n ) * 0.5,\n layout_name = craftsman$layout_name\n )\n if (!craftsman$free_facet) {\n if (is_discrete_design(design)) {\n if (nlevels(.subset2(design, \"panel\")) > 1L) {\n plot <- plot + facet_sector(\n ggplot2::vars(.data$.panel),\n sector_spacing = circle@sector_spacing %||% (pi / 180),\n drop = FALSE\n )\n } else {\n plot <- ggmelt_facet(plot, ggplot2::facet_null())\n }\n } else {\n if (inherits(plot$facet, \"FacetSector\")) {\n plot <- ggfacet_modify(plot,\n sector_spacing = circle@sector_spacing %||% (pi / 180),\n drop = FALSE\n )\n } else {\n plot <- ggmelt_facet(plot, ggplot2::facet_null())\n }\n }\n }\n plot$coordinates <- plot_coord\n\n # set limits and default scales\n if (!craftsman$free_limits) {\n plot <- plot + ggalign_design(\n x = design,\n xlabels = .subset(craftsman$labels, .subset2(design, \"index\"))\n )\n }\n\n # let `Craftsman` add other components\n plot <- craftsman$build_plot(plot, design = design)\n plot <- craftsman$finish_plot(\n plot,\n schemes = plot_schemes, theme = theme\n )\n plot <- plot + ggplot2::labs(x = NULL, y = NULL) +\n theme(panel.border = element_blank())\n plot <- chain_decorate(circle, plot)\n\n # copied from `ggplot2:::ggplot_gtable`\n data <- ggplot2::ggplot_build(plot)\n plot <- data$plot\n plot_layout <- data$layout\n data <- data$data\n plot_theme <- complete_theme(plot$theme)\n\n geom_grobs <- ggfun(\"by_layer\")(\n function(l, d) l$draw_geom(d, plot_layout),\n plot$layers, data,\n \"converting geom to grob\"\n )\n gt <- plot_layout$render(geom_grobs, data, plot_theme, plot$labels)\n\n # for each inner gtable, we insert it to the panel area of the\n # outter gtable\n #\n # For bbox, `ggplot2::polar_bbox` always take (0.5, 0.5) as origin\n bbox <- ggfun(\"polar_bbox\")(\n plot_layout$coord$arc, margin = c(0, 0, 0, 0),\n inner_radius = plot_layout$coord$inner_radius\n )\n origin <- c(\n scales::rescale(0.5, from = bbox$x),\n scales::rescale(0.5, from = bbox$y)\n )\n spacing <- calc_element(\"panel.spacing.r\", plot_theme)\n\n if (is.null(plot_table)) {\n plot_table <- gt\n } else {\n # define the panel size of the inner track\n rescale_factor <- last_plot_size / plot_size\n\n # the spacer between two plots\n if (identical(direction, \"outward\")) {\n spacer <- last_spacing\n } else {\n spacer <- spacing\n }\n if (inherits(spacer, \"element_blank\") || is.null(spacer)) {\n spacer <- unit(0, \"mm\")\n }\n plot_table <- editGrob(plot_table, vp = viewport(\n width = unit(rescale_factor, \"npc\") - spacer,\n height = unit(rescale_factor, \"npc\") - spacer,\n x = origin[1L], y = origin[2L], just = just,\n default.units = \"native\", clip = \"off\"\n ))\n\n # add the inner track to the panel area of the outter track\n panel_loc <- find_panel(gt)\n plot_table <- gtable_add_grob(\n gt, plot_table,\n t = .subset2(panel_loc, \"t\"),\n l = .subset2(panel_loc, \"l\"),\n b = .subset2(panel_loc, \"b\"),\n r = .subset2(panel_loc, \"r\"),\n name = \"inner-track\"\n )\n }\n\n # build legends\n guides[i] <- list(plot$guides$assemble(plot_theme))\n\n # assign value for next loop\n just <- origin\n last_plot_size <- plot_size # the last plot panel size\n last_spacing <- spacing\n }\n\n # attach the guide legends\n guides <- collect_guides_list(guides, zeroGrob())\n theme$legend.spacing <- theme$legend.spacing %||% unit(0.5, \"lines\")\n theme$legend.spacing.y <- calc_element(\"legend.spacing.y\", theme)\n theme$legend.spacing.x <- calc_element(\"legend.spacing.x\", theme)\n theme$legend.box.spacing <- calc_element(\n \"legend.box.spacing\", theme\n ) %||% unit(0.2, \"cm\")\n legend_box <- .mapply(\n function(guides, guide_pos) assemble_guides(guides, guide_pos, theme),\n list(guides = guides, guide_pos = names(guides)),\n NULL\n )\n names(legend_box) <- names(guides)\n plot_table <- ggfun(\"table_add_legends\")(plot_table, legend_box, theme)\n\n # Title\n title <- element_render(\n theme, \"plot.title\", .subset2(circle@titles, \"title\"),\n margin_y = TRUE, margin_x = TRUE\n )\n title_height <- grobHeight(title)\n\n # Subtitle\n subtitle <- element_render(\n theme, \"plot.subtitle\", .subset2(circle@titles, \"subtitle\"),\n margin_y = TRUE, margin_x = TRUE\n )\n subtitle_height <- grobHeight(subtitle)\n\n # whole plot annotation\n caption <- element_render(\n theme, \"plot.caption\", .subset2(circle@titles, \"caption\"),\n margin_y = TRUE, margin_x = TRUE\n )\n caption_height <- grobHeight(caption)\n\n # positioning of title and subtitle is governed by plot.title.position\n # positioning of caption is governed by plot.caption.position\n # \"panel\" means align to the panel(s)\n # \"plot\" means align to the entire plot (except margins and tag)\n title_pos <- arg_match0(\n theme$plot.title.position %||% \"panel\",\n c(\"panel\", \"plot\"),\n arg_nm = \"plot.title.position\",\n error_call = quote(theme())\n )\n\n caption_pos <- arg_match0(\n theme$plot.caption.position %||% \"panel\",\n values = c(\"panel\", \"plot\"),\n arg_nm = \"plot.caption.position\",\n error_call = quote(theme())\n )\n\n pans <- plot_table$layout[\n grepl(\"^panel\", plot_table$layout$name), ,\n drop = FALSE\n ]\n if (title_pos == \"panel\") {\n title_l <- min(pans$l)\n title_r <- max(pans$r)\n } else {\n title_l <- 1\n title_r <- ncol(plot_table)\n }\n if (caption_pos == \"panel\") {\n caption_l <- min(pans$l)\n caption_r <- max(pans$r)\n } else {\n caption_l <- 1\n caption_r <- ncol(plot_table)\n }\n\n plot_table <- gtable_add_rows(plot_table, subtitle_height, pos = 0)\n plot_table <- gtable_add_grob(plot_table, subtitle,\n name = \"subtitle\",\n t = 1, b = 1, l = title_l, r = title_r, clip = \"off\"\n )\n\n plot_table <- gtable_add_rows(plot_table, title_height, pos = 0)\n plot_table <- gtable_add_grob(plot_table, title,\n name = \"title\",\n t = 1, b = 1, l = title_l, r = title_r, clip = \"off\"\n )\n\n plot_table <- gtable_add_rows(plot_table, caption_height, pos = -1)\n plot_table <- gtable_add_grob(plot_table, caption,\n name = \"caption\",\n t = -1, b = -1, l = caption_l, r = caption_r, clip = \"off\"\n )\n plot_table <- ggfun(\"table_add_tag\")(plot_table, NULL, theme)\n\n # Margins\n plot_margin <- calc_element(\"plot.margin\", theme) %||% margin()\n plot_table <- gtable_add_padding(plot_table, plot_margin)\n\n if (inherits(theme$plot.background, \"element\")) {\n plot_table <- gtable_add_grob(plot_table,\n element_render(theme, \"plot.background\"),\n t = 1, l = 1, b = -1, r = -1, name = \"background\", z = -Inf\n )\n plot_table$layout <- plot_table$layout[\n c(nrow(plot_table$layout), 1:(nrow(plot_table$layout) - 1)),\n ]\n plot_table$grobs <- plot_table$grobs[\n c(nrow(plot_table$layout), 1:(nrow(plot_table$layout) - 1))\n ]\n }\n\n # add alt-text as attribute\n # attr(plot_table, \"alt-label\") <- plot$labels$alt\n strip_pos <- find_strip_pos(plot_table)\n\n # always add strips columns and/or rows\n plot_table <- add_strips(plot_table, strip_pos)\n setup_patch_titles(plot_table, patch_titles = list(\n top = NULL, left = NULL, bottom = NULL, right = NULL\n ), theme = theme)\n}\n"], ["/ggalign/R/alignpatch-guides.R", "#' Returns a list of guide boxes collected from all plots.\n#' Each element in the list corresponds to a specific position, containing a\n#' sub-list of guide boxes, where each guide box represents a single plot.\n#' @noRd\ncollect_guides_list <- function(guides_list, empty = NULL) {\n ans <- lapply(c(.TLBR, \"inside\"), function(guide_pos) {\n guides <- lapply(guides_list, function(guides) {\n # IF no guide-box, a single `zeroGrob()` will be given\n # here, we regard each position is a `zeroGrob()`\n if (is_null_grob(guides)) return(list(guides)) # styler: off\n o <- .subset2(guides, guide_pos)\n # A guide-box should be a `zeroGrob()` or a `gtable` object\n if (maybe_guide_box(o)) {\n return(list(o))\n }\n # For other grobs, we just removed them silently\n if (is.grob(o)) {\n list(NULL)\n } else if (is.list(o)) {\n o[\n vapply(o, maybe_guide_box, # styler: off\n logical(1L), USE.NAMES = FALSE # styler: off\n )\n ]\n } else {\n list(NULL)\n }\n })\n guides <- unlist(guides, FALSE, FALSE)\n guides <- guides[\n !vapply(guides, is.null, logical(1L), USE.NAMES = FALSE)\n ]\n if (is_empty(guides)) empty else guides\n })\n names(ans) <- c(.TLBR, \"inside\")\n ans[!vapply(ans, is.null, logical(1L), USE.NAMES = FALSE)]\n}\n\n#' @param guides A list of guide-box\n#' @importFrom ggplot2 zeroGrob\n#' @importFrom gtable gtable gtable_add_grob\n#' @noRd\nassemble_guides <- function(guides, guide_pos, theme) {\n if (guide_pos == \"inside\") {\n # for `zeroGrob()`, it doesn't record the `viewport` information\n # used to identify the inside guide groups, we just removed them\n guides <- guides[\n !vapply(guides, is_null_grob, logical(1L), USE.NAMES = FALSE)\n ]\n if (is_empty(guides)) {\n guide_box <- zeroGrob()\n } else {\n positions <- justs <- vector(\"list\", length(guides))\n for (i in seq_along(guides)) {\n guide <- .subset2(guides, i)\n # for inside guides, it may contain multiple guide-box\n is_box <- grepl(\"guide-box-inside\", guide$layout$name)\n if (any(is_box)) {\n guides[[i]] <- guide$grobs[is_box]\n } else {\n guides[[i]] <- list(guide)\n }\n positions[[i]] <- lapply(guides[[i]], function(guide_box) {\n unit.c(guide_box$vp$x, guide_box$vp$y)\n })\n justs[[i]] <- lapply(guides[[i]], function(guide_box) {\n guide_box$vp$justification\n })\n }\n guides <- unlist(guides, FALSE, FALSE)\n groups <- data_frame0(\n positions = unlist(positions, FALSE, FALSE),\n justs = unlist(justs, FALSE, FALSE)\n )\n groups <- vec_group_loc(groups)\n index <- vec_seq_along(groups)\n\n # pakcage each group into a guide-box\n box_list <- vector(\"list\", vec_size(index))\n for (i in index) {\n box_list[[i]] <- assemble_box(\n guides[groups$loc[[i]]], guide_pos,\n theme = theme + theme(\n legend.position.inside = groups$key$positions[[i]],\n legend.justification.inside = groups$key$justs[[i]]\n )\n )\n }\n if (vec_size(box_list) > 1L) {\n guide_box <- gtable(unit(1L, \"npc\"), unit(1L, \"npc\"))\n guide_box <- gtable_add_grob(\n guide_box, box_list,\n t = 1L, l = 1L, clip = \"off\",\n name = paste(\"guide-box-collected-inside\", index, sep = \"-\")\n )\n } else {\n guide_box <- box_list[[1L]]\n }\n }\n } else {\n guide_box <- assemble_box(guides, guide_pos, theme = theme)\n }\n guide_box\n}\n\n#' @param guides A list of guide-box\n#' @importFrom rlang try_fetch\n#' @importFrom ggplot2 zeroGrob\n#' @noRd\nassemble_box <- function(guides, guide_pos, theme) {\n guides <- guides[\n !vapply(guides, is_null_grob, logical(1L), USE.NAMES = FALSE)\n ]\n if (is_empty(guides)) {\n zeroGrob()\n } else {\n # Remove the guide box background\n grobs <- lapply(guides, function(box) {\n box$grobs[grepl(\"guides\", box$layout$name)]\n })\n grobs <- unlist(grobs, FALSE, FALSE)\n\n # remove duplicated guides\n grobs <- collapse_guides(grobs)\n if (is_empty(grobs)) return(zeroGrob()) # styler: off\n # for every position, collect all individual guides and arrange them\n # into a guide box which will be inserted into the main gtable\n package_box <- try_fetch(\n .subset2(ggfun(\"Guides\"), \"package_box\"),\n error = function(cnd) package_box\n )\n package_box(grobs, guide_pos, theme)\n }\n}\n\n# The following code was used in earlier versions of ggplot2; \n# coverage is not calculated here.\n# nocov start\n#' @importFrom gtable gtable_add_rows gtable_add_cols\n#' @importFrom ggplot2 calc_element\n#' @importFrom grid valid.just editGrob viewport\npackage_box <- function(guides, guide_pos, theme) {\n theme <- complete_guide_theme(guide_pos, theme)\n guides <- guides_build(guides, theme)\n\n # Set the justification of the legend box\n # First value is xjust, second value is yjust\n just <- valid.just(calc_element(\"legend.justification\", theme))\n xjust <- just[1L]\n yjust <- just[2L]\n guides <- editGrob(guides,\n vp = viewport(x = xjust, y = yjust, just = c(xjust, yjust))\n )\n guides <- gtable_add_rows(guides, unit(yjust, \"null\"))\n guides <- gtable_add_rows(guides, unit(1L - yjust, \"null\"), 0L)\n guides <- gtable_add_cols(guides, unit(xjust, \"null\"), 0L)\n guides <- gtable_add_cols(guides, unit(1L - xjust, \"null\"))\n guides\n}\n\n#' @importFrom gtable gtable_width gtable_height gtable gtable_add_grob\n#' @importFrom grid editGrob heightDetails widthDetails valid.just unit.c unit\n#' @importFrom ggplot2 margin element_grob element_blank calc_element element_render\nguides_build <- function(guides, theme) {\n legend.spacing.y <- .subset2(theme, \"legend.spacing.y\")\n legend.spacing.x <- .subset2(theme, \"legend.spacing.x\")\n legend.box.margin <- calc_element(\"legend.box.margin\", theme) %||%\n margin()\n widths <- do.call(`unit.c`, lapply(guides, gtable_width))\n heights <- do.call(`unit.c`, lapply(guides, gtable_height))\n\n just <- valid.just(.subset2(theme, \"legend.box.just\"))\n xjust <- just[1]\n yjust <- just[2]\n vert <- identical(.subset2(theme, \"legend.box\"), \"horizontal\")\n guides <- lapply(guides, function(g) {\n editGrob(g, vp = viewport(\n x = xjust, y = yjust, just = c(xjust, yjust),\n height = if (vert) heightDetails(g) else 1,\n width = if (!vert) widthDetails(g) else 1\n ))\n })\n guide_ind <- seq(by = 2, length.out = length(guides))\n sep_ind <- seq(2, by = 2, length.out = length(guides) - 1)\n if (vert) {\n heights <- max(heights)\n if (length(widths) != 1) {\n w <- unit(rep_len(0, length(widths) * 2 - 1), \"mm\")\n w[guide_ind] <- widths\n w[sep_ind] <- legend.spacing.x\n widths <- w\n }\n } else {\n widths <- max(widths)\n if (length(heights) != 1) {\n h <- unit(rep_len(0, length(heights) * 2 - 1), \"mm\")\n h[guide_ind] <- heights\n h[sep_ind] <- legend.spacing.y\n heights <- h\n }\n }\n widths <- unit.c(legend.box.margin[4], widths, legend.box.margin[2])\n heights <- unit.c(legend.box.margin[1], heights, legend.box.margin[3])\n guides <- gtable_add_grob(\n gtable(widths, heights, name = \"guide-box\"),\n guides,\n t = 1 + if (!vert) guide_ind else 1,\n l = 1 + if (vert) guide_ind else 1,\n name = \"guides\"\n )\n gtable_add_grob(\n guides,\n element_render(theme, \"legend.box.background\"),\n t = 1, l = 1, b = -1, r = -1,\n z = -Inf, clip = \"off\", name = \"legend.box.background\"\n )\n}\n\n#' @importFrom ggplot2 calc_element\ncomplete_guide_theme <- function(guide_pos, theme) {\n if (guide_pos %in% c(\"top\", \"bottom\")) {\n theme$legend.box <- calc_element(\"legend.box\", theme) %||% \"horizontal\"\n theme$legend.direction <- calc_element(\"legend.direction\", theme) %||%\n \"horizontal\"\n theme$legend.box.just <- calc_element(\"legend.box.just\", theme) %||%\n c(\"center\", \"top\")\n } else {\n theme$legend.box <- calc_element(\"legend.box\", theme) %||% \"vertical\"\n theme$legend.direction <- calc_element(\"legend.direction\", theme) %||%\n \"vertical\"\n theme$legend.box.just <- calc_element(\"legend.box.just\", theme) %||%\n c(\"left\", \"top\")\n }\n theme\n}\n# nocov end\n\n################################################################ 3\n# Copied from patchwork\ncollapse_guides <- function(guides) {\n unnamed <- lapply(guides, unname_grob)\n for (i in rev(seq_along(unnamed)[-1])) {\n for (j in seq_len(i - 1)) {\n if (isTRUE(all.equal(unnamed[[i]], unnamed[[j]],\n check.names = FALSE, check.attributes = FALSE\n ))) {\n guides[i] <- NULL\n break\n }\n }\n }\n guides\n}\n\n#' @importFrom grid is.unit absolute.size\nunname_vp <- function(x) {\n if (inherits(x, \"vpTree\")) {\n x$parent <- unname_vp(x$parent)\n x$children <- lapply(x$children, unname_vp)\n } else if (inherits(x, \"viewport\")) {\n x$name <- \"\"\n if (!is.null(x$layout$widths)) {\n x$layout$widths <- absolute.size(x$layout$widths)\n }\n if (!is.null(x$layout$heights)) {\n x$layout$heights <- absolute.size(x$layout$heights)\n }\n }\n unit_elements <- vapply(x, is.unit, logical(1), USE.NAMES = FALSE)\n x[unit_elements] <- lapply(.subset(x, unit_elements), absolute.size)\n x\n}\n\n#' @importFrom grid is.grob is.unit absolute.size\n#' @importFrom gtable is.gtable\nunname_grob <- function(x) {\n if (is.gtable(x)) {\n x$name <- \"\"\n x$rownames <- NULL\n x$vp <- unname_vp(x$vp)\n names(x$grobs) <- NULL\n x$grobs <- lapply(x$grobs, unname_grob)\n } else if (is.grob(x)) {\n x$name <- \"\"\n x$vp <- unname_vp(x$vp)\n x$children <- unname(lapply(x$children, unname_grob))\n x$childrenOrder <- rep_len(\"\", length(x$childrenOrder))\n }\n unit_elements <- vapply(x, is.unit, logical(1), USE.NAMES = FALSE)\n x[unit_elements] <- lapply(.subset(x, unit_elements), absolute.size)\n x\n}\n"], ["/ggalign/R/ggplot-facet-sector.R", "#' Polar coordinates with Facet support\n#'\n#' Draw each panel in a sector of the polar coordinate system. If\n#' `facet_sector()` is used in a ggplot, the coordinate system must be created\n#' with [`coord_circle()`] or [`coord_radial()`][ggplot2::coord_radial].\n#'\n#' @inheritParams ggplot2::facet_wrap\n#' @param sector_spacing The size of spacing between different panel. A numeric\n#' of the radians or a [`rel()`][ggplot2::rel] object.\n#' @param radial `r lifecycle::badge(\"deprecated\")` Please add the coordinate\n#' system directly to the ggplot instead.\n#' @param spacing_theta `r lifecycle::badge(\"deprecated\")` Please use\n#' `sector_spacing` instead.\n#' @examples\n#' ggplot(mtcars, aes(disp, mpg)) +\n#' geom_point() +\n#' facet_sector(vars(cyl)) +\n#' coord_circle(\n#' start = -0.4 * pi, end = 0.4 * pi, inner.radius = 0.3,\n#' outer.radius = 0.8, expand = TRUE\n#' )\n#' @importFrom ggplot2 ggproto\n#' @export\nfacet_sector <- function(facets, sector_spacing = pi / 180, drop = TRUE,\n radial = deprecated(), spacing_theta = deprecated()) {\n if (packageVersion(\"ggplot2\") > \"3.5.2\") {\n facets <- ggfun(\"compact_facets\")(facets)\n } else {\n facets <- ggfun(\"wrap_as_facets_list\")(facets)\n }\n if (inherits(sector_spacing, \"CoordRadial\") ||\n lifecycle::is_present(radial)) {\n lifecycle::deprecate_stop(\n \"1.0.2\",\n \"facet_sector(radial = )\",\n details = \"Please add the coordinate to the ggplot instead\"\n )\n }\n if (lifecycle::is_present(spacing_theta)) {\n lifecycle::deprecate_warn(\n \"1.0.2\",\n \"facet_sector(spacing_theta = )\",\n \"facet_sector(sector_spacing = )\"\n )\n sector_spacing <- spacing_theta\n }\n\n # @param strip.position By default, the labels are displayed on the\n # `\"outer\"` of the plot. Allowed values are `r oxford_or(c(\"outer\",\n # \"inner\"))`\n # strip.position <- arg_match0(strip.position, c(\"outer\", \"inner\"))\n # strip.position <- switch(strip.position,\n # outer = \"top\",\n # inner = \"bottom\"\n # )\n # labeller <- ggfun(\"fix_labeller\")(labeller)\n assert_bool(drop)\n\n # TO-DO: remove this line and update to\n # the next version of ggplot2 (> 3.5.2)\n if (packageVersion(\"ggplot2\") > \"3.5.2\") {\n dir <- \"lt\"\n } else {\n dir <- \"h\"\n }\n ggproto(\n NULL,\n FacetSector,\n sector_spacing = sector_spacing,\n params = list(\n facets = facets,\n free = list(x = TRUE, y = FALSE),\n strip.position = \"top\",\n drop = drop, ncol = NULL, nrow = 1L,\n space_free = list(x = TRUE, y = FALSE),\n labeller = ggplot2::label_value, dir = dir,\n draw_axes = list(x = TRUE, y = FALSE),\n axis_labels = list(x = TRUE, y = FALSE),\n as.table = TRUE\n )\n )\n}\n\n#' @importFrom ggplot2 ggplot_add\n#' @export\nggplot_add.FacetSector <- function(object, plot, object_name, ...) {\n plot <- NextMethod()\n if (!inherits(plot, \"ggalign_facet_sector_plot\")) {\n plot <- add_class(plot, \"ggalign_facet_sector_plot\")\n }\n plot\n}\n\n#' @importFrom ggplot2 ggplot_build ggproto ggproto_parent\n#' @export\nggplot_build.ggalign_facet_sector_plot <- function(plot, ...) {\n if (inherits(plot$facet, \"FacetSector\")) {\n if (!inherits(plot$coordinates, \"CoordRadial\")) {\n if (!isTRUE(plot$coordinates$default)) {\n cli_abort(c(\n paste(\n \"Cannot use {.fn {snake_class(plot$coordinates)}}\",\n \"coordinate with {.fn facet_sector}\"\n ),\n i = \"Please use {.fn coord_circle}/{.fn coord_radial} instead\"\n ))\n }\n plot$coordinates <- coord_circle()\n }\n ParentLayout <- plot$layout\n plot$layout <- ggproto(\n \"FacetSectorLayout\", ParentLayout,\n setup_panel_params = function(self) {\n ggproto_parent(ParentLayout, self)$setup_panel_params()\n if (is.null(ggplot2::Facet$setup_panel_params) &&\n !is.null(self$facet$setup_panel_params)) {\n self$panel_params <- self$facet$setup_panel_params(\n self$panel_params, self$coord\n )\n }\n invisible()\n }\n )\n }\n NextMethod()\n}\n\n#' @importFrom rlang inject\n#' @importFrom grid gTree editGrob viewport\n#' @importFrom ggplot2 ggproto ggproto_parent\nFacetSector <- ggproto(\n \"FacetSector\", ggplot2::FacetWrap,\n setup_panel_params = function(self, panel_params, coord, ...) {\n # total theta for panel area and panel spacing\n arc_theta <- abs(diff(coord$arc))\n sector_spacing <- self$sector_spacing\n if (inherits(sector_spacing, \"rel\")) {\n sector_spacing <- sector_spacing * arc_theta\n }\n panel_weights <- vapply(panel_params, function(panel_param) {\n abs(diff(.subset2(panel_param, \"theta.range\")))\n }, numeric(1L), USE.NAMES = FALSE)\n\n # total theta for panel area\n panel_theta <- arc_theta -\n # substract the number of spacing between panels\n sector_spacing *\n # for the whole circle, arc_theta == 2 * pi\n # there should be as many panels as the number of panel spacing\n if (abs(arc_theta - 2 * pi) < .Machine$double.eps^0.5) {\n length(panel_weights)\n } else {\n length(panel_weights) - 1L\n }\n if (panel_theta <= 0L) {\n cli_abort(\"No panel area, try to reduce {.arg sector_spacing}\")\n }\n\n # re-distribute the arc for each panel\n panel_point <- vec_interleave(\n panel_theta * panel_weights / sum(panel_weights),\n rep_len(sector_spacing, length(panel_weights))\n )\n panel_point <- cumsum(c(coord$arc[1L], utils::head(panel_point, -1L)))\n for (i in seq_along(panel_params)) {\n panel_param <- .subset2(panel_params, i)\n panel_param$arc <- panel_point[i * 2L - 1:0]\n panel_param$bbox <- ggfun(\"polar_bbox\")(\n panel_param$arc, margin = c(0, 0, 0, 0),\n inner_radius = coord$inner_radius\n )\n panel_params[[i]] <- panel_param\n }\n panel_params\n },\n draw_panels = function(self, panels, layout, x_scales, y_scales, ranges,\n coord, data, theme, params) {\n # merge different sector into one panel\n bbox <- ggfun(\"polar_bbox\")(\n coord$arc, margin = c(0, 0, 0, 0),\n inner_radius = coord$inner_radius\n )\n for (i in seq_along(panels)) {\n panel_param <- .subset2(ranges, i)\n vp <- list(\n x = scales::rescale(panel_param$bbox$x, from = bbox$x),\n y = scales::rescale(panel_param$bbox$y, from = bbox$y)\n )\n panels[[i]] <- editGrob(\n .subset2(panels, i),\n vp = viewport(\n x = vp$x[1L], y = vp$y[1L],\n width = abs(diff(vp$x)),\n height = abs(diff(vp$y)),\n just = c(0, 0),\n clip = \"off\",\n default.units = \"native\"\n )\n )\n }\n panels <- gTree(children = inject(gList(!!!panels)))\n ranges <- lapply(ranges, function(panel_param) {\n panel_param$arc <- coord$arc\n panel_param$bbox <- bbox\n panel_param\n })\n ggplot2::FacetNull$draw_panels(\n panels = list(panels),\n layout = layout, x_scales = x_scales, y_scales = y_scales,\n ranges = ranges, coord = coord, data = data,\n theme = theme, params = params\n )\n }\n)\n"], ["/ggalign/R/ggplot-geom-subrect.R", "#' Subdivide Rectangles\n#'\n#' @description\n#' These geoms subdivide rectangles with shared borders into a grid. Both geoms\n#' achieve the same result but differ in how the rectangles are parameterized:\n#' - **`geom_subrect()`**: Defines rectangles using their four corners (`xmin`,\n#' `xmax`, `ymin`, `ymax`).\n#' - **`geom_subtile()`**: Defines rectangles using the center (`x`, `y`) and\n#' dimensions (`width`, `height`).\n#'\n#' @param byrow A single boolean value indicates whether we should arrange the\n#' divided rectangles in the row-major order.\n#' @param nrow,ncol A single positive integer specifying the number of rows or\n#' columns in the layout of the subdivided cell. By default, the layout\n#' dimensions are determined automatically using logic similar to\n#' [`facet_wrap()`][ggplot2::facet_wrap].\n#' @param direction `r lifecycle::badge(\"deprecated\")` A string specifying the\n#' arrangement direction:\n#' - `\"h\"`(`horizontal`): Creates a single row (one-row layout).\n#' - `\"v\"`(`vertical`): Creates a single column (one-column layout).\n#' @inheritParams ggplot2::geom_rect\n#' @inheritParams ggplot2::geom_segment\n#' @aesthetics GeomSubrect\n#' @examples\n#' # arranges by row\n#' ggplot(data.frame(value = letters[seq_len(5)])) +\n#' geom_subtile(aes(x = 1, y = 1, fill = value), byrow = TRUE)\n#'\n#' # arranges by column\n#' ggplot(data.frame(value = letters[seq_len(9)])) +\n#' geom_subtile(aes(x = 1, y = 1, fill = value))\n#'\n#' # one-row\n#' ggplot(data.frame(value = letters[seq_len(4)])) +\n#' geom_subtile(aes(x = 1, y = 1, fill = value), nrow = 1)\n#'\n#' # one-column\n#' ggplot(data.frame(value = letters[seq_len(4)])) +\n#' geom_subtile(aes(x = 1, y = 1, fill = value), ncol = 1)\n#'\n#' @importFrom rlang list2\n#' @export\ngeom_subrect <- function(mapping = NULL, data = NULL,\n stat = \"identity\", position = \"identity\",\n ...,\n byrow = FALSE, nrow = NULL, ncol = NULL,\n lineend = \"butt\", linejoin = \"mitre\",\n na.rm = FALSE, show.legend = NA, inherit.aes = TRUE,\n direction = deprecated()) {\n assert_bool(byrow)\n assert_number_whole(nrow, min = 1, allow_null = TRUE)\n assert_number_whole(ncol, min = 1, allow_null = TRUE)\n if (lifecycle::is_present(direction)) {\n lifecycle::deprecate_warn(\n \"1.0.2\",\n \"geom_subtile(direction = )\",\n details = \"Please use the `nrow`/`ncol` argument instead.\"\n )\n if (is_horizontal(direction)) {\n nrow <- 1L\n ncol <- NULL\n } else {\n nrow <- NULL\n ncol <- 1L\n }\n }\n ggplot2::layer(\n data = data,\n mapping = mapping,\n stat = stat,\n geom = GeomSubrect,\n position = position,\n show.legend = show.legend,\n inherit.aes = inherit.aes,\n params = list2(\n byrow = byrow,\n nrow = nrow,\n ncol = ncol,\n lineend = lineend,\n linejoin = linejoin,\n na.rm = na.rm,\n ...\n )\n )\n}\n\n#' @importFrom ggplot2 ggproto ggproto_parent wrap_dims\nGeomSubrect <- ggproto(\n \"GeomSubrect\",\n ggplot2::GeomRect,\n extra_params = c(ggplot2::GeomRect$extra_params, \"byrow\", \"nrow\", \"ncol\"),\n setup_data = function(self, data, params) {\n data <- ggproto_parent(ggplot2::GeomRect, self)$setup_data(data, params)\n indices <- vec_group_loc(data[c(\"xmin\", \"xmax\", \"ymin\", \"ymax\")])\n data_list <- vec_chop(data, indices = .subset2(indices, \"loc\"))\n max_n_tiles <- max(list_sizes(data_list))\n if (max_n_tiles == 1L) return(data) # styler: off\n cli_inform(paste(\n \"{.fn {snake_class(self)}} subdivide tile into a maximal\",\n \"of {max_n_tiles} rectangles\"\n ))\n nrow <- .subset2(params, \"nrow\")\n ncol <- .subset2(params, \"ncol\")\n vec_rbind(!!!lapply(data_list, function(data) {\n n <- vec_size(data)\n if (n == 1L) return(data) # styler: off\n dims <- wrap_dims(n, nrow = nrow, ncol = ncol)\n n_rows <- dims[1L]\n n_cols <- dims[2L]\n one_row <- vec_slice(data, 1L)\n width <- (one_row$xmax - one_row$xmin) / n_cols\n height <- (one_row$ymax - one_row$ymin) / n_rows\n\n if (.subset2(params, \"byrow\")) {\n # we arrange the rectangles from from left to\n # right, then from top to bottom\n data$xmin <- data$xmin +\n vec_rep(width * (seq_len(n_cols) - 1L), n_rows)[\n seq_len(n)\n ]\n data$xmax <- data$xmax -\n vec_rep(width * rev(seq_len(n_cols) - 1L), n_rows)[\n seq_len(n)\n ]\n\n data$ymin <- data$ymin +\n vec_rep_each(height * rev(seq_len(n_rows) - 1L), n_cols)[\n seq_len(n)\n ]\n data$ymax <- data$ymax -\n vec_rep_each(height * (seq_len(n_rows) - 1L), n_cols)[\n seq_len(n)\n ]\n } else {\n # we arrange the rectangles from top to bottom,\n # then from left to right\n data$xmin <- data$xmin +\n vec_rep_each(width * (seq_len(n_cols) - 1L), n_rows)[\n seq_len(n)\n ]\n data$xmax <- data$xmax -\n vec_rep_each(width * rev(seq_len(n_cols) - 1L), n_rows)[\n seq_len(n)\n ]\n\n data$ymin <- data$ymin +\n vec_rep(height * rev(seq_len(n_rows) - 1L), n_cols)[\n seq_len(n)\n ]\n data$ymax <- data$ymax -\n vec_rep(height * (seq_len(n_rows) - 1L), n_cols)[\n seq_len(n)\n ]\n }\n\n data\n }))\n }\n)\n\n#' @aesthetics GeomSubtile\n#' @importFrom rlang list2\n#' @export\n#' @rdname geom_subrect\ngeom_subtile <- function(mapping = NULL, data = NULL,\n stat = \"identity\", position = \"identity\",\n ...,\n byrow = TRUE, nrow = NULL, ncol = NULL,\n lineend = \"butt\", linejoin = \"mitre\",\n na.rm = FALSE, show.legend = NA, inherit.aes = TRUE,\n direction = deprecated()) {\n assert_bool(byrow)\n assert_number_whole(nrow, min = 1, allow_null = TRUE)\n assert_number_whole(ncol, min = 1, allow_null = TRUE)\n if (lifecycle::is_present(direction)) {\n lifecycle::deprecate_warn(\n \"1.0.2\",\n \"geom_subtile(direction = )\",\n details = \"Please use the `nrow`/`ncol` argument instead.\"\n )\n if (is_horizontal(direction)) {\n nrow <- 1L\n ncol <- NULL\n } else {\n nrow <- NULL\n ncol <- 1L\n }\n }\n ggplot2::layer(\n data = data,\n mapping = mapping,\n stat = stat,\n geom = GeomSubtile,\n position = position,\n show.legend = show.legend,\n inherit.aes = inherit.aes,\n params = list2(\n byrow = byrow,\n nrow = nrow,\n ncol = ncol,\n lineend = lineend,\n linejoin = linejoin,\n na.rm = na.rm,\n ...\n )\n )\n}\n\n#' @importFrom ggplot2 ggproto ggproto_parent\nGeomSubtile <- ggproto(\n \"GeomSubtile\",\n ggplot2::GeomTile,\n extra_params = c(ggplot2::GeomRect$extra_params, \"byrow\", \"nrow\", \"ncol\"),\n setup_data = function(self, data, params) {\n data <- ggproto_parent(ggplot2::GeomTile, self)$setup_data(data, params)\n ggproto_parent(GeomSubrect, self)$setup_data(data, params)\n }\n)\n"], ["/ggalign/R/ggplot-utils.R", "#' @importFrom ggplot2 .pt\nggfun <- function(fn, mode = \"any\") from_namespace(\"ggplot2\", fn, mode = mode)\n\nallow_lambda <- function(x) {\n if (rlang::is_formula(x)) rlang::as_function(x) else x\n}\n\nis.waive <- function(x) inherits(x, \"waiver\")\n\n`%|w|%` <- function(x, y) if (inherits(x, \"waiver\")) y else x\n\nsnake_class <- function(x) ggfun(\"snake_class\")(x)\n\nggadd_default <- function(plot, mapping = NULL, theme = NULL) {\n if (!is.null(mapping)) {\n plot <- plot + mapping + plot$mapping\n }\n if (!is.null(theme)) plot$theme <- theme + plot$theme\n plot\n}\n\nis_palette_unset <- function(type, aes) {\n type <- match.arg(type, c(\"discrete\", \"continuous\", \"binned\"))\n aes <- match.arg(aes, c(\"fill\", \"colour\"))\n is.null(getOption(sprintf(\"ggplot2.%s.%s\", type, aes)))\n}\n\n# A guide-box should be a `zeroGrob()` or a `gtable` object\n#' @importFrom gtable is.gtable\nmaybe_guide_box <- function(x) inherits(x, \"zeroGrob\") || is.gtable(x)\n\n######################################################\ngguse_data <- function(plot, data) {\n # ggplot use waiver() to indicate no data\n plot[\"data\"] <- list(data %||% waiver())\n plot\n}\n\nggremove_margin <- function(plot, direction) {\n if (!is.null(direction) && packageVersion(\"ggplot2\") > \"3.5.2\") {\n plot <- plot + switch_direction(\n direction,\n theme(plot.margin = margin(t = 0, r = NA, b = 0, l = NA)),\n theme(plot.margin = margin(t = NA, r = 0, b = NA, l = 0))\n )\n }\n plot\n}\n\n######################################################\ndefault_expansion <- function(x = NULL, y = NULL) {\n structure(list(x = x, y = y), class = c(\"ggalign_default_expansion\"))\n}\n\n#' @importFrom ggplot2 ggplot_add ggproto ggproto_parent\n#' @export\nggplot_add.ggalign_default_expansion <- function(object, plot, object_name,\n ...) {\n if (is.null(.subset2(object, \"x\")) && is.null(.subset2(object, \"y\"))) {\n return(plot)\n }\n ParentFacet <- plot$facet\n plot$facet <- ggproto(\n NULL,\n ParentFacet,\n init_scales = function(self, layout, x_scale = NULL, y_scale = NULL,\n params) {\n if (!is.null(x_scale) && !is.null(.subset2(object, \"x\"))) {\n x_scale$expand <- x_scale$expand %|w|% .subset2(object, \"x\")\n }\n if (!is.null(y_scale) && !is.null(.subset2(object, \"y\"))) {\n y_scale$expand <- y_scale$expand %|w|% .subset2(object, \"y\")\n }\n ggproto_parent(ParentFacet, self)$init_scales(\n layout = layout,\n x_scale = x_scale,\n y_scale = y_scale,\n params = params\n )\n }\n )\n plot\n}\n\n######################################################\nreverse_continuous_axis <- function(plot, axis) {\n if (plot$scales$has_scale(axis)) {\n # modify scale in place\n scale <- plot$scales$get_scales(axis)\n if (!scale$is_discrete()) {\n if (identical(scale$trans$name, \"identity\")) {\n scale$trans <- scales::as.transform(\"reverse\")\n } else if (identical(scale$trans$name, \"reverse\")) {\n scale$trans <- scales::as.transform(\"identity\")\n }\n }\n } else {\n plot <- plot +\n switch(axis,\n x = ggplot2::scale_x_reverse(),\n y = ggplot2::scale_y_reverse()\n )\n }\n plot\n}\n"], ["/ggalign/R/alignpatch-wrap.R", "#' Wrap Arbitrary Graphics to ggplot\n#'\n#' The `ggwrap()` function allows non-ggplot2 elements to be converted into a\n#' compliant representation for use with [`align_plots()`]. This is useful for\n#' adding any graphics that can be converted into a [`grob`][grid::grob] with\n#' the [`patch()`] method.\n#'\n#' @param plot Any graphic that can be converted into a [`grob`][grid::grob]\n#' using [`patch()`].\n#' @param ... Additional arguments passed to the [`patch()`] method.\n#' @param align A string specifying the area to place the plot: `\"full\"` for the\n#' full area, `\"plot\"` for the full plotting area (including the axis label), or\n#' `\"panel\"` for only the actual area where data is drawn.\n#' @param clip A single boolean value indicating whether the grob should be\n#' clipped if they expand outside their designated area.\n#' @param on_top A single boolean value indicates whether the graphic plot\n#' should be put frontmost. Note: the graphic plot will always put above the\n#' background.\n#' @param vp A [`viewport`][grid::viewport] object, you can use this to define\n#' the plot area.\n#' @return A `wrapped_plot` object that can be directly placed into\n#' [`align_plots()`].\n#' @inherit patch seealso\n#' @examples\n#' library(grid)\n#' ggwrap(rectGrob(gp = gpar(fill = \"goldenrod\")), align = \"full\") +\n#' inset(rectGrob(gp = gpar(fill = \"steelblue\")), align = \"panel\") +\n#' inset(textGrob(\"Here are some text\", gp = gpar(color = \"black\")),\n#' align = \"panel\"\n#' )\n#' p1 <- ggplot(mtcars) +\n#' geom_point(aes(mpg, disp)) +\n#' ggtitle(\"Plot 1\")\n#' align_plots(p1, ggwrap(\n#' ~ plot(mtcars$mpg, mtcars$disp),\n#' mar = c(0, 2, 0, 0), bg = NA\n#' ))\n#'\n#' @importFrom ggplot2 theme element_blank ggplot\n#' @importFrom grid is.grob\n#' @export\nggwrap <- function(plot, ..., align = \"panel\", on_top = FALSE,\n clip = TRUE, vp = NULL) {\n patch <- ggplot() +\n theme(\n plot.background = element_blank(),\n panel.background = element_blank()\n )\n inset <- make_inset(\n plot = plot, ..., align = align, on_top = on_top,\n clip = clip, vp = vp\n )\n make_wrap(patch, inset)\n}\n\nmake_wrap <- function(patch, inset) UseMethod(\"make_wrap\")\n\nmake_wrapped_plot <- function(patch, inset) {\n if (.subset2(inset, \"on_top\")) {\n patch$ggalign_wrapped_insets_above <- c(\n patch$ggalign_wrapped_insets_above, list(inset)\n )\n } else {\n patch$ggalign_wrapped_insets_under <- c(\n patch$ggalign_wrapped_insets_under, list(inset)\n )\n }\n add_class(patch, \"wrapped_plot\")\n}\n\n#' @export\nmake_wrap.ggplot <- function(patch, inset) {\n patch <- add_class(patch, \"patch_ggplot\")\n make_wrap(patch, inset)\n}\n\n#' @export\nmake_wrap.patch_ggplot <- make_wrapped_plot\n\n#' @export\nmake_wrap.alignpatches <- make_wrapped_plot\n\n#################################################\n#' @importFrom ggplot2 ggproto ggproto_parent\n#' @export\nalignpatch.wrapped_plot <- function(x) {\n Parent <- NextMethod()\n ggproto(\n \"PatchWrapped\", Parent,\n ggalign_wrapped_insets_under = x$ggalign_wrapped_insets_under,\n ggalign_wrapped_insets_above = x$ggalign_wrapped_insets_above,\n patch_gtable = function(self, theme, guides, plot = Parent$plot) {\n ans <- ggproto_parent(Parent, self)$patch_gtable(\n theme = theme, guides = guides, plot = plot\n )\n ans <- add_wrapped_insets(\n ans, self$ggalign_wrapped_insets_under, FALSE\n )\n add_wrapped_insets(ans, self$ggalign_wrapped_insets_above, TRUE)\n }\n )\n}\n\n# For wrapped plot -------------------\n#' @export\nalignpatch.grob <- function(x) alignpatch(ggwrap(x))\n\n#' @export\nalignpatch.gList <- alignpatch.grob\n\n#' @export\nalignpatch.formula <- alignpatch.grob\n\n#' @export\nalignpatch.function <- alignpatch.grob\n\n#' @export\nalignpatch.recordedplot <- alignpatch.grob\n\n#' @export\nalignpatch.trellis <- alignpatch.grob\n\n#' @export\nalignpatch.Heatmap <- function(x) alignpatch(ggwrap(x, align = \"full\"))\n\n#' @export\nalignpatch.HeatmapList <- alignpatch.Heatmap\n\n#' @export\nalignpatch.HeatmapAnnotation <- alignpatch.Heatmap\n\n#' @export\nalignpatch.pheatmap <- function(x) alignpatch(ggwrap(x, align = \"full\"))\n\n################################################## 3\nadd_wrapped_insets <- function(gt, insets, on_top) {\n if (is.null(insets)) return(gt) # styler: off\n for (i in seq_along(insets)) {\n gt <- add_wrapped_inset(gt, .subset2(insets, i), on_top, i)\n }\n gt\n}\n\n#' @importFrom gtable gtable is.gtable gtable_add_grob\nadd_wrapped_inset <- function(gt, inset, on_top, i) {\n align <- .subset2(inset, \"align\")\n clip <- .subset2(inset, \"clip\")\n layout <- .subset2(gt, \"layout\")\n grob <- .subset2(inset, \"grob\")\n if (on_top) {\n z <- Inf\n } else {\n background <- .subset2(layout, \"name\") == \"background\"\n z <- .subset2(layout, \"z\")[background] + 1L\n gt$layout$z[layout$z >= z] <- layout$z[layout$z >= z] + 1L\n }\n\n # add the grob to the gtable\n if (align == \"full\") {\n gt <- gtable_add_grob(gt,\n list(grob), 1L, 1L, nrow(gt), ncol(gt),\n clip = clip, name = sprintf(\"wrap-full-%d\", i), z = z\n )\n } else {\n panel_loc <- find_panel(gt)\n gt <- switch(align,\n plot = gtable_add_grob(gt,\n list(grob),\n .subset2(panel_loc, \"t\") - 3L,\n .subset2(panel_loc, \"l\") - 3L,\n .subset2(panel_loc, \"b\") + 3L,\n .subset2(panel_loc, \"r\") + 3L,\n clip = clip, name = sprintf(\"wrap-plot-%d\", i), z = z\n ),\n panel = gtable_add_grob(gt,\n list(grob),\n .subset2(panel_loc, \"t\"),\n .subset2(panel_loc, \"l\"),\n .subset2(panel_loc, \"b\"),\n .subset2(panel_loc, \"r\"),\n clip = clip, name = sprintf(\"wrap-panel-%d\", i), z = z\n )\n )\n }\n gt\n}\n"], ["/ggalign/R/alignpatch-inset.R", "#' Create a ggplot inset\n#'\n#' @inheritParams ggwrap\n#' @return A `patch_inset` object, which can be added in ggplot.\n#' @inherit patch seealso\n#' @examples\n#' library(grid)\n#' p1 <- ggplot(mtcars) +\n#' geom_point(aes(mpg, disp))\n#' p2 <- ggplot(mtcars) +\n#' geom_boxplot(aes(gear, disp, group = gear))\n#' p1 + inset(p2, vp = viewport(0.6, 0.6,\n#' just = c(0, 0), width = 0.4, height = 0.4\n#' ))\n#' @export\ninset <- function(\n plot,\n ...,\n align = \"panel\",\n on_top = TRUE,\n clip = TRUE,\n vp = NULL) {\n make_inset(\n plot = plot,\n ...,\n align = align,\n on_top = on_top,\n clip = clip,\n vp = vp\n )\n}\n\n#' @importFrom grid editGrob\n#' @importFrom rlang arg_match0\nmake_inset <- function(\n plot,\n ...,\n align,\n on_top,\n clip,\n vp,\n call = caller_call()) {\n assert_bool(on_top, call = call)\n align <- arg_match0(align, c(\"panel\", \"plot\", \"full\"), error_call = call)\n assert_bool(clip, call = call)\n assert_s3_class(vp, \"viewport\", allow_null = TRUE, call = call)\n if (!is.grob(grob <- patch(x = plot, ...))) {\n cli_abort(\"{.fn patch} must return a {.cls grob}\", call = call)\n }\n if (!is.null(vp)) grob <- editGrob(grob, vp = vp)\n structure(\n list(\n grob = grob,\n align = align,\n clip = if (clip) \"on\" else \"off\",\n on_top = on_top\n ),\n class = \"patch_inset\"\n )\n}\n\n#' @importFrom grid grid.draw\n#' @export\ngrid.draw.patch_inset <- function(x, recording = TRUE) {\n grid.draw(.subset2(x, \"grob\"))\n}\n\n#' @importFrom ggplot2 ggplot_add\n#' @export\nggplot_add.patch_inset <- function(object, plot, object_name, ...) {\n make_wrap(plot, object)\n}\n"], ["/ggalign/R/genomic-helper.R", "#' Calculate inter-region distances for genomic rainfall plots\n#'\n#' This function computes distances between adjacent genomic regions, grouped by\n#' chromosome. Useful for visualizing clustering or dispersion of genomic\n#' features.\n#'\n#' @param region A data frame with at least 3 columns: chromosome, start, and\n#' end.\n#' @param mode How to assign distance for intermediate regions: one of `\"min\"`,\n#' `\"max\"`, `\"mean\"`, `\"left\"`, or `\"right\"`.\n#' @details\n#' The distance between two adjacent regions is calculated as the number of\n#' bases between the **end position of the upstream region** and the\n#' **start position of the downstream region**. If two regions overlap or are\n#' adjacent (≤1 bp apart), the distance is set to `0`. The resulting distance is\n#' assigned to each region according to the selected `mode`:\n#'\n#' - `\"left\"`: assign the distance to the upstream region\n#' - `\"right\"`: assign to the downstream region\n#' - `\"min\"` / `\"max\"` / `\"mean\"`: for intermediate regions, calculate the\n#' minimum, maximum, or average of the distances to neighboring regions\n#'\n#' @return A data frame with an additional `dist` column.\n#' @export\ngenomic_dist <- function(region, mode = NULL) {\n # Check input validity\n if (is.null(mode)) {\n mode <- \"min\"\n } else {\n mode <- arg_match0(mode, c(\"min\", \"max\", \"mean\", \"left\", \"right\"))\n }\n if (!is.data.frame(region) || ncol(region) < 3L) {\n cli_abort(\"{.arg region} must have at least 3 columns: chromosome, start, and end\")\n }\n if (anyNA(region[[1L]]) || anyNA(region[[2L]]) || anyNA(region[[3L]])) {\n cli_abort(\"Columns 1, 2, and 3 of {.arg region} must not contain missing values\")\n }\n if (!is.numeric(region[[2L]]) || !is.numeric(region[[3L]])) {\n cli_abort(\"Columns 2 and 3 of {.arg region} must be numeric (start and end positions)\")\n }\n if (any(region[[2L]] > region[[3L]])) {\n cli_abort(\"Column 2 (start) must not be greater than column 3 (end) in any row of {.arg region}\")\n }\n\n # Split the region data frame by chromosome (first column)\n groups <- vec_split(region, .subset2(region, 1L))\n dist_list <- lapply(.subset2(groups, \"val\"), function(d) {\n n <- nrow(d)\n if (n < 2L) {\n d$dist <- NA_real_\n return(d)\n }\n\n # Sort regions by start, then end positions\n ordering <- order(.subset2(d, 2L), .subset2(d, 3L))\n\n # Compute distances between adjacent regions\n dists <- vapply(seq_len(n - 1L), function(i) {\n first <- vec_slice(d, ordering[i])\n second <- vec_slice(d, ordering[i + 1])\n out <- .subset2(second, 2L) - .subset2(first, 3L)\n # If overlapping or adjacent (≤1 bp), treat distance as 0\n if (out <= 1L) out <- 0L else out <- as.integer(out)\n out\n }, integer(1L), USE.NAMES = FALSE)\n\n # If only two regions, just repeat the distance\n if (n == 2L) {\n d$dist <- rep_len(dists, n)\n return(d)\n }\n\n # For intermediate regions (not first or last), choose how to assign\n # distance\n d1 <- dists[seq_len(n - 2L)]\n d2 <- dists[2:(n - 1L)]\n if (mode == \"min\") {\n body_dists <- pmin(d1, d2)\n } else if (mode == \"max\") {\n body_dists <- pmax(d1, d2)\n } else if (mode == \"mean\") {\n body_dists <- (d1 + d2) / 2L\n } else if (mode == \"left\") {\n body_dists <- d1\n } else if (mode == \"right\") {\n body_dists <- d2\n }\n\n # Combine distances: head, body, and tail\n d$dist <- c(dists[1L], body_dists, dists[n - 1L])[order(ordering)]\n d\n })\n vec_rbind(!!!dist_list)\n}\n\n#' Calculate Genomic Region Density\n#'\n#' Computes the density or count of genomic regions in sliding or fixed windows\n#' across the genome. The density can be reported as the percentage of uncovered\n#' bases or the number of overlapping regions within each window.\n#'\n#' This function splits the input by chromosome and tiles the genomic space\n#' into windows, optionally overlapping. For each window, it calculates:\n#'\n#' - the number of regions that overlap it (if `mode = \"count\"`), or\n#' - the fraction of bases covered by any region (if `mode = \"percent\"`).\n#'\n#' @param region A data frame with at least 3 columns: chromosome, start, and\n#' end.\n#' - Column 1: character or factor, chromosome name.\n#' - Column 2: numeric, start position (must be ≤ end).\n#' - Column 3: numeric, end position.\n#' @param window_size Numeric, the width of each window (default is `1e+07`).\n#' Ignored if `n_window` is specified.\n#' @param n_window Integer, the number of windows per chromosome. If provided,\n#' overrides `window_size` and evenly splits the chromosome into `n_window`\n#' (non-overlapping) or `2*n_window - 1` (overlapping) windows.\n#' @param overlap Logical, whether to use overlapping windows (default `TRUE`).\n#' Overlapping windows are spaced by half the window size.\n#' @param mode Character, either `\"coverage\"` or `\"count\"`:\n#' - `\"count\"`: reports the number of regions overlapping each window.\n#' - `\"coverage\"`: reports the fraction of each window covered by regions.\n#' @param seqlengths Optional named vector of chromosome lengths. If missing,\n#' the maximum `end` value in the input is used as the chromosome length.\n#'\n#' @return A data frame with columns:\n#' - `seqnames`: The sequence (e.g., chromosome) names.\n#' - `start`: start of each window\n#' - `end`: end of each window\n#' - `density`: the region count or covered percent, depending on `mode`\n#'\n#' @examples\n#' region <- data.frame(\n#' chr = rep(\"chr1\", 3),\n#' start = c(100, 5000000, 15000000),\n#' end = c(2000000, 7000000, 17000000)\n#' )\n#' genomic_density(region, window_size = 1e7, mode = \"count\")\n#' genomic_density(region, n_window = 3, overlap = FALSE, mode = \"coverage\")\n#'\n#' @export\ngenomic_density <- function(region, window_size = 1e+07, n_window = NULL,\n overlap = TRUE, mode = c(\"coverage\", \"count\"),\n seqlengths = NULL) {\n # Check input validity\n assert_number_whole(window_size, allow_null = TRUE, min = 1)\n assert_number_whole(n_window, allow_null = TRUE, min = 1)\n if (is.null(window_size) && is.null(n_window)) {\n cli_abort(c(\n \"Both {.arg window_size} and {.arg n_window} are {.val NULL}.\",\n \"i\" = \"You must supply at least one of these arguments to define the binning strategy.\"\n ))\n }\n assert_bool(overlap)\n if (is.null(mode)) {\n mode <- \"coverage\"\n } else {\n mode <- arg_match0(mode, c(\"coverage\", \"count\"))\n }\n if (!is.data.frame(region) || ncol(region) < 3L) {\n cli_abort(\"{.arg region} must have at least 3 columns: chromosome, start, and end\")\n }\n if (anyNA(region[[1L]]) || anyNA(region[[2L]]) || anyNA(region[[3L]])) {\n cli_abort(\"Columns 1, 2, and 3 of {.arg region} must not contain missing values\")\n }\n if (!is.numeric(region[[2L]]) || !is.numeric(region[[3L]])) {\n cli_abort(\"Columns 2 and 3 of {.arg region} must be numeric (start and end positions)\")\n }\n if (any(region[[2L]] > region[[3L]])) {\n cli_abort(\"Column 2 (start) must not be greater than column 3 (end) in any row of {.arg region}\")\n }\n\n # Split the region data frame by chromosome (first column)\n groups <- vec_split(region, .subset2(region, 1L))\n density_list <- lapply(.subset2(groups, \"val\"), function(d) {\n chr <- .subset2(d, 1L)[1L]\n if (is.null(seqlengths)) {\n max_pos <- max(.subset2(region, 3L))\n } else {\n max_pos <- seqlengths[chr]\n if (is.na(max_pos)) {\n cli_abort(\"Chromosome {.val {chr}} is not found in {.arg seqlengths}. Please check that all chromosomes in {.arg region} have corresponding sequence lengths.\")\n }\n }\n if (overlap) {\n if (is.null(n_window)) {\n # Half-step sliding windows: start at 1, step = half window size\n b <- seq(0L, max_pos, by = window_size %/% 2L)\n s <- b[-length(b)]\n s <- s[-length(s)] + 1L\n e <- s + window_size - 1L\n } else {\n b <- seq(0L, max_pos, length.out = 2L * n_window + 1L)\n s <- b[-length(b)]\n s <- s[-length(s)] + 1L\n e <- s + b[3L] - b[1L] - 1L\n }\n } else {\n if (is.null(n_window)) {\n b <- seq(0L, max_pos, by = window_size)\n s <- b[-length(b)] + 1L\n e <- s + window_size - 1L\n } else {\n b <- seq(0, max_pos, length.out = n_window + 1L)\n s <- b[-length(b)] + 1L\n e <- s + b[2L] - b[1L]\n }\n }\n s <- as.integer(s)\n e <- as.integer(e)\n region_s <- .subset2(d, 2L)\n region_e <- .subset2(d, 3L)\n if (mode == \"count\") {\n # For each window, count how many regions overlap with it\n density <- vapply(seq_along(s), function(i) {\n si <- s[i]\n ei <- e[i]\n sum(!(region_s > ei | region_e < si))\n }, integer(1L), USE.NAMES = FALSE)\n } else {\n region_s <- as.integer(ceiling(region_s))\n region_e <- as.integer(floor(region_e))\n # For each window, calculate the proportion of bases covered by\n # regions\n density <- vapply(seq_along(s), function(i) {\n si <- s[i]\n ei <- e[i]\n # Keep regions that overlap with current window\n keep <- !(region_s > ei | region_e < si)\n\n # Clip regions to fit within the current window\n region_s_used <- pmax(region_s[keep], si)\n region_e_used <- pmin(region_e[keep], ei)\n\n # If no overlapping region, coverage is zero\n if (length(region_s_used) == 0L) {\n return(0)\n }\n\n # Sort intervals by start, then end\n ordering <- order(region_s_used, region_e_used)\n region_s_used <- region_s_used[ordering]\n region_e_used <- region_e_used[ordering]\n\n # Initialize with the first interval\n start <- region_s_used[1L]\n end <- region_e_used[1L]\n\n # If there's only one interval, just compute its coverage\n if (length(region_s_used) == 1L) {\n cov <- end - start + 1L\n return(cov / (ei - si + 1L))\n }\n # Merge overlapping/adjacent intervals and compute total\n # coverage\n cov <- 0L\n for (j in 2:length(region_s_used)) {\n if (region_s_used[j] - end <= 1L) {\n end <- max(end, region_e_used[j])\n } else {\n cov <- cov + (end - start + 1L)\n start <- region_s_used[j]\n end <- region_e_used[j]\n }\n }\n cov <- cov + (end - start + 1L)\n cov / (ei - si + 1L)\n }, numeric(1L), USE.NAMES = FALSE)\n }\n data_frame0(seqnames = chr, start = s, end = e, density = density)\n })\n vec_rbind(!!!density_list)\n}\n"], ["/ggalign/R/craft-align-kmeans.R", "#' Split observations by k-means clustering groups.\n#'\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' Aligns and groups observations based on k-means clustering, enabling\n#' observation splits by cluster groups.\n#'\n#' @inheritDotParams stats::kmeans -x -centers\n#' @param data A numeric matrix to be used by k-means. By default, it will\n#' inherit from the layout matrix.\n#' @inheritParams align\n#' @inheritSection align Discrete Axis Alignment\n#' @examples\n#' ggheatmap(matrix(rnorm(81), nrow = 9)) +\n#' anno_top() +\n#' align_kmeans(3L)\n#' @importFrom rlang list2\n#' @export\nalign_kmeans <- function(..., data = NULL, active = NULL) {\n assert_active(active)\n active <- update_active(active, new_active(use = FALSE))\n align(\n align = AlignKmeans,\n params = list2(...),\n active = active,\n data = data\n )\n}\n\n#' @importFrom ggplot2 ggproto\n#' @importFrom rlang inject\nAlignKmeans <- ggproto(\"AlignKmeans\", CraftAlign,\n interact_layout = function(self, layout) {\n ggproto_parent(AlignOrder2, self)$interact_layout(layout)\n },\n compute = function(self, panel, index) {\n inject(stats::kmeans(x = self$data, !!!self$params))\n },\n align = function(self, panel, index) {\n list(.subset2(self$statistics, \"cluster\"), index)\n },\n summary_align = function(self) c(FALSE, TRUE)\n)\n"], ["/ggalign/R/alignpatch-.R", "# here is copied from patchwork\n# we modified the `patchwork` package for following reasons:\n# 1. collect guides for each side (should be merged into patchwork, not allowed\n# to be merged: https://github.com/thomasp85/patchwork/issues/379).\n# 2. `free_*()` functions: see https://github.com/thomasp85/patchwork/issues/379\n# - `free_align()`: added\n# - `free_border()`: not added\n# - `free_lab()`: added\n# - `free_space()`: added\n# - `free_vp()`: not added\n# 3. Added titles around the plot top, left, bottom, and right\n# (`patch_titles()`)\nTABLE_ROWS <- 18L + 2L\nTABLE_COLS <- 15L + 2L\n\nTOP_BORDER <- 9L + 1L\nLEFT_BORDER <- 7L + 1L\nBOTTOM_BORDER <- 8L + 1L\nRIGHT_BORDER <- 7L + 1L\n\n# top-bottom\n# 1: margin\n# 2: tag\n# 3: title\n# 4: subtitle\n# 5: guide-box-top\n# 6: legend.box.spacing\n# feature: insert patch title\n# 7: xlab-t\n# strip.placement = \"inside\"/\"outside\"\n# 8: axis-t/strip-t\n# 9: strip-t/axis-t\n# 10: panel\n# 11: strip-b\n# 12: axis-b\n# 13: xlab-b\n# feature: insert patch title\n# 14: legend.box.spacing\n# 15: guide-box-bottom\n# 16: caption\n# 17: tag\n# 18: margin\n\n# left-right\n#\n# 1: margin\n# 2: tag\n# 3: guide-box-left\n# 4: legend.box.spacing\n# feature: insert patch title\n# 5: ylab-l\n# 6: axis-l\n# 8: panel\n# 10: axis-r\n# 11: ylab-r\n# feature: insert patch title\n# 12: legend.box.spacing\n# 13: guide-box-right\n# 14: tag\n# 15: margin\n\n.TLBR <- c(\"top\", \"left\", \"bottom\", \"right\")\n.tlbr <- c(\"t\", \"l\", \"b\", \"r\")\n\n# position is a single string contains `.tlbr`\nsetdiff_position <- function(x, y) gsub(sprintf(\"[%s]\", y), \"\", x)\nunion_position <- function(x, y) paste0(x, gsub(sprintf(\"[%s]\", x), \"\", y))\nsplit_position <- function(x) {\n vec_unique(.subset2(strsplit(x, \"\", fixed = TRUE), 1L))\n}\n\n# pos is an atomic character\nsetup_pos <- function(x) unname(complete_pos(split_position(x)))\n\nsetup_guides <- function(x) {\n .subset(\n c(t = \"top\", l = \"left\", b = \"bottom\", r = \"right\", i = \"inside\"),\n split_position(x)\n )\n}\n\ncomplete_pos <- function(x) {\n .subset(c(t = \"top\", l = \"left\", b = \"bottom\", r = \"right\"), x)\n}\n\nopposite_pos <- function(pos) {\n switch(pos,\n top = \"bottom\",\n bottom = \"top\",\n left = \"right\",\n right = \"left\"\n )\n}\n\n#' @importFrom ggplot2 zeroGrob\n#' @importFrom gtable gtable gtable_add_grob\n#' @importFrom grid unit\nmake_patch_table <- function() {\n widths <- unit(rep(0L, TABLE_COLS), \"mm\")\n widths[LEFT_BORDER + 1L] <- unit(1L, \"null\")\n heights <- unit(rep(0L, TABLE_ROWS), \"mm\")\n heights[TOP_BORDER + 1L] <- unit(1L, \"null\")\n ans <- gtable(widths, heights)\n gtable_add_grob(ans,\n list(zeroGrob()), TOP_BORDER + 1L, LEFT_BORDER + 1L,\n z = -Inf, name = \"panel-area\"\n )\n}\n\n#' Generate a plot grob.\n#'\n#' @param x An object to be converted into a [grob][grid::grob].\n#' @return A [`grob()`][grid::grob] object.\n#' @examples\n#' ggalignGrob(ggplot())\n#' @export\nggalignGrob <- function(x) {\n ggalign_gtable(ggalign_build(x))\n}\n\n# Now, we only define `ggalign_gtable` method for `alignpatches` and `ggplot`\n# `ggalign_build` must return these objects\nggalign_build <- function(x) UseMethod(\"ggalign_build\")\n\nggalign_gtable <- function(x) UseMethod(\"ggalign_gtable\")\n\n#' @export\nggalign_gtable.gtable <- function(x) x\n\n#' Prepare plots to be aligned with `align_plots`\n#'\n#' @param x A plot object to be prepared for alignment.\n#' @details\n#' `ggalign` has implement `alignpatch` method for following objects:\n#' - [`ggplot`][ggplot2::ggplot]\n#' - [`alignpatches`][align_plots]\n#' - [`wrapped_plot`][ggwrap]\n#' - [`patch`][patchwork::patchGrob]\n#' - [`wrapped_patch`][patchwork::wrap_elements]\n#' - [`spacer`][patchwork::plot_spacer]\n#'\n#' @return A `Patch` object.\n#' @examples\n#' alignpatch(ggplot())\n#' @seealso [`align_plots()`]\n#' @export\n#' @keywords internal\nalignpatch <- function(x) UseMethod(\"alignpatch\")\n\n#' @export\nalignpatch.default <- function(x) {\n cli_abort(\"Cannot align {.obj_type_friendly {x}}\")\n}\n\n#' @export\nalignpatch.NULL <- function(x) NULL\n\npatch_no_method <- function(plot, method) {\n cli_abort(\"no {.fn {method}} method for {.obj_type_friendly {plot}}\")\n}\n\n#' @importFrom ggplot2 ggproto\n#' @importFrom grid unit.c\nPatch <- ggproto(\n \"Patch\", NULL,\n # following fields will be added by `alignpatch()`\n plot = NULL,\n # following fields will be added in `alignpatches$patch_gtable()`\n # borders = NULL, gt = NULL,\n\n #' @param guides `guides` argument from the parent alignpatches\n #' @return Which side of guide legends should be collected by the parent\n #' `alignpatches` object?\n #' @noRd\n set_guides = function(self, guides) {\n patch_no_method(self$plot, \"set_guides\")\n },\n patch_gtable = function(self, theme, guides, plot = self$plot) {\n patch_no_method(self$plot, \"patch_gtable\")\n },\n collect_guides = function(self, guides, gt = self$gt) {\n if (is.null(guides)) return(list()) # styler: off\n layout <- .subset2(gt, \"layout\")\n grobs <- .subset2(gt, \"grobs\")\n guides_ind <- grep(\"guide-box\", .subset2(layout, \"name\"))\n guides_loc <- vec_slice(layout, guides_ind)\n collected_guides <- vector(\"list\", length(guides))\n names(collected_guides) <- guides\n panel_loc <- find_panel(gt)\n remove_grobs <- NULL\n for (guide_pos in guides) {\n guide_ind <- switch(guide_pos,\n top = .subset2(guides_loc, \"b\") < .subset2(panel_loc, \"t\"),\n left = .subset2(guides_loc, \"r\") < .subset2(panel_loc, \"l\"),\n bottom = .subset2(guides_loc, \"t\") > .subset2(panel_loc, \"b\"),\n right = .subset2(guides_loc, \"l\") > .subset2(panel_loc, \"r\"),\n inside = .subset2(guides_loc, \"t\") >= .subset2(panel_loc, \"t\") &\n .subset2(guides_loc, \"b\") <= .subset2(panel_loc, \"b\") &\n .subset2(guides_loc, \"l\") >= .subset2(panel_loc, \"l\") &\n .subset2(guides_loc, \"r\") <= .subset2(panel_loc, \"r\")\n )\n if (!any(guide_ind)) next\n guide_loc <- vec_slice(guides_loc, guide_ind)\n guide_ind <- .subset(guides_ind, guide_ind)\n remove_grobs <- c(guide_ind, remove_grobs)\n collected_guides[[guide_pos]] <- .subset2(grobs, guide_ind)\n\n # remove the guide spaces from the original gtable\n # for inside guide, no need to remove the spaces\n if (guide_pos == \"inside\") next\n\n space_pos <- switch(guide_pos,\n top = ,\n left = 1L,\n bottom = ,\n right = -1L\n )\n if (guide_pos %in% c(\"right\", \"left\")) {\n gt$widths[c(guide_loc$l, guide_loc$l + space_pos)] <- unit(\n c(0L, 0L), \"mm\"\n )\n } else if (guide_pos %in% c(\"bottom\", \"top\")) {\n gt$heights[c(guide_loc$t, guide_loc$t + space_pos)] <- unit(\n c(0L, 0L), \"mm\"\n )\n }\n }\n if (length(remove_grobs)) {\n gt <- subset_gt(gt, -remove_grobs, trim = FALSE)\n }\n self$gt <- gt\n collected_guides\n },\n respect = function(self, gt = self$gt) isTRUE(.subset2(gt, \"respect\")),\n align_panel_sizes = function(self, panel_width, panel_height,\n gt = self$gt) {\n list(width = panel_width, height = panel_height, respect = FALSE)\n },\n get_sizes = function(self, free = NULL, gt = self$gt) {\n ans <- .subset2(gt, \"heights\")\n if (any(free == \"t\")) {\n top <- unit(rep_len(0, TOP_BORDER), \"mm\")\n } else {\n top <- ans[seq_len(TOP_BORDER)]\n }\n if (any(free == \"b\")) {\n bottom <- unit(rep_len(0, BOTTOM_BORDER), \"mm\")\n } else {\n bottom <- ans[seq(length(ans) - BOTTOM_BORDER + 1L, length(ans))]\n }\n ans <- .subset2(gt, \"widths\")\n if (any(free == \"l\")) {\n left <- unit(rep_len(0, LEFT_BORDER), \"mm\")\n } else {\n left <- ans[seq_len(LEFT_BORDER)]\n }\n if (any(free == \"r\")) {\n right <- unit(rep_len(0, RIGHT_BORDER), \"mm\")\n } else {\n right <- ans[seq(length(ans) - RIGHT_BORDER + 1L, length(ans))]\n }\n list(\n widths = unit.c(left, unit(0, \"mm\"), right),\n heights = unit.c(top, unit(0, \"mm\"), bottom)\n )\n },\n align_border = function(self, t = NULL, l = NULL, b = NULL, r = NULL,\n gt = self$gt) {\n if (!is.null(t)) gt$heights[seq_along(t)] <- t\n if (!is.null(l)) gt$widths[seq_along(l)] <- l\n if (!is.null(b)) {\n n_row <- nrow(gt)\n gt$heights[seq(n_row - length(b) + 1L, n_row)] <- b\n }\n if (!is.null(r)) {\n n_col <- ncol(gt)\n gt$widths[seq(n_col - length(r) + 1L, n_col)] <- r\n }\n gt\n },\n split_gt = function(self, gt = self$gt) {\n isbg <- .subset2(.subset2(gt, \"layout\"), \"name\") == \"background\"\n if (any(isbg)) {\n bg <- .subset(.subset2(gt, \"grobs\"), isbg) # a list of background\n plot <- subset_gt(gt, !isbg, trim = FALSE)\n } else {\n bg <- NULL\n plot <- gt\n }\n list(bg = bg, plot = plot)\n },\n add_plot = function(self, gt, plot, t, l, b, r, name, z = 2L) {\n gtable_add_grob(\n gt,\n grobs = plot,\n t = t, l = l, b = b, r = r,\n name = name, z = z\n )\n },\n add_background = function(self, gt, bg, t, l, b, r, name, z = 1L) {\n gtable_add_grob(\n gt,\n grobs = bg,\n t = t, l = l, b = b, r = r,\n name = name, z = z\n )\n },\n free_border = function(self, borders, gt = self$gt) {\n patch_no_method(self$plot, \"free_border\")\n },\n align_free_border = function(self, borders,\n t = NULL, l = NULL, b = NULL, r = NULL,\n gt = self$gt) {\n patch_no_method(self$plot, \"align_free_border\")\n },\n free_lab = function(self, labs, gt = self$gt) {\n patch_no_method(self$plot, \"free_lab\")\n }\n)\n"], ["/ggalign/R/alignpatch-free-align.R", "#' Free from alignment\n#'\n#' [align_plots] will try to align plot panels, and every elements of the plot,\n#' following functions romove these restrictions:\n#' - `free_align`: if we want to compose plots without alignment of some panel\n#' axes (panel won't be aligned). we can wrap the plot with `free_align`.\n#' - `free_border`: attaches borders (e.g., axis titles, tick marks) directly to\n#' the plot panel. This keeps them visually close to the panel during\n#' alignment.\n#' - `free_lab()`: Similar to `free_border()`, but only attaches axis titles\n#' and tick labels, not full borders. It’s mainly included for completeness;\n#' in most cases, combining `free_border()` and `free_space()` is sufficient.\n#' - `free_space`: Removing the ggplot element sizes when aligning.\n#' - `free_vp`: Customize the [viewport][grid::viewport] when aligning.\n#' - `free_guide`: If we want to override the behaviour of the overall guides\n#' behaviour, we can wrap the plot with `free_guide`.\n#'\n#' @param plot A [ggplot][ggplot2::ggplot] or [alignpatches][align_plots]\n#' object.\n#' @param axes Which axes shouldn't be aligned? A string containing\n#' one or more of `r oxford_and(.tlbr)`.\n#' @return\n#' - `free_align`: A modified version of `plot` with a `free_align` class.\n#' @examples\n#' # directly copied from `patchwork`\n#' # Sometimes you have a plot that defies good composition alginment, e.g. due\n#' # to long axis labels\n#' p1 <- ggplot(mtcars) +\n#' geom_bar(aes(y = factor(gear), fill = factor(gear))) +\n#' scale_y_discrete(\n#' \"\",\n#' labels = c(\n#' \"3 gears are often enough\",\n#' \"But, you know, 4 is a nice number\",\n#' \"I would def go with 5 gears in a modern car\"\n#' )\n#' )\n#'\n#' # When combined with other plots it ends up looking bad\n#' p2 <- ggplot(mtcars) +\n#' geom_point(aes(mpg, disp))\n#'\n#' align_plots(p1, p2, ncol = 1L)\n#'\n#' # We can fix this be using `free_align`\n#' align_plots(free_align(p1), p2, ncol = 1L)\n#'\n#' # If we still want the panels to be aligned to the right, we can choose to\n#' # free only the left side\n#' align_plots(free_align(p1, axes = \"l\"), p2, ncol = 1L)\n#'\n#' # We could use `free_lab` to fix the layout in a different way\n#' align_plots(p1, free_lab(p2), ncol = 1L)\n#'\n#' # `free_border` is similar with `free_lab`, they have a distinction in terms\n#' # of placement on either the top or bottom side of the panel. Specifically,\n#' # the top side contains the `title` and `subtitle`, while the bottom side\n#' # contains the `caption`. free_lab() does not attach these elements in the\n#' # panel area.\n#' p3 <- ggplot(mtcars) +\n#' geom_point(aes(hp, wt, colour = mpg)) +\n#' ggtitle(\"Plot 3\")\n#' p_axis_top <- ggplot(mtcars) +\n#' geom_point(aes(mpg, disp)) +\n#' ggtitle(\"Plot axis in top\") +\n#' scale_x_continuous(position = \"top\")\n#' align_plots(p_axis_top, free_lab(p3))\n#' align_plots(p_axis_top, free_border(p3))\n#'\n#' # Another issue is that long labels can occupy much spaces\n#' align_plots(NULL, p1, p2, p2)\n#'\n#' # This can be fixed with `free_space`\n#' align_plots(NULL, free_space(p1, \"l\"), p2, p2)\n#'\n#' @export\n#' @rdname free\nfree_align <- function(plot, axes = \"tlbr\") {\n UseMethod(\"free_align\")\n}\n\n# free_guides: set_guides\n# free_lab: collect_guides\n# free_border: collect_guides and align_border\n# free_space: get_sizes\n# free_align: get_sizes and align_border\n# free_vp: align_border\n\n#' @export\nfree_align.ggplot <- function(plot, axes = \"tlbr\") {\n assert_position(axes)\n attr(plot, \"free_axes\") <- axes\n add_class(plot, \"free_align\")\n}\n\n#' @export\nfree_align.alignpatches <- free_align.ggplot\n\n#' @importFrom rlang is_empty\n#' @export\nfree_align.free_lab <- function(plot, axes = \"tlbr\") {\n assert_position(axes)\n # if axes are free, it's not necessary to free the labs\n free_labs <- setdiff_position(attr(plot, \"free_labs\"), axes)\n if (nzchar(free_labs)) {\n attr(plot, \"free_labs\") <- free_labs\n } else {\n attr(plot, \"free_labs\") <- NULL\n plot <- remove_class(plot, \"free_lab\")\n }\n NextMethod()\n}\n\n#' @importFrom rlang is_empty\n#' @export\nfree_align.free_space <- function(plot, axes = \"tlbr\") {\n assert_position(axes)\n free_spaces <- setdiff_position(attr(plot, \"free_spaces\"), axes)\n if (nzchar(free_spaces)) {\n attr(plot, \"free_spaces\") <- free_spaces\n } else {\n attr(plot, \"free_spaces\") <- NULL\n plot <- remove_class(plot, \"free_space\")\n }\n NextMethod()\n}\n\n#' @importFrom rlang is_empty\n#' @export\nfree_align.free_border <- function(plot, axes = \"tlbr\") {\n assert_position(axes)\n free_borders <- setdiff_position(attr(plot, \"free_borders\"), axes)\n if (nzchar(free_borders)) {\n attr(plot, \"free_borders\") <- free_borders\n } else {\n attr(plot, \"free_borders\") <- NULL\n plot <- remove_class(plot, \"free_border\")\n }\n NextMethod()\n}\n\n#' @export\nfree_align.free_align <- function(plot, axes = \"tlbr\") {\n assert_position(axes)\n attr(plot, \"free_axes\") <- union_position(attr(plot, \"free_axes\"), axes)\n plot\n}\n\n#' @export\nfree_align.default <- function(plot, axes = \"tlbr\") {\n cli_abort(\"Cannot use with {.obj_type_friendly {plot}}\")\n}\n\n#' @importFrom ggplot2 ggproto ggproto_parent\n#' @export\nalignpatch.free_align <- function(x) {\n Parent <- NextMethod()\n ggproto(\n \"PatchFreeAlign\", Parent,\n free_axes = split_position(attr(x, \"free_axes\")),\n get_sizes = function(self, free = NULL, gt = self$gt) {\n ggproto_parent(Parent, self)$get_sizes(\n union(free, self$free_axes),\n gt = gt\n )\n },\n align_border = function(self, t = NULL, l = NULL, b = NULL, r = NULL,\n gt = self$gt) {\n for (axis in self$free_axes) {\n assign(x = axis, value = NULL, envir = environment())\n }\n ggproto_parent(Parent, self)$align_border(\n t = t, l = l, b = b, r = r, gt = gt\n )\n }\n )\n}\n"], ["/ggalign/R/active.R", "#' Plot Adding Context Settings\n#'\n#' @description\n#' `r lifecycle::badge('experimental')`\n#'\n#' These settings control the behavior of the plot when added to a layout, as\n#' well as the arrangement of individual plot areas within the layout.\n#'\n#' @details\n#' By default, the active context is set only for functions that add plot areas.\n#' This allows other `ggplot2` elements-such as `geoms`, `stats`, `scales`, or\n#' `themes`- to be seamlessly added to the current plot area.\n#'\n#' The default ordering of the plot areas is from top to bottom or from left to\n#' right, depending on the layout orientation. However, users can customize this\n#' order using the `order` argument.\n#'\n#' @param order An integer specifying the order of the plot area within the\n#' layout.\n#' @param use A logical (`TRUE`/`FALSE`) indicating whether to set the\n#' active context to the current plot when added to a layout. If `TRUE`,\n#' any subsequent `ggplot` elements will be applied to this plot.\n#' @param name A string specifying the plot's name, useful for switching active\n#' contexts through the `what` argument in functions like\n#' [`quad_anno()`]/[`stack_switch()`].\n#' @export\nactive <- function(order = waiver(), use = waiver(), name = waiver()) {\n if (!is.waive(order)) order <- check_order(order)\n if (!is.waive(use)) assert_bool(use)\n if (!is.waive(name)) {\n assert_string(name,\n empty_ok = FALSE, allow_na = TRUE,\n allow_null = FALSE\n )\n }\n new_active(order = order, use = use, name = name)\n}\n\n# for internal function, we only adjust to the `use` argument\n# here, we put it in the first\nnew_active <- function(use, order = NA_integer_, name = NA_character_) {\n structure(\n list(order = order, use = use, name = name),\n class = \"ggalign_active\"\n )\n}\n\n#' @importFrom utils modifyList\nupdate_active <- function(active, default) {\n if (is.null(active)) return(default) # styler: off\n modifyList(default,\n active[!vapply(active, is.waive, logical(1L), USE.NAMES = FALSE)],\n keep.null = TRUE\n )\n}\n"], ["/ggalign/R/grid-utils.R", "#' @importFrom grid gpar\n#' @export\ngrid::gpar\n\n#' @importFrom grid unit\n#' @export\ngrid::unit\n\nis.gList <- function(x) inherits(x, \"gList\")\n\nis.gTree <- function(x) inherits(x, \"gTree\")\n\n#' @importFrom grid unitType absolute.size\nis_absolute_unit <- function(x) unitType(absolute.size(x)) != \"null\"\n\n#' @importFrom grid unitType\nis_null_unit <- function(x) unitType(x) == \"null\"\n\nis_null_grob <- function(x) inherits(x, c(\"zeroGrob\", \"null\"))\n\n#' @importFrom grid is.grob nullGrob\nensure_grob <- function(x, default = nullGrob()) {\n if (is.gList(x)) x <- gTree(children = x)\n if (is.grob(x)) x else default\n}\n\n# `current.transform()` transforms from *inches* within the current viewport to\n# *inches* on the overall device.\ngrid_solve_loc <- function(loc, trans, valueOnly = FALSE) {\n x <- grid::convertX(loc$x, \"inches\", valueOnly = TRUE)\n y <- grid::convertY(loc$y, \"inches\", valueOnly = TRUE)\n out <- matrix(c(x, y, rep_len(1, length(x))), ncol = 3L) %*%\n trans\n out <- list(x = out[, 1L, drop = TRUE], y = out[, 2L, drop = TRUE])\n if (!valueOnly) out <- lapply(out, unit, \"inches\")\n out\n}\n\nloc_device2vp <- function(x, y, valueOnly = FALSE) {\n assert_s3_class(x, \"unit\")\n assert_s3_class(y, \"unit\")\n if (length(x) != length(y)) {\n cli_abort(\"{.arg x} and {.arg y} must have the same length\")\n }\n assert_bool(valueOnly)\n grid_solve_loc(\n list(x = x, y = y),\n solve(grid::current.transform()),\n valueOnly = valueOnly\n )\n}\n\nloc_vp2device <- function(x, y, valueOnly = FALSE) {\n assert_s3_class(x, \"unit\")\n assert_s3_class(y, \"unit\")\n if (length(x) != length(y)) {\n cli_abort(\"{.arg x} and {.arg y} must have the same length\")\n }\n assert_bool(valueOnly)\n grid::deviceLoc(x, y, valueOnly = valueOnly)\n}\n\n# # allow the missing value in the unit for `str` method\n# ggalign_unit <- function(x, ...) UseMethod(\"ggalign_unit\")\n# #' @export\n# ggalign_unit.default <- function(x, ...) ggalign_unit(as.numeric(x), ...)\n# #' @export\n# ggalign_unit.numeric <- function(x, units = \"null\", data = NULL, ...) {\n# add_class(unit(x, units, data = data), \"ggalign_unit\")\n# }\n# #' @export\n# ggalign_unit.unit <- function(x, ...) add_class(x, \"ggalign_unit\")\n# is_ggalign_unit <- function(x) inherits(x, \"ggalign_unit\")\n\n# # allow the missing value in the unit for `str` method\n#' @importFrom utils str\n#' @export\nstr.unit <- function(object, ...) obj_str(object, ...)\n\n#' @export\nvec_ptype_abbr.unit <- function(x, ...) fclass(x)\n\n#' @importFrom utils str\n#' @export\nobj_str_footer.unit <- function(x, ..., indent.str = \" \", nest.lev = 0,\n give.attr = TRUE) {\n if (!isTRUE(give.attr)) {\n return(invisible(x))\n }\n attr <- attributes(x)\n attr[[\"class\"]] <- NULL\n attr[[\"names\"]] <- NULL\n if (length(attr) == 0) {\n return(invisible(x))\n }\n indent.str <- paste0(\" \", indent.str)\n for (nm in names(attr)) {\n cat(indent.str, paste0(\"- attr(*, \\\"\", nm, \"\\\"):\"), sep = \"\")\n str(\n attr[[nm]],\n no.list = TRUE, ...,\n nest.lev = nest.lev + 1L,\n indent.str = indent.str\n )\n }\n invisible(x)\n}\n\n#' @importFrom gtable gtable_trim\nsubset_gt <- function(gt, index, trim = TRUE) {\n gt$layout <- vec_slice(.subset2(gt, \"layout\"), index)\n gt$grobs <- .subset(.subset2(gt, \"grobs\"), index)\n if (trim) gtable_trim(gt) else gt\n}\n\ngtable_trim_widths <- function(gt) {\n layout <- .subset2(gt, \"layout\")\n w <- range(.subset2(layout, \"l\"), .subset2(layout, \"r\"))\n gt$widths <- .subset2(gt, \"widths\")[seq.int(w[1L], w[2L])]\n if (is.matrix(respect <- .subset2(gt, \"respect\"))) {\n respect <- respect[, seq.int(w[1L], w[2L]), drop = FALSE]\n if (all(respect == 0L)) respect <- FALSE\n gt$respect <- respect\n }\n layout$l <- .subset2(layout, \"l\") - w[1L] + 1L\n layout$r <- .subset2(layout, \"r\") - w[1L] + 1L\n gt$layout <- layout\n gt\n}\n\ngtable_trim_heights <- function(gt) {\n layout <- .subset2(gt, \"layout\")\n h <- range(.subset2(layout, \"t\"), .subset2(layout, \"b\"))\n gt$heights <- .subset2(gt, \"heights\")[seq.int(h[1L], h[2L])]\n if (is.matrix(respect <- .subset2(gt, \"respect\"))) {\n respect <- respect[seq.int(h[1L], h[2L]), , drop = FALSE]\n if (all(respect == 0L)) respect <- FALSE\n gt$respect <- respect\n }\n layout$t <- .subset2(layout, \"t\") - h[1L] + 1L\n layout$b <- .subset2(layout, \"b\") - h[1L] + 1L\n gt$layout <- layout\n gt\n}\n\nliberate_area <- function(gt, top, left, bottom, right,\n clip = \"inherit\", name = NULL, vp = NULL) {\n if (any(remove <- grob_in_area(gt, top, right, bottom, left))) {\n liberated <- gt[top:bottom, left:right]\n if (is.function(vp <- allow_lambda(vp))) {\n liberated$vp <- vp(liberated)\n } else if (inherits(vp, \"viewport\")) {\n liberated$vp <- vp\n }\n liberated$respect <- FALSE\n name <- name %||%\n paste(\n .subset2(.subset2(liberated, \"layout\"), \"name\"),\n collapse = \"; \"\n )\n gt <- subset_gt(gt, !remove, trim = FALSE)\n gt <- gtable_add_grob(\n gt,\n list(liberated),\n top,\n left,\n bottom,\n right,\n z = max(.subset2(.subset2(liberated, \"layout\"), \"z\")),\n clip = clip,\n name = name\n )\n }\n gt\n}\n\ngrob_in_area <- function(gt, top, right, bottom, left) {\n .subset2(.subset2(gt, \"layout\"), \"l\") >= left &\n .subset2(.subset2(gt, \"layout\"), \"t\") >= top &\n .subset2(.subset2(gt, \"layout\"), \"r\") <= right &\n .subset2(.subset2(gt, \"layout\"), \"b\") <= bottom\n}\n\ncompute_null_width <- function(x, unitTo = \"mm\", valueOnly = FALSE) {\n compute_null_unit(x, \"width\", unitTo = unitTo, valueOnly = valueOnly)\n}\n\ncompute_null_height <- function(x, unitTo = \"mm\", valueOnly = FALSE) {\n compute_null_unit(x, \"height\", unitTo = unitTo, valueOnly = valueOnly)\n}\n\n#' @importFrom grid unit convertHeight convertWidth\ncompute_null_unit <- function(x, type = c(\"width\", \"height\"), unitTo = \"mm\",\n valueOnly = FALSE) {\n null <- is_null_unit(x) # null unit\n if (type == \"width\") {\n ans <- convertWidth(x, unitTo, valueOnly = TRUE)\n total <- convertWidth(unit(1, \"npc\"), unitTo = unitTo, valueOnly = TRUE)\n } else {\n ans <- convertHeight(x, unitTo, valueOnly = TRUE)\n total <- convertHeight(\n unit(1, \"npc\"),\n unitTo = unitTo,\n valueOnly = TRUE\n )\n }\n if (any(null)) {\n null_size <- total - sum(ans[!null])\n # other units in the same row/ column also have unit null\n coef <- as.numeric(x[null])\n ans[null] <- (null_size / sum(coef)) * coef\n }\n if (!valueOnly) ans <- unit(ans, unitTo)\n ans\n}\n"], ["/ggalign/R/layout-chain-stack-build.R", "#' @export\nggalign_build.StackLayout <- function(x) {\n x <- default_layout(x)\n (stack_build(x) %||% align_plots(theme = x@theme)) +\n layout_title(\n title = .subset2(x@titles, \"title\"),\n subtitle = .subset2(x@titles, \"subtitle\"),\n caption = .subset2(x@titles, \"caption\")\n )\n}\n\n#' @param schemes,theme Parameters from parent layout\n#' @param extra_design layout parameters of the axis vertically with the stack.\n#' @noRd\nstack_build <- function(stack, schemes = NULL, theme = NULL,\n extra_design = NULL) {\n if (is_empty(stack@plot_list)) {\n return(NULL)\n }\n direction <- stack@direction\n position <- .subset2(stack@heatmap, \"position\")\n schemes <- inherit_parent_layout_schemes(stack, schemes)\n\n if (is_horizontal(direction)) {\n spacing <- \"y\"\n # for horizontal stack, we by default remove top and bottom spaces\n # if (!is.null(position)) {\n # schemes$scheme_align[\"free_spaces\"] <- list(\n # .subset2(schemes$scheme_align, \"free_spaces\") %|w|% \"tb\"\n # )\n # }\n } else {\n spacing <- \"x\"\n # for vertical stack, we by default remove left and right spaces\n # if (!is.null(position)) {\n # schemes$scheme_align[\"free_spaces\"] <- list(\n # .subset2(schemes$scheme_align, \"free_spaces\") %|w|% \"lr\"\n # )\n # }\n }\n theme <- inherit_parent_layout_theme(stack, theme, spacing = spacing)\n composer <- resolve_stack_layout(stack, schemes, theme, extra_design)\n if (is_empty(plots <- .subset2(composer, \"plots\"))) {\n return(NULL)\n }\n\n # arrange plots\n if (is.null(position)) { # for stack layout\n # sizes should be of length 3\n sizes <- stack@sizes\n # recycle the sizes when necessary\n if (length(sizes) == 1L) sizes <- rep(sizes, length.out = 3L)\n sizes <- sizes[\n c(\n .subset2(composer, \"left_or_top\"),\n TRUE,\n .subset2(composer, \"right_or_bottom\")\n )\n ]\n } else { # for the heatmap annotation\n sizes <- NA\n }\n plot <- align_plots(\n !!!plots,\n design = area(\n .subset2(composer, \"t\"),\n .subset2(composer, \"l\"),\n .subset2(composer, \"b\"),\n .subset2(composer, \"r\")\n ),\n widths = switch_direction(\n direction,\n do.call(unit.c, .subset2(composer, \"sizes\")),\n sizes\n ),\n heights = switch_direction(\n direction,\n sizes,\n do.call(unit.c, .subset2(composer, \"sizes\"))\n ),\n guides = .subset2(.subset2(schemes, \"scheme_align\"), \"guides\"),\n theme = stack@theme\n )\n\n # for annotation, we should always make it next to the main body\n if (is.null(position)) {\n return(plot)\n }\n plot <- free_vp(\n plot,\n x = switch(position,\n left = 1L,\n right = 0L,\n 0.5\n ),\n y = switch(position,\n top = 0L,\n bottom = 1L,\n 0.5\n ),\n just = switch(position,\n top = \"bottom\",\n left = \"right\",\n bottom = \"top\",\n right = \"left\"\n )\n )\n\n # whether we should override the `guides` collection for the whole\n # annotation stack\n free_guides <- .subset2(stack@heatmap, \"free_guides\")\n if (!is.waive(free_guides)) plot <- free_guide(plot, free_guides)\n # we also apply the `free_spaces` for the whole annotation stack\n free_spaces <- .subset2(\n .subset2(schemes, \"scheme_align\"), \"free_spaces\"\n ) %|w|% NULL\n if (!is.null(free_spaces)) {\n plot <- free_space(free_border(plot, free_spaces), free_spaces)\n }\n plot\n}\n\n#' @param schemes,theme Parameters for current stack, which have inherited\n#' parameters from the parent.\n#' @noRd\nresolve_stack_layout <- function(stack, schemes, theme, extra_design) {\n UseMethod(\"resolve_stack_layout\")\n}\n\n#' @export\nresolve_stack_layout.StackLayout <- function(stack, schemes, theme,\n extra_design) {\n plot_list <- stack@plot_list\n direction <- stack@direction\n position <- .subset2(stack@heatmap, \"position\")\n\n # we remove the plot without actual plot area\n keep <- vapply(plot_list, function(plot) {\n # we remove objects without plot area\n # Now, only `CraftBox` will contain `NULL`\n !is_craftbox(plot) || !is.null(plot@plot)\n }, logical(1L), USE.NAMES = FALSE)\n plot_list <- .subset(plot_list, keep)\n if (is_empty(plot_list)) return(NULL) # styler: off\n\n # we reorder the plots based on the `order` slot\n plot_order <- vapply(plot_list, function(plot) {\n if (is_layout(plot)) {\n .subset2(plot@plot_active, \"order\")\n } else {\n .subset2(plot@active, \"order\")\n }\n }, integer(1L), USE.NAMES = FALSE)\n plot_list <- .subset(plot_list, make_order(plot_order))\n\n # build the stack\n composer <- stack_composer(direction)\n\n # for `free_spaces`, if we have applied it in the whole stack layout\n # we shouln't use it for a single plot. Otherwise, the guide legends\n # collected by the layout will overlap with the axis of the plot in the\n # layout.\n #\n # this occurs in the annotation stack (`position` is not `NULL`).\n #\n # here is the example:\n # p1 <- ggplot(mtcars) +\n # geom_point(aes(mpg, disp))\n # p2 <- ggplot(mtcars) +\n # geom_boxplot(aes(gear, disp, group = gear, fill = gear))\n # p3 <- ggplot(mtcars) +\n # geom_bar(aes(gear)) +\n # facet_wrap(~cyl)\n # align_plots(\n # free_space(free_border(\n # align_plots(\n # # we shouldn't add free_space for the internal plot\n # free_space(\n # free_border(\n # p1 + scale_y_continuous(\n # expand = expansion(),\n # labels = ~ paste(\"very very long labels\", .x)\n # ),\n # \"l\"\n # ),\n # \"l\"\n # ),\n # p2 + theme(legend.position = \"left\"),\n # guides = \"l\"\n # ),\n # \"l\"\n # ), \"l\"),\n # p3 + theme(plot.margin = margin(l = 5, unit = \"cm\")),\n # ncol = 1\n # )\n stack_spaces <- .subset2(.subset2(schemes, \"scheme_align\"), \"free_spaces\")\n if (is_string(stack_spaces) && !is.null(position)) {\n released_spaces <- stack_spaces\n } else {\n released_spaces <- NULL\n }\n\n design <- setup_design(stack@design)\n stack_composer_add(\n plot_list,\n stack = stack,\n composer,\n schemes = schemes,\n theme = theme,\n design = design,\n extra_design = extra_design,\n direction = direction,\n position = position,\n released_spaces = released_spaces,\n previous_design = NULL\n )\n}\n\nmake_order <- function(order) {\n l <- length(order)\n index <- seq_len(l)\n\n # for order not set by user, we use heuristic algorithm to define the order\n need_action <- is.na(order)\n if (all(need_action)) { # shorthand for the usual way, we don't set any\n return(index)\n } else if (all(!need_action)) { # we won't need do something special\n return(order(order))\n }\n\n # 1. for outliers, we always put them in the two tail\n # 2. for order has been set and is not the outliers,\n # we always follow the order\n # 3. non-outliers were always regarded as the integer index\n used <- as.integer(order[!need_action & order >= 1L & order <= l])\n\n # we flatten user index to continuous integer sequence\n sequence <- vec_unrep(used) # key is the sequence start\n start <- .subset2(sequence, \"key\")\n end <- pmin(\n start + .subset2(sequence, \"times\") - 1L,\n vec_c(start[-1L] - 1L, l) # the next start - 1L\n )\n used <- .mapply(function(s, e) s:e, list(s = start, e = end), NULL)\n\n # following index can be used\n unused <- vec_set_difference(index, unlist(used, FALSE, FALSE))\n\n # we assign the candidate index to the order user not set.\n order[need_action] <- unused[seq_len(sum(need_action))]\n\n # make_order(c(NA, 1, NA)): c(2, 1, 3)\n # make_order(c(NA, 1, 3)): c(2, 1, 3)\n # make_order(c(NA, 1, 3, 1)): c(2, 4, 3, 1)\n order(order)\n}\n"], ["/ggalign/R/ggplot-coord-circle.R", "#' Polar Coordinates with Enhanced Controls\n#'\n#' An extended version of [`coord_radial()`][ggplot2::coord_radial], providing\n#' additional customization options.\n#'\n#' @inheritParams ggplot2::coord_radial\n#' @param thetalim,rlim Limits for the `theta` and `r` axes.\n#' @param inner.radius A numeric in `[0, 1)` indicates the inner radius.\n#' @param outer.radius A numeric in `(0, 1]` indicates the outer radius.\n#' [`coord_radial()`][ggplot2::coord_radial] by default uses `0.8`.\n#' @examples\n#' ggplot(mtcars, aes(disp, mpg)) +\n#' geom_point() +\n#' coord_circle(\n#' start = -0.4 * pi, end = 0.4 * pi,\n#' inner.radius = 0.3, outer.radius = 1\n#' )\n#' ggplot(mtcars, aes(disp, mpg)) +\n#' geom_point() +\n#' coord_circle(\n#' start = -0.4 * pi, end = 0.4 * pi,\n#' inner.radius = 0.3, outer.radius = 0.5\n#' )\n#' @importFrom ggplot2 ggproto\n#' @importFrom rlang arg_match0\n#' @export\ncoord_circle <- function(theta = \"x\", start = 0, end = NULL,\n thetalim = NULL, rlim = NULL, expand = FALSE,\n direction = 1, clip = \"off\",\n r.axis.inside = NULL, rotate.angle = FALSE,\n inner.radius = 0, outer.radius = 0.95) {\n theta <- arg_match0(theta, c(\"x\", \"y\"))\n assert_number_decimal(start, allow_infinite = FALSE)\n assert_number_decimal(end, allow_infinite = FALSE, allow_null = TRUE)\n if (packageVersion(\"ggplot2\") <= \"3.5.2\") {\n assert_bool(expand)\n }\n clip <- arg_match0(clip, c(\"off\", \"on\"))\n\n valid_inside_axis <- .rlang_check_bool(r.axis.inside,\n allow_null = TRUE\n ) ||\n .rlang_check_number(r.axis.inside,\n allow_decimal = TRUE, allow_infinite = FALSE\n ) == 0L\n if (!valid_inside_axis) {\n cli_abort(\n \"{.arg r.axis.inside} must be a single boolean value or a number\"\n )\n }\n\n assert_bool(rotate.angle)\n assert_number_decimal(inner.radius,\n min = 0, max = 1,\n allow_infinite = FALSE\n )\n assert_number_decimal(outer.radius,\n min = 0, max = 1,\n allow_infinite = FALSE\n )\n if (inner.radius >= outer.radius) {\n cli_abort(\n \"{.arg outer.radius} must be larger than {.arg inner.radius}\"\n )\n }\n r <- if (theta == \"x\") \"y\" else \"x\"\n\n arc <- c(start, end %||% (start + 2 * pi))\n if (arc[1] > arc[2]) {\n n_rotate <- ((arc[1] - arc[2]) %/% (2 * pi)) + 1\n arc[1] <- arc[1] - n_rotate * 2 * pi\n }\n r.axis.inside <- r.axis.inside %||% !(abs(arc[2] - arc[1]) >= 1.999 * pi)\n inner_radius <- c(inner.radius, outer.radius) / 2\n\n ggproto(NULL, CoordCircle,\n limits = list(theta = thetalim, r = rlim),\n theta = theta,\n r = r,\n arc = arc,\n expand = expand,\n direction = sign(direction),\n r_axis_inside = r.axis.inside,\n rotate_angle = rotate.angle,\n inner_radius = inner_radius,\n clip = clip\n )\n}\n\n#' @importFrom ggplot2 ggproto_parent\ncircle_panel_params <- function(self, scale_x, scale_y, params = list()) {\n out <- ggproto_parent(ggplot2::CoordRadial, self)$setup_panel_params(\n scale_x, scale_y, params\n )\n if (packageVersion(\"ggplot2\") <= \"3.5.2\") {\n if (self$theta == \"x\") {\n xlimits <- self$limits$theta\n ylimits <- self$limits$r\n } else {\n xlimits <- self$limits$r\n ylimits <- self$limits$theta\n }\n new <- c(\n view_scales_polar(\n scale_x, self$theta, xlimits,\n expand = params$expand[c(4, 2)] %||% self$expand\n ),\n view_scales_polar(\n scale_y, self$theta, ylimits,\n expand = params$expand[c(3, 1)] %||% self$expand\n )\n )\n out[names(new)] <- new\n }\n out$bbox <- ggfun(\"polar_bbox\")(\n self$arc, margin = c(0, 0, 0, 0),\n inner_radius = self$inner_radius\n )\n out\n}\n\nview_scales_polar <- function(scale, theta, coord_limits, expand = TRUE) {\n aesthetic <- scale$aesthetics[1]\n is_theta <- theta == aesthetic\n name <- if (is_theta) \"theta\" else \"r\"\n expansion <- ggfun(\"default_expansion\")(scale, expand = expand)\n limits <- scale$get_limits()\n continuous_range <- ggfun(\"expand_limits_scale\")(\n scale, expansion, limits, coord_limits = coord_limits\n )\n primary <- ggfun(\"view_scale_primary\")(scale, limits, continuous_range)\n view_scales <- list(\n primary,\n sec = ggfun(\"view_scale_secondary\")(scale, limits, continuous_range),\n major = primary$map(primary$get_breaks()),\n minor = primary$map(primary$get_breaks_minor()),\n range = continuous_range\n )\n names(view_scales) <- c(name, paste0(name, \".\", names(view_scales)[-1]))\n view_scales\n}\n\n#' @importFrom ggplot2 ggproto\nCoordCircle <- ggproto(\n \"CoordCircle\", ggplot2::CoordRadial,\n setup_panel_params = circle_panel_params\n)\n"], ["/ggalign/R/ggplot-theme.R", "#' @importFrom ggplot2 theme_bw element_blank\ndefault_theme <- function() {\n if (is_theme_unset()) {\n theme_bw() +\n theme(\n axis.text = ggplot2::element_text(color = \"black\"),\n strip.text = ggplot2::element_text(color = \"black\"),\n panel.border = element_blank(),\n panel.grid = element_blank()\n )\n } else {\n theme_get()\n }\n}\n\n# Check if user has set the theme\nis_theme_unset <- function() {\n isTRUE(all.equal(\n complete_theme(ggfun(\"ggplot_global\")$theme_default),\n complete_theme(theme_get())\n ))\n}\n\nis_theme_complete <- function(x) isTRUE(attr(x, \"complete\", exact = TRUE))\n\n#' @importFrom ggplot2 rel element_blank\ntheme_no_strip <- function() {\n theme(\n strip.text = element_blank(),\n strip.background = element_blank()\n )\n}\n\ntheme_panel_border <- function() theme(panel.border = element_rect(fill = NA))\n\n#' @importFrom utils packageVersion\n#' @importFrom rlang try_fetch\ncomplete_theme <- function(theme) {\n if (packageVersion(\"ggplot2\") > \"3.5.2\") {\n ggfun(\"complete_theme\")(theme)\n } else {\n ggfun(\"plot_theme\")(list(theme = theme))\n }\n}\n\n#' @importFrom ggplot2 register_theme_elements el_def element_line\ntheme_elements <- function() {\n register_theme_elements(\n ggalign.line = element_line(\n color = \"black\",\n linewidth = 0.5,\n linetype = 1,\n lineend = \"butt\",\n linejoin = \"round\"\n ),\n ggalign.polygon = element_polygon(\n fill = NA,\n color = \"black\",\n linewidth = 0.5,\n linetype = 1,\n alpha = NA,\n lineend = \"butt\",\n linejoin = \"round\",\n linemitre = 10\n ),\n element_tree = list(\n plot.patch_title = el_def(\"element_text\", \"text\"),\n plot.patch_title.top = el_def(\"element_text\", \"text\"),\n plot.patch_title.left = el_def(\"element_text\", \"text\"),\n plot.patch_title.bottom = el_def(\"element_text\", \"text\"),\n plot.patch_title.right = el_def(\"element_text\", \"text\"),\n plot.patch_title.position = el_def(\"character\"),\n plot.patch_title.position.top = el_def(\"character\"),\n plot.patch_title.position.left = el_def(\"character\"),\n plot.patch_title.position.bottom = el_def(\"character\"),\n plot.patch_title.position.right = el_def(\"character\"),\n panel.spacing.r = el_def(c(\"unit\", \"rel\"), \"panel.spacing\"),\n ggalign.line = el_def(\"element_line\"),\n ggalign.curve = el_def(\"element_curve\"),\n ggalign.polygon = el_def(\"element_polygon\")\n )\n )\n}\n\n#' Used to match theme\n#'\n#' @keywords internal\n#' @noRd\ntheme_recycle <- function() structure(list(), class = \"theme_recycle\")\n\n#' @importFrom ggplot2 ggplot_add ggproto ggproto_parent\n#' @export\nggplot_add.theme_recycle <- function(object, plot, object_name, ...) {\n ParentFacet <- plot$facet\n if (!inherits(ParentFacet, c(\"FacetGrid\", \"FacetWrap\"))) {\n return(plot)\n }\n # recycle axis theme elements\n plot$facet <- ggproto(\n NULL, ParentFacet,\n draw_panels = function(self, panels, layout,\n x_scales = NULL, y_scales = NULL,\n ranges, coord, data = NULL, theme, params) {\n # we recycle the theme elements of the guide axis\n theme <- recycle_theme_axis(\"x\", theme, x_scales)\n theme <- recycle_theme_axis(\"y\", theme, y_scales)\n ParentCoord <- coord\n h_tick0 <- h_text0 <- 0L\n v_tick0 <- v_text0 <- 0L\n # subset theme for each panel\n coord <- ggproto(NULL, ParentCoord,\n # `align_scales` will attach the `.__plot_index__`\n render_axis_h = function(self, panel_params, theme) {\n scale <- (.subset2(panel_params, \"x\") %||%\n .subset2(panel_params, \"theta\")\n )$scale\n h_tick1 <- h_tick0 + length(scale$get_breaks())\n h_text1 <- h_text0 + length(scale$get_labels())\n theme <- subset_theme_axis(\n \"x\", theme, h_tick0, h_text0, h_tick1, h_text1\n )\n h_tick0 <<- h_tick1\n h_text0 <<- h_text1\n ggproto_parent(ParentCoord, self)$render_axis_h(\n panel_params, theme\n )\n },\n render_axis_v = function(self, panel_params, theme) {\n scale <- (.subset2(panel_params, \"y\") %||%\n .subset2(panel_params, \"r\")\n )$scale\n v_tick1 <- v_tick0 + length(scale$get_breaks())\n v_text1 <- v_text0 + length(scale$get_labels())\n theme <- subset_theme_axis(\n \"y\", theme, v_tick0, v_text0, v_tick1, v_text1\n )\n v_tick0 <<- v_tick1\n v_text0 <<- v_text1\n ggproto_parent(ParentCoord, self)$render_axis_v(\n panel_params, theme\n )\n }\n )\n ggproto_parent(ParentFacet, self)$draw_panels(\n panels = panels, layout = layout,\n x_scales = x_scales, y_scales = y_scales,\n ranges = ranges, coord = coord, data = data,\n theme = theme, params = params\n )\n }\n )\n plot\n}\n\n#################################################################\n# Apply a function to the vectorized field of the theme object\ntheme_vec <- function(.th, .el, .fn, ...) {\n element <- calc_element(.el, .th)\n if (inherits(element, \"element\")) {\n .th[[.el]] <- element_vec(element, .fn, ...)\n } else if (!is.null(element)) {\n .th[[.el]] <- .fn(element, ...)\n }\n .th\n}\n\nrecycle_theme_axis <- function(axis, theme, scales) {\n breaks <- unlist(lapply(scales, function(s) s$get_breaks()), FALSE, FALSE)\n labels <- unlist(lapply(scales, function(x) x$get_labels()), FALSE, FALSE)\n align_theme_axis(axis, theme,\n tick_fn = function(v, arg) rep(v, length.out = length(breaks)),\n text_fn = function(v, arg) rep(v, length.out = length(labels))\n )\n}\n\nsubset_theme_axis <- function(axis, theme, tick0, text0, tick1, text1) {\n tick_index <- (tick0 + 1L):tick1\n text_index <- (text0 + 1L):text1\n align_theme_axis(\n axis, theme,\n tick_fn = function(value) vec_slice(value, tick_index),\n text_fn = function(value) vec_slice(value, text_index)\n )\n}\n\nalign_theme_axis <- function(axis, theme, text_fn, tick_fn) {\n if (axis == \"y\") {\n positions <- c(\"left\", \"right\")\n } else {\n positions <- c(\"top\", \"bottom\")\n }\n # only apply the function when the element values is not a scalar\n .text_fn <- function(v) if (length(v) > 1L) text_fn(v) else v\n .tick_fn <- function(v) if (length(v) > 1L) tick_fn(v) else v\n for (element in paste(\"axis.text\", axis, positions, sep = \".\")) {\n theme <- theme_vec(theme, element, .text_fn)\n }\n for (element in paste(\"axis.ticks\", axis, positions, sep = \".\")) {\n theme <- theme_vec(theme, element, .tick_fn)\n }\n for (element in paste(\"axis.ticks.length\", axis, positions, sep = \".\")) {\n theme <- theme_vec(theme, element, .tick_fn)\n }\n theme\n}\n"], ["/ggalign/R/layer-order.R", "#' Change the layer adding order\n#'\n#' @description\n#' This function allows you to change the order in which layers are added to a\n#' ggplot.\n#'\n#' @param layer A [`layer geometry`][ggplot2::layer_geoms] object to be added.\n#' @param order An integer indicating the position at which the layer should be\n#' added. If `<= 0`, the layer will be added at the beginning. If greater than\n#' the number of plot layers, it will be added at the end.\n#' @return A `layer_order` object.\n#' @examples\n#' ggplot(faithfuld, aes(waiting, eruptions)) +\n#' geom_raster(aes(fill = density)) +\n#' geom_point(color = \"red\", size = 1)\n#' ggplot(faithfuld, aes(waiting, eruptions)) +\n#' geom_raster(aes(fill = density)) +\n#' layer_order(geom_point(color = \"red\", size = 1))\n#' @export\nlayer_order <- function(layer, order = 0) {\n assert_number_decimal(order)\n UseMethod(\"layer_order\")\n}\n\n#' @export\nlayer_order.default <- function(layer, order = 0) {\n cli_abort(\"{.arg layer} must be a {.fn geom_*} object\")\n}\n\n#' @export\nlayer_order.Layer <- function(layer, order = 0) {\n if (!is.infinite(order)) order <- vec_cast(order, integer())\n structure(\n list(\n object = layer,\n order = order,\n # used for `ggplot_add`\n object_name = paste(deparse(substitute(layer)), collapse = \" \")\n ),\n class = \"ggalign_layer_order\"\n )\n}\n\n#' @export\nlayer_order.ggalign_layer_order <- function(layer, order = 0) {\n if (!is.infinite(order)) order <- vec_cast(order, integer())\n layer$order <- order\n layer\n}\n\n#' @importFrom ggplot2 ggplot_add\n#' @export\nggplot_add.ggalign_layer_order <- function(object, plot, object_name, ...) {\n # ggplot2 will do something special for the layer\n # add layer_name, we re-call the method for the layer\n ans <- ggplot_add(\n .subset2(object, \"object\"),\n plot, .subset2(object, \"object_name\")\n )\n if ((cur <- length(layers <- ans$layers)) == 1L) {\n return(ans)\n }\n order <- .subset2(object, \"order\")\n layer <- .subset2(layers, cur)\n if (order >= length(layers)) return(ans) # styler: off\n if (order <= 0L) {\n layers <- append(vec_slice(layers, -cur), layer, 0L)\n } else {\n layers <- append(vec_slice(layers, -cur), layer, order)\n }\n ans$layers <- layers\n ans\n}\n"], ["/ggalign/R/scheme-.R", "new_schemes <- function(...) {\n default <- list(\n new_scheme_data(),\n new_scheme_align(),\n new_scheme_theme()\n )\n names(default) <- vapply(default, ggalign_scheme_name,\n character(1L),\n USE.NAMES = FALSE\n )\n for (i in seq_len(...length())) {\n scheme <- ...elt(i)\n default[[ggalign_scheme_name(scheme)]] <- scheme\n }\n default\n}\n\nnew_scheme <- function(name, data, ..., class = character()) {\n structure(data,\n `__ggalign.scheme_name__` = name, ...,\n class = c(class, \"ggalign_scheme\")\n )\n}\n\nggalign_scheme_name <- function(x) {\n attr(x, \"__ggalign.scheme_name__\", exact = TRUE)\n}\n\n#' @importFrom ggplot2 theme\ndefault_schemes <- function(data = NULL, th = theme()) {\n if (!is.waive(data)) data <- NULL\n new_schemes(\n new_scheme_data(data),\n new_scheme_theme(th)\n )\n}\n\n###############################################################\n#' Used to update global data\n#' @noRd\nupdate_scheme <- function(new, old, object_name) {\n UseMethod(\"update_scheme\", old)\n}\n\n#' @export\nupdate_scheme.default <- function(new, old, object_name) new\n\nupdate_layout_scheme <- function(object, layout, object_name) {\n name <- ggalign_scheme_name(object)\n layout@schemes[name] <- list(update_scheme(\n object, .subset2(layout@schemes, name), object_name\n ))\n layout\n}\n\n###############################################################\ninherit_scheme <- function(scheme, pscheme) {\n UseMethod(\"inherit_scheme\", pscheme)\n}\n\n# If no parent scheme, use child scheme directly\n#' @export\ninherit_scheme.NULL <- function(scheme, pscheme) scheme\n\ninherit_schemes <- function(schemes, pschemes) {\n nms <- vapply(pschemes,\n ggalign_scheme_name, character(1L),\n USE.NAMES = FALSE\n )\n ans <- lapply(nms, function(opt) {\n inherit_scheme(.subset2(schemes, opt), .subset2(pschemes, opt))\n })\n names(ans) <- nms\n ans\n}\n\n###############################################################\nplot_add_scheme <- function(plot, scheme) UseMethod(\"plot_add_scheme\", scheme)\n\n#' @export\nplot_add_scheme.NULL <- function(plot, scheme) plot\n\nplot_add_schemes <- function(plot, schemes) {\n for (i in seq_along(schemes)) {\n plot <- plot_add_scheme(plot, scheme = .subset2(schemes, i))\n }\n plot\n}\n"], ["/ggalign/R/craft-align-group.R", "#' Group and align observations based on a group vector\n#'\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' Splits observations into groups, with slice ordering based on group levels.\n#'\n#' @param group A character define the groups of the observations.\n#' @inheritParams align\n#' @examples\n#' set.seed(1L)\n#' small_mat <- matrix(rnorm(81), nrow = 9)\n#' ggheatmap(small_mat) +\n#' anno_top() +\n#' align_group(sample(letters[1:4], ncol(small_mat), replace = TRUE))\n#' @export\nalign_group <- function(group, active = NULL) {\n assert_active(active)\n if (vec_size(group) == 0L) {\n cli_abort(\"{.arg group} cannot be empty\")\n }\n active <- update_active(active, new_active(use = FALSE))\n align(\n align = AlignGroup,\n group = group,\n active = active,\n check.param = TRUE\n )\n}\n\n#' @importFrom ggplot2 ggproto\nAlignGroup <- ggproto(\"AlignGroup\", CraftAlign,\n interact_layout = function(self, layout) {\n layout <- ggproto_parent(CraftAlign, self)$interact_layout(layout)\n if (is.null(layout_nobs <- .subset2(layout@design, \"nobs\"))) {\n layout@design[\"nobs\"] <- list(vec_size(self$group))\n } else {\n assert_mismatch_nobs(\n self, layout_nobs, vec_size(self$group),\n arg = \"group\"\n )\n }\n layout\n },\n align = function(self, panel, index) list(self$group, index),\n summary_align = function(self) c(FALSE, TRUE)\n)\n"], ["/ggalign/R/layout-chain-operator.R", "#' @keywords internal\nchain_layout_subtract <- function(object, layout, object_name) {\n UseMethod(\"chain_layout_subtract\")\n}\n\n#' @export\nchain_layout_subtract.default <- function(object, layout, object_name) {\n if (is.null(active_index <- layout@active) ||\n is_craftbox(plot <- .subset2(layout@plot_list, active_index))) {\n layout@plot_list <- lapply(layout@plot_list, function(plot) {\n if (is_craftbox(plot)) {\n chain_plot_add(plot, object, object_name, force = FALSE)\n } else {\n plot\n }\n })\n } else {\n layout@plot_list[[active_index]] <- quad_layout_subtract(\n object, plot, object_name\n )\n }\n layout\n}\n\n# for objects can inherit from layout\n#' @export\nchain_layout_subtract.ggalign_scheme <- function(object, layout, object_name) {\n if (is.null(active_index <- layout@active) ||\n is_craftbox(plot <- .subset2(layout@plot_list, active_index))) {\n layout <- update_layout_scheme(object, layout, object_name)\n } else {\n layout@plot_list[[active_index]] <- quad_layout_subtract(\n object, plot, object_name\n )\n }\n layout\n}\n\n#' @export\nchain_layout_subtract.ggalign_with_quad <- function(object, layout,\n object_name) {\n if (!is_stack_layout(layout)) {\n cli_abort(sprintf(\n \"Cannot add {.var {object_name}} to %s\",\n object_name(layout)\n ))\n }\n if (is.null(active_index <- layout@active) ||\n is_craftbox(plot <- .subset2(layout@plot_list, active_index))) {\n inner <- .subset2(object, \"object\")\n inner_name <- .subset2(object, \"object_name\")\n\n # subtract set at layout level, if it is a plot option\n # we only apply to current active layout\n if (inherits(inner, \"ggalign_scheme\")) {\n layout <- update_layout_scheme(inner, layout, inner_name)\n return(layout)\n }\n\n # otherwise, we apply the object to all plots in the stack layout\n direction <- layout@direction\n layout@plot_list <- lapply(layout@plot_list, function(plot) {\n if (is_craftbox(plot)) {\n plot <- chain_plot_add(plot, inner, inner_name, force = FALSE)\n } else if (is.waive(.subset2(object, \"position\"))) {\n # default behaviour for object wrap with `with_quad()`\n # we add the object along the stack layout\n # if means for horizontal stack, we'll add it\n # to the left and right annotation, and the main plot\n positions <- switch_direction(\n direction,\n c(\"left\", \"right\"),\n c(\"top\", \"bottom\")\n )\n for (position in positions) {\n if (!is.null(slot(plot, position))) {\n slot(plot, position) <- chain_layout_subtract(\n inner, slot(plot, position), inner_name\n )\n }\n }\n if (is.null(main <- .subset2(object, \"main\")) || main) {\n plot <- quad_body_add(inner, plot, inner_name)\n }\n } else {\n # we respect the context setting\n plot <- quad_layout_subtract(object, plot, object_name)\n }\n plot\n })\n } else {\n layout@plot_list[[active_index]] <- quad_layout_subtract(\n object, plot, object_name\n )\n }\n layout\n}\n\n##################################################################\n#' @keywords internal\nchain_layout_and_add <- function(object, layout, object_name) {\n UseMethod(\"chain_layout_and_add\")\n}\n\n#' @export\nchain_layout_and_add.ggalign_with_quad <- function(object, layout, object_name) {\n if (!is_stack_layout(layout)) {\n cli_abort(sprintf(\n \"Cannot add {.var {object_name}} to %s\",\n object_name(layout)\n ))\n }\n object <- .subset2(object, \"object\")\n object_name <- .subset2(object, \"object_name\")\n NextMethod()\n}\n\n#' @export\nchain_layout_and_add.default <- function(object, layout, object_name) {\n layout@plot_list <- lapply(layout@plot_list, function(plot) {\n if (is_craftbox(plot)) {\n plot <- chain_plot_add(plot, object, object_name, force = FALSE)\n } else {\n plot <- quad_layout_and_add(object, plot, object_name)\n }\n plot\n })\n layout\n}\n\n#' @export\nchain_layout_and_add.theme <- function(object, layout, object_name) {\n ans <- NextMethod()\n # to align with `patchwork`, we also modify the layout theme\n # when using `&` to add the theme object.\n ans@theme <- ggfun(\"add_theme\")(ans@theme, object)\n ans\n}\n"], ["/ggalign/R/layout-chain-stack-composer.R", "#' @keywords internal\nstack_composer <- function(direction) {\n structure(\n list(\n t = integer(), l = integer(),\n b = integer(), r = integer(),\n plots = list(), sizes = list(),\n direction = direction,\n align = 1L,\n # attributes used by `stack_layout()`\n left_or_top = FALSE, right_or_bottom = FALSE\n ),\n class = \"stack_composer\"\n )\n}\n\nstack_composer_add_plot <- function(composer, plot, t, l, b = t, r = l) {\n composer$t <- c(.subset2(composer, \"t\"), t)\n composer$l <- c(.subset2(composer, \"l\"), l)\n composer$b <- c(.subset2(composer, \"b\"), b)\n composer$r <- c(.subset2(composer, \"r\"), r)\n composer$plots <- c(.subset2(composer, \"plots\"), list(plot))\n composer\n}\n\n#' @importFrom rlang is_empty\nstack_composer_align_plot <- function(composer, plot, size) {\n if (is.null(plot)) {\n return(composer)\n }\n if (is_horizontal(.subset2(composer, \"direction\"))) {\n r_border <- .subset2(composer, \"r\")\n if (is_empty(r_border)) {\n l <- 1L\n } else {\n l <- max(r_border) + 1L\n }\n t <- .subset2(composer, \"align\")\n } else {\n b_border <- .subset2(composer, \"b\")\n if (is_empty(b_border)) {\n t <- 1L\n } else {\n t <- max(b_border) + 1L\n }\n l <- .subset2(composer, \"align\")\n }\n composer$sizes <- c(.subset2(composer, \"sizes\"), list(size))\n stack_composer_add_plot(composer, plot, t, l)\n}\n\nstack_composer_add <- function(plot, stack, composer, ...) {\n UseMethod(\"stack_composer_add\")\n}\n\n#' @importFrom utils packageVersion\n#' @export\nstack_composer_add.CraftBox <- function(plot, stack, composer, design, ...,\n schemes, theme,\n released_spaces,\n direction, position) {\n size <- plot@size\n\n # for `released_spaces`, release the `free_spaces` in a single plot\n plot_schemes <- inherit_schemes(plot@schemes, schemes)\n if (!is.null(released_spaces)) {\n plot_spaces <- .subset2(\n .subset2(plot_schemes, \"scheme_align\"), \"free_spaces\"\n )\n if (is_string(plot_spaces)) {\n plot_spaces <- setdiff_position(plot_spaces, released_spaces)\n if (!nzchar(plot_spaces)) plot_spaces <- NULL\n plot_schemes$scheme_align[\"free_spaces\"] <- list(plot_spaces)\n }\n }\n\n # let `Align` to determine how to build the plot\n craftsman <- plot@craftsman # `Craftsman` object\n plot <- plot@plot\n if (!craftsman$free_facet && is_discrete_design(design)) {\n if (nlevels(.subset2(design, \"panel\")) > 1L) {\n if (is_horizontal(direction)) {\n facet <- ggplot2::facet_grid(\n rows = ggplot2::vars(.data$.panel),\n scales = \"free_y\", space = \"free\",\n drop = FALSE, as.table = FALSE\n )\n free_row <- FALSE\n free_column <- TRUE\n } else {\n facet <- ggplot2::facet_grid(\n cols = ggplot2::vars(.data$.panel),\n scales = \"free_x\", space = \"free\",\n drop = FALSE, as.table = FALSE\n )\n free_row <- TRUE\n free_column <- FALSE\n }\n } else {\n facet <- facet_stack(direction, craftsman$layout_name)\n }\n plot <- ggmelt_facet(plot, facet,\n free_row = free_row, free_column = free_column\n )\n }\n if (!craftsman$free_coord) {\n plot <- gguse_linear_coord(plot, layout_name = craftsman$layout_name)\n }\n\n # set limits and default scales\n if (!craftsman$free_limits) {\n if (is_horizontal(direction)) {\n plot <- plot + ggalign_design(\n y = design,\n ylabels = .subset(craftsman$labels, .subset2(design, \"index\"))\n )\n } else {\n plot <- plot + ggalign_design(\n x = design,\n xlabels = .subset(craftsman$labels, .subset2(design, \"index\"))\n )\n }\n }\n\n # let `Craftsman` add other components\n plot <- craftsman$build_plot(plot, design = design, ...)\n plot <- craftsman$finish_plot(plot, plot_schemes, theme)\n\n # Let layout finally modify the plot\n plot <- chain_decorate(stack, plot)\n\n # add the plot to the composer\n stack_composer_align_plot(composer, plot, size)\n}\n\n#' @importFrom grid unit.c unit\nstack_composer_add.QuadLayout <- function(plot, stack, composer, schemes, theme,\n direction, ...) {\n patches <- quad_build(plot, schemes, theme, direction)\n plots <- .subset2(patches, \"plots\")\n sizes <- .subset2(patches, \"sizes\")\n\n if (is_horizontal(.subset2(composer, \"direction\"))) {\n composer$left_or_top <- .subset2(composer, \"left_or_top\") ||\n !is.null(.subset2(plots, \"top\"))\n composer$right_or_bottom <- .subset2(composer, \"right_or_bottom\") ||\n !is.null(.subset2(plots, \"bottom\"))\n composer <- stack_composer_align_plot(\n composer,\n .subset2(plots, \"left\"),\n .subset2(sizes, \"left\")\n )\n composer <- stack_composer_align_plot(\n composer,\n .subset2(plots, \"main\"),\n .subset2(.subset2(sizes, \"main\"), \"width\")\n )\n l <- max(.subset2(composer, \"r\"))\n if (!is.null(top <- .subset2(plots, \"top\"))) {\n if (.subset2(composer, \"align\") == 1L) {\n composer$t <- .subset2(composer, \"t\") + 1L\n composer$b <- .subset2(composer, \"b\") + 1L\n composer$align <- .subset2(composer, \"align\") + 1L\n }\n if (!is_null_unit(size <- .subset2(sizes, \"top\"))) {\n attr(top, \"vp\")$height <- size\n }\n composer <- stack_composer_add_plot(composer, top, t = 1L, l = l)\n }\n if (!is.null(bottom <- .subset2(plots, \"bottom\"))) {\n if (!is_null_unit(size <- .subset2(sizes, \"bottom\"))) {\n attr(bottom, \"vp\")$height <- size\n }\n composer <- stack_composer_add_plot(composer, bottom,\n t = .subset2(composer, \"align\") + 1L, l = l\n )\n }\n composer <- stack_composer_align_plot(\n composer,\n .subset2(plots, \"right\"),\n .subset2(sizes, \"right\")\n )\n } else {\n composer$left_or_top <- .subset2(composer, \"left_or_top\") ||\n !is.null(.subset2(plots, \"left\"))\n composer$right_or_bottom <- .subset2(composer, \"right_or_bottom\") ||\n !is.null(.subset2(plots, \"right\"))\n composer <- stack_composer_align_plot(\n composer,\n .subset2(plots, \"top\"),\n .subset2(sizes, \"top\")\n )\n composer <- stack_composer_align_plot(\n composer,\n .subset2(plots, \"main\"),\n .subset2(.subset2(sizes, \"main\"), \"height\")\n )\n t <- max(.subset2(composer, \"b\"))\n if (!is.null(left <- .subset2(plots, \"left\"))) {\n if (.subset2(composer, \"align\") == 1L) {\n composer$l <- .subset2(composer, \"l\") + 1L\n composer$r <- .subset2(composer, \"r\") + 1L\n composer$align <- .subset2(composer, \"align\") + 1L\n }\n if (!is_null_unit(size <- .subset2(sizes, \"left\"))) {\n attr(left, \"vp\")$width <- size\n }\n composer <- stack_composer_add_plot(composer, left, t = t, l = 1L)\n }\n if (!is.null(right <- .subset2(plots, \"right\"))) {\n if (!is_null_unit(size <- .subset2(sizes, \"right\"))) {\n attr(right, \"vp\")$width <- size\n }\n composer <- stack_composer_add_plot(composer, right,\n t = t, l = .subset2(composer, \"align\") + 1L\n )\n }\n composer <- stack_composer_align_plot(\n composer,\n .subset2(plots, \"bottom\"),\n .subset2(sizes, \"bottom\")\n )\n }\n composer\n}\n\n#' @export\nstack_composer_add.list <- function(plot, stack, composer, ...) {\n for (p in plot) {\n composer <- stack_composer_add(\n plot = p, stack = stack, composer = composer, ...\n )\n }\n composer\n}\n"], ["/ggalign/R/alignpatch-free-vp.R", "#' @inheritParams grid::viewport\n#' @inheritDotParams grid::viewport -x -y -width -height\n#' @return\n#' - `free_vp`: A modified version of `plot` with a `free_vp` class.\n#' @importFrom grid viewport\n#' @export\n#' @rdname free\nfree_vp <- function(plot, x = 0.5, y = 0.5, width = NA, height = NA, ...) {\n UseMethod(\"free_vp\")\n}\n\n#' @export\nfree_vp.default <- function(plot, x = 0.5, y = 0.5,\n width = NA, height = NA, ...) {\n cli_abort(\"Cannot use with {.obj_type_friendly {plot}}\")\n}\n\n#' @export\nfree_vp.ggplot <- function(plot, x = 0.5, y = 0.5,\n width = NA, height = NA, ...) {\n attr(plot, \"vp\") <- viewport(\n x = x, y = y, width = width, height = height, ...,\n )\n add_class(plot, \"free_vp\")\n}\n\n#' @export\nfree_vp.alignpatches <- free_vp.ggplot\n\n####################################################\n#' @importFrom gtable gtable_width gtable_height\n#' @importFrom ggplot2 ggproto ggproto_parent\n#' @export\nalignpatch.free_vp <- function(x) {\n Parent <- NextMethod()\n ggproto(\n \"PatchFreeViewport\", Parent,\n vp = attr(x, \"vp\"),\n align_border = function(self, t = NULL, l = NULL, b = NULL, r = NULL,\n gt = self$gt) {\n ans <- ggproto_parent(Parent, self)$align_border(\n t = t, l = l, b = b, r = r, gt = gt\n )\n vp <- self$vp\n\n if (!any(is_null_unit(widths <- .subset2(ans, \"widths\")))) {\n horizontal_just <- TRUE\n vp$width <- sum(widths)\n } else if (!is.na(as.numeric(vp$width))) {\n # we guess the width from the gtable\n horizontal_just <- TRUE\n vp$width <- max(vp$width, sum(widths))\n } else {\n vp$width <- unit(1, \"npc\")\n horizontal_just <- FALSE\n }\n if (!any(is_null_unit(heights <- .subset2(ans, \"heights\")))) {\n vertical_just <- TRUE\n vp$height <- sum(heights)\n } else if (!is.na(as.numeric(vp$height))) {\n # we guess the height from the gtable\n vertical_just <- TRUE\n vp$height <- max(vp$height, sum(heights))\n } else {\n vp$height <- unit(1, \"npc\")\n vertical_just <- FALSE\n }\n if (horizontal_just || vertical_just) ans$vp <- vp\n ans\n }\n )\n}\n"], ["/ggalign/R/alignpatch-ggplot2.R", "#' @export\nggalign_gtable.ggplot <- function(x) alignpatch(x)$patch_gtable()\n\n#' @export\nggalign_build.ggplot <- function(x) x\n\n##################################################\n#' @export\n#' @include alignpatch-build.R\nprint.patch_ggplot <- print.alignpatches\n\n#' @importFrom grid grid.draw\n#' @exportS3Method\ngrid.draw.patch_ggplot <- grid.draw.alignpatches\n\n#################################################\n#' @importFrom ggplot2 ggproto\n#' @export\nalignpatch.ggplot <- function(x) ggproto(NULL, PatchGgplot, plot = x)\n\n# ggplot2 has following grobs:\n# panel\n# axis: must follow panel\n# strip: must follow the panel\n# xlab/ylab: can be aligned or follow the panel\n# subtitle\n# title\n# caption\n# guide: can be collected or kept\n#' @importFrom ggplot2 ggplotGrob update_labels\n#' @include alignpatch-.R\nPatchGgplot <- ggproto(\"PatchGgplot\", Patch,\n set_guides = function(guides) guides,\n patch_gtable = function(self, theme, guides, plot = self$plot) {\n # extract patch titles --------------------------------\n patch_titles <- plot$ggalign_patch_labels\n\n # complete_theme() will ensure elements exist --------\n theme <- complete_theme(plot$theme)\n # here: we remove tick length when the tick is blank\n theme <- setup_tick_length_element(theme)\n plot$theme <- theme\n\n # build the grob -------------------------------------\n ans <- ggplotGrob(plot)\n strip_pos <- find_strip_pos(ans)\n # always add strips columns and/or rows\n ans <- add_strips(ans, strip_pos)\n setup_patch_titles(ans, patch_titles = patch_titles, theme = theme)\n },\n respect = function(self, gt = self$gt) .subset2(gt, \"respect\"),\n\n #' @importFrom ggplot2 find_panel\n align_panel_sizes = function(self, panel_width, panel_height,\n gt = self$gt) {\n panel_pos <- find_panel(gt)\n rows <- c(.subset2(panel_pos, \"t\"), .subset2(panel_pos, \"b\"))\n cols <- c(.subset2(panel_pos, \"l\"), .subset2(panel_pos, \"r\"))\n respect <- .subset2(gt, \"respect\")\n if (rows[1L] == rows[2L] && cols[1L] == cols[2L]) {\n if (respect) {\n can_set_width <- is.na(as.numeric(panel_width))\n can_set_height <- is.na(as.numeric(panel_height))\n w <- .subset2(gt, \"widths\")[LEFT_BORDER + 1L]\n h <- .subset2(gt, \"heights\")[TOP_BORDER + 1L]\n if (can_set_width && can_set_height) {\n panel_width <- w\n panel_height <- h\n } else if (can_set_width) {\n panel_width <- as.numeric(w) / as.numeric(h) * panel_height\n } else if (can_set_height) {\n panel_height <- as.numeric(h) / as.numeric(w) * panel_width\n } else {\n respect <- FALSE\n }\n }\n } else {\n respect <- FALSE\n }\n list(width = panel_width, height = panel_height, respect = respect)\n },\n\n #' @importFrom gtable gtable_add_grob gtable_height gtable_width\n #' @importFrom grid unit viewport\n #' @importFrom ggplot2 find_panel\n free_border = function(self, borders, gt = self$gt) {\n panel_pos <- find_panel(gt)\n for (border in borders) {\n if (border == \"top\") {\n gt <- liberate_area(\n gt,\n 1L,\n 1L,\n .subset2(panel_pos, \"t\") - 1L,\n ncol(gt),\n clip = \"off\",\n name = \"free-border-top\",\n vp = ~ viewport(\n y = 0L, just = \"bottom\",\n height = gtable_height(.x)\n )\n )\n } else if (border == \"left\") {\n gt <- liberate_area(\n gt,\n 1L,\n 1L,\n nrow(gt),\n .subset2(panel_pos, \"l\") - 1L,\n clip = \"off\",\n name = \"free-border-left\",\n vp = ~ viewport(\n x = 1L, just = \"right\",\n width = gtable_width(.x)\n )\n )\n } else if (border == \"bottom\") {\n gt <- liberate_area(\n gt,\n .subset2(panel_pos, \"b\") + 1L,\n 1L,\n nrow(gt),\n ncol(gt),\n clip = \"off\",\n name = \"free-border-bottom\",\n vp = ~ viewport(\n y = 1L, just = \"top\",\n height = gtable_height(.x)\n )\n )\n } else if (border == \"right\") {\n gt <- liberate_area(\n gt,\n 1L,\n .subset2(panel_pos, \"r\") + 1L,\n nrow(gt),\n ncol(gt),\n clip = \"off\",\n name = \"free-border-right\",\n vp = ~ viewport(\n x = 0L, just = \"left\",\n width = gtable_width(.x)\n )\n )\n }\n }\n gt\n },\n align_free_border = function(self, borders,\n t = NULL, l = NULL, b = NULL, r = NULL,\n gt = self$gt) {\n if (is.null(t) && is.null(l) && is.null(b) && is.null(r)) {\n return(gt)\n }\n # For free borders, we also align the margins\n for (border in borders) {\n i <- .subset2(.subset2(gt, \"layout\"), \"name\") ==\n sprintf(\"free-border-%s\", border)\n if (any(i)) {\n i <- which(i)\n gt$grobs[[i]] <- switch_position(\n border,\n Patch$align_border(l = l, r = r, gt = gt$grobs[[i]]),\n Patch$align_border(t = t, b = b, gt = gt$grobs[[i]])\n )\n }\n }\n gt\n },\n\n #' @importFrom ggplot2 find_panel\n #' @importFrom gtable is.gtable gtable_height gtable_width gtable_add_grob\n #' @importFrom grid grobHeight grobWidth viewport\n free_lab = function(self, labs, gt = self$gt) {\n panel_pos <- find_panel(gt)\n for (lab in labs) {\n name <- paste(\n switch_position(lab, \"xlab\", \"ylab\"),\n \"axis\", lab,\n sep = \"-\"\n )\n if (lab == \"top\") {\n panel_border <- .subset2(panel_pos, \"t\")\n gt <- liberate_area(\n gt,\n panel_border - 3L,\n .subset2(panel_pos, \"l\"),\n panel_border - 1L,\n .subset2(panel_pos, \"r\"),\n name = name,\n vp = ~ viewport(\n y = 0L, just = \"bottom\",\n height = gtable_height(.x)\n )\n )\n } else if (lab == \"left\") {\n panel_border <- .subset2(panel_pos, \"l\")\n gt <- liberate_area(\n gt,\n .subset2(panel_pos, \"t\"),\n panel_border - 3L,\n .subset2(panel_pos, \"b\"),\n panel_border - 1L,\n name = name,\n vp = ~ viewport(\n x = 1L, just = \"right\",\n width = gtable_width(.x)\n )\n )\n } else if (lab == \"bottom\") {\n panel_border <- .subset2(panel_pos, \"b\")\n gt <- liberate_area(\n gt,\n panel_border + 1L,\n .subset2(panel_pos, \"l\"),\n panel_border + 3L,\n .subset2(panel_pos, \"r\"),\n name = name,\n vp = ~ viewport(\n y = 1L, just = \"top\",\n height = gtable_height(.x)\n )\n )\n } else if (lab == \"right\") {\n panel_border <- .subset2(panel_pos, \"r\")\n gt <- liberate_area(\n gt,\n .subset2(panel_pos, \"t\"),\n panel_border + 1L,\n .subset2(panel_pos, \"b\"),\n panel_border + 3L,\n name = name,\n vp = ~ viewport(\n x = 0L, just = \"left\",\n width = gtable_width(.x)\n )\n )\n }\n }\n gt\n }\n)\n\n#' @importFrom ggplot2 calc_element\n#' @importFrom grid unit\nsetup_tick_length_element <- function(theme) {\n for (tick in c(\"x.top\", \"y.left\", \"x.bottom\", \"y.right\")) {\n for (axis in c(\"axis.minor\", \"axis\")) {\n blank <- inherits(calc_element(\n paste(axis, \"ticks\", tick, sep = \".\"), theme\n ), \"element_blank\")\n if (blank) { # No ticks, no length\n element <- paste(axis, \"ticks.length\", tick, sep = \".\")\n theme[[element]] <- unit(0, \"mm\")\n }\n }\n }\n theme\n}\n\n#' @importFrom gtable gtable_add_rows gtable_add_cols\n#' @importFrom ggplot2 find_panel\n#' @importFrom grid unit\nadd_strips <- function(gt, strip_pos) {\n panel_loc <- find_panel(gt)\n strip_pos <- switch(strip_pos, inside = 0L, outside = 2L) # styler: off\n layout <- .subset2(gt, \"layout\")\n if (!any(grepl(\"strip-b\", layout$name))) { # No strips\n gt <- gtable_add_rows(\n gt, unit(0L, \"mm\"),\n panel_loc$b + strip_pos\n )\n } else if (strip_pos == 2L && !any(layout$b == panel_loc$b + 2L)) {\n # Merge the strip-gap height into the axis and remove it. Only performed\n # if an axis exist\n gt$heights[panel_loc$b + 1L] <- sum(gt$heights[panel_loc$b + 1:2])\n gt <- gt[-(panel_loc$b + 2L), ]\n }\n if (!any(grepl(\"strip-t\", layout$name))) {\n gt <- gtable_add_rows(\n gt, unit(0L, \"mm\"),\n panel_loc$t - 1L - strip_pos\n )\n } else if (strip_pos == 2L && !any(layout$t == panel_loc$t - 2L)) {\n gt$heights[panel_loc$t - 1L] <- sum(gt$heights[panel_loc$t - 1:2])\n gt <- gt[-(panel_loc$t - 2L), ]\n }\n if (!any(grepl(\"strip-r\", layout$name))) {\n gt <- gtable_add_cols(\n gt, unit(0L, \"mm\"),\n panel_loc$r + strip_pos\n )\n } else if (strip_pos == 2L && !any(layout$r == panel_loc$r + 2L)) {\n gt$widths[panel_loc$r + 1L] <- sum(gt$widths[panel_loc$r + 1:2])\n gt <- gt[, -(panel_loc$r + 2L)]\n }\n if (!any(grepl(\"strip-l\", layout$name))) {\n gt <- gtable_add_cols(\n gt, unit(0L, \"mm\"),\n panel_loc$l - 1L - strip_pos\n )\n } else if (strip_pos == 2L && !any(layout$l == panel_loc$l - 2L)) {\n gt$widths[panel_loc$l - 1L] <- sum(gt$widths[panel_loc$l - 1:2])\n gt <- gt[, -(panel_loc$l - 2L)]\n }\n gt\n}\n\n# theme(strip.placement)\n#' @importFrom ggplot2 find_panel\nfind_strip_pos <- function(gt) {\n panel_loc <- find_panel(gt)\n layout <- .subset2(gt, \"layout\")\n nms <- .subset2(layout, \"name\")\n ind <- grep(\"strip-t\", nms)\n if (length(ind) != 0L && panel_loc$t - min(layout$t[ind]) != 1L) {\n return(\"outside\")\n }\n ind <- grep(\"strip-l\", nms)\n if (length(ind) != 0L && panel_loc$l - min(layout$l[ind]) != 1L) {\n return(\"outside\")\n }\n ind <- grep(\"strip-r\", nms)\n if (length(ind) != 0L && max(layout$r[ind]) - panel_loc$r != 1L) {\n return(\"outside\")\n }\n ind <- grep(\"strip-b\", nms)\n if (length(ind) != 0L && max(layout$b[ind]) - panel_loc$b != 1L) {\n return(\"outside\")\n }\n \"inside\"\n}\n"], ["/ggalign/R/alignpatch-patchwork.R", "########################################\n#' @importFrom utils modifyList getFromNamespace\n#' @export\nalignpatch.patchwork <- function(x) {\n rlang::check_installed(\"patchwork\", \"to align patchwork\")\n get_patches <- getFromNamespace(\"get_patches\", \"patchwork\")\n # patchwork will keep the class when extracting patches from it.\n # we removed the classes for patchwork, added behind patchwork\n # in this way, the last plot won't have class like `free_align`,\n # `free_border`, `free_lab`, et al. which is added for the patchwork\n sub_patchwork_cls <- which(class(x) == \"patchwork\") - 1L # nolint\n if (sub_patchwork_cls > 0L) {\n class(x) <- class(x)[-seq_len(sub_patchwork_cls)]\n }\n x <- get_patches(x)\n plots <- .subset2(x, \"plots\")\n layout <- .subset2(x, \"layout\")\n annotation <- .subset2(x, \"annotation\")\n default <- getFromNamespace(\"default_layout\", \"patchwork\")\n layout <- modifyList(default, layout[\n !vapply(layout, is.null, logical(1L), USE.NAMES = FALSE)\n ])\n if (identical(.subset2(layout, \"guides\"), \"collect\")) {\n layout$guides <- .TLBR\n } else {\n layout$guides <- NULL\n }\n alignpatch(AlignPatches(\n plots,\n layout = layout,\n titles = .subset(annotation, names(layout_title())),\n theme = .subset2(annotation, \"theme\")\n ))\n}\n\n#' @export\nalignpatch.free_plot <- function(x) {\n if (inherits(x, \"patchwork\")) {\n free_settings <- attr(x, \"patchwork_free_settings\")\n } else {\n free_settings <- attr(x, \"free_settings\")\n }\n free_settings <- split(\n names(free_settings),\n factor(free_settings, rev(unique(free_settings)))\n )\n class(x) <- vec_set_difference(class(x), \"free_plot\")\n for (type in names(free_settings)) {\n side <- paste(.subset2(free_settings, type), collapse = \"\")\n x <- switch(type,\n panel = free_align(x, side),\n label = free_lab(x, side),\n space = free_space(free_border(x, side), side),\n )\n }\n alignpatch(x)\n}\n\n######################################\n# `patch` from `patchwork`: patchwork::plot_spacer\n#' @importFrom ggplot2 ggproto\n#' @export\nalignpatch.patch <- function(x) {\n rlang::check_installed(\n \"patchwork\", sprintf(\"to align %s plot\", obj_type_friendly(x))\n )\n ggproto(NULL, PatchPatchworkPatch, plot = x)\n}\n\n#' @importFrom ggplot2 ggproto\nPatchPatchworkPatch <- ggproto(\n \"PatchPatchworkPatch\", Patch,\n # `patch` from `patchwork`: patchwork::plot_spacer\n #' @importFrom gtable gtable_add_rows gtable_add_cols\n #' @importFrom ggplot2 find_panel\n patch_gtable = function(self, theme, guides, plot = self$plot) {\n guides <- if (length(guides)) \"collect\" else \"keep\"\n ans <- patchwork::patchGrob(patch, guides = guides)\n for (border in .TLBR) {\n panel_pos <- find_panel(ans)\n if (border == \"top\") {\n h <- .subset2(panel_pos, \"t\") - 4L # above original xlab\n ans <- gtable_add_rows(ans, unit(0L, \"mm\"), pos = h)\n } else if (border == \"left\") {\n v <- .subset2(panel_pos, \"l\") - 4L # left of the ylab\n ans <- gtable_add_cols(ans, unit(0, \"mm\"), pos = v)\n } else if (border == \"bottom\") {\n h <- .subset2(panel_pos, \"b\") + 3L # below original xlab\n ans <- gtable_add_rows(ans, unit(0L, \"mm\"), pos = h)\n } else if (border == \"right\") {\n v <- .subset2(panel_pos, \"r\") + 3L # right of the ylab\n ans <- gtable_add_cols(ans, unit(0, \"mm\"), pos = v)\n }\n }\n ans\n }\n)\n\n#' @export\nalignpatch.spacer <- function(x) NULL\n\n#########################################\n# `patch` from `patchwork`: patchwork::wrap_elements\n#' @export\nalignpatch.wrapped_patch <- alignpatch.patch\n"], ["/ggalign/R/layout-heatmap-build.R", "#' @export\nquad_build.HeatmapLayout <- function(quad, schemes = NULL, theme = NULL,\n direction = NULL) {\n ans <- NextMethod()\n\n # add heatmap filling in the first layer --------------\n if (!is.null(filling <- quad@filling)) {\n # we always ensure the filling layer has a fill mapping\n if (is.null(.subset2(ans$plots$main$mapping, \"fill\"))) {\n mapping <- aes(.data$.x, .data$.y, fill = .data$value)\n } else {\n mapping <- aes(.data$.x, .data$.y)\n }\n if (is.waive(filling)) {\n if (nrow(quad@data) * ncol(quad@data) > 20000L) {\n cli_inform(c(\">\" = \"heatmap built with {.fn geom_raster}\"))\n filling <- \"raster\"\n } else {\n cli_inform(c(\">\" = \"heatmap built with {.fn geom_tile}\"))\n filling <- \"tile\"\n }\n }\n ans$plots$main <- ans$plots$main + layer_order(switch(filling,\n raster = ggplot2::geom_raster(mapping = mapping),\n tile = ggplot2::geom_tile(mapping = mapping)\n ))\n }\n # add class to set the default color mapping --------\n ans$plots$main <- add_class(ans$plots$main, \"ggalign_heatmap\")\n ans\n}\n\n#' @importFrom ggplot2 ggplot_build\n#' @export\nggplot_build.ggalign_heatmap <- function(plot, ...) {\n with_options(\n NextMethod(),\n ggplot2.discrete.fill = heatmap_fill(\"discrete\"),\n ggplot2.continuous.fill = heatmap_fill(\"continuous\")\n )\n}\n\nheatmap_fill <- function(type) {\n opt <- sprintf(\"%s.heatmap_%s_fill\", pkg_nm(), type)\n if (is.null(ans <- getOption(opt, default = NULL))) {\n if (type == \"continuous\") {\n ans <- function(...) {\n ggplot2::scale_fill_gradient2(low = \"blue\", high = \"red\")\n }\n } else {\n ans <- getOption(\"ggplot2.discrete.fill\")\n }\n }\n ans\n}\n"], ["/ggalign/R/alignpatch-free-border.R", "#' @param borders Which border shouldn't be aligned? A string containing one or\n#' more of `r oxford_and(.tlbr)`.\n#' @return\n#' - `free_border`: A modified version of `plot` with a `free_border` class.\n#' @export\n#' @rdname free\nfree_border <- function(plot, borders = \"tlbr\") {\n UseMethod(\"free_border\")\n}\n\n#' @export\nfree_border.ggplot <- function(plot, borders = \"tlbr\") {\n assert_position(borders)\n attr(plot, \"free_borders\") <- borders\n add_class(plot, \"free_border\")\n}\n\n#' @export\nfree_border.alignpatches <- free_border.ggplot\n\n#' @export\nfree_border.free_align <- function(plot, borders = \"tlbr\") {\n assert_position(borders)\n borders <- setdiff_position(borders, attr(plot, \"free_axes\"))\n if (!nzchar(borders)) {\n return(plot)\n }\n NextMethod()\n}\n\n#' @export\nfree_border.free_lab <- function(plot, borders = \"tlbr\") {\n assert_position(borders)\n free_labs <- setdiff_position(attr(plot, \"free_labs\"), borders)\n if (nzchar(free_labs)) {\n attr(plot, \"free_labs\") <- free_labs\n } else {\n attr(plot, \"free_labs\") <- NULL\n plot <- remove_class(plot, \"free_lab\")\n }\n NextMethod()\n}\n\n#' @export\nfree_border.free_border <- function(plot, borders = \"tlbr\") {\n assert_position(borders)\n attr(plot, \"free_borders\") <- union_position(\n attr(plot, \"free_borders\"), borders\n )\n plot\n}\n\n#' @export\nfree_border.default <- function(plot, borders = \"tlbr\") {\n cli_abort(\"Cannot use with {.obj_type_friendly {plot}}\")\n}\n\n################################################################\n#' @importFrom ggplot2 ggproto ggproto_parent\n#' @export\nalignpatch.free_border <- function(x) {\n Parent <- NextMethod()\n ggproto(\n \"PatchFreeBorder\", Parent,\n free_borders = setup_pos(attr(x, \"free_borders\")),\n collect_guides = function(self, guides, gt = self$gt) {\n ans <- ggproto_parent(Parent, self)$collect_guides(\n guides = guides, gt = gt\n )\n self$gt <- ggproto_parent(Parent, self)$free_border(\n borders = self$free_borders, gt = self$gt\n )\n ans\n },\n align_border = function(self, t = NULL, l = NULL, b = NULL, r = NULL,\n gt = self$gt) {\n gt <- ggproto_parent(Parent, self)$align_border(\n t = t, l = l, b = b, r = r, gt = gt\n )\n ggproto_parent(Parent, self)$align_free_border(\n borders = self$free_borders,\n t = t, l = l, b = b, r = r, gt = gt\n )\n },\n free_border = function(self, borders, gt = self$gt) {\n borders <- vec_set_difference(borders, self$free_borders)\n if (length(borders)) {\n gt <- ggproto_parent(Parent, self)$free_border(\n borders = borders, gt = gt\n )\n }\n gt\n },\n align_free_border = function(self, borders,\n t = NULL, l = NULL, b = NULL, r = NULL,\n gt = self$gt) {\n borders <- vec_set_difference(borders, self$free_borders)\n if (length(borders)) {\n gt <- ggproto_parent(Parent, self)$align_free_border(\n borders = borders,\n t = t, l = l, b = b, r = r, gt = gt\n )\n }\n gt\n }\n )\n}\n"], ["/ggalign/R/import-standalone-purrr.R", "# Standalone file: do not edit by hand\n# Source: \n# ----------------------------------------------------------------------\n#\n# ---\n# repo: Yunuuuu/standalone\n# file: standalone-purrr.R\n# last-updated: 2024-11-13\n# license: https://unlicense.org\n# ---\n\n# This file provides a minimal shim to provide a purrr-like API on top of\n# base R functions. They are not drop-in replacements but allow a similar style\n# of programming.\n#\n# Note: these functions won't support lambda syntax.\n\n# ## Changelog\n# 2024-11-13:\n# rename `transpose()` to `list_transpose()`\n#\n# 2024-11-12:\n# First release\n#\n# nocov start\n\nmap <- function(.x, .f, ...) lapply(.x, .f, ...)\n\nwalk <- function(.x, .f, ...) {\n lapply(.x, .f, ...)\n invisible(.x)\n}\n\nmap_lgl <- function(.x, .f, ...) {\n vapply(X = .x, FUN = .f, logical(1L), ...)\n}\n\nmap_int <- function(.x, .f, ...) {\n vapply(X = .x, FUN = .f, integer(1L), ...)\n}\n\nmap_dbl <- function(.x, .f, ...) {\n vapply(X = .x, FUN = .f, double(1L), ...)\n}\n\nmap_chr <- function(.x, .f, ...) {\n vapply(X = .x, FUN = .f, character(1L), ...)\n}\n\npmap <- function(.l, .f, ...) {\n out <- .mapply(.f, .l, list(...))\n if (!is.null(nms <- names(.subset2(.l, 1L)))) names(out) <- nms\n out\n}\n\npmap_lgl <- function(.l, .f, ...) {\n .purrr_pmap_mold(.l, .f, ..., mold = logical(1L))\n}\n\npmap_int <- function(.l, .f, ...) {\n .purrr_pmap_mold(.l, .f, ..., mold = integer(1L))\n}\n\npmap_dbl <- function(.l, .f, ...) {\n .purrr_pmap_mold(.l, .f, ..., mold = double(1L))\n}\n\npmap_chr <- function(.l, .f, ...) {\n .purrr_pmap_mold(.l, .f, ..., mold = character(1L))\n}\n\n.purrr_pmap_mold <- function(.l, .f, ..., mold) {\n nms <- names(.subset2(.l, 1L))\n dots <- list(...)\n out <- vapply(seq_along(nms), function(i) {\n do.call(.f, args = c(lapply(.l, .subset2, i), dots))\n }, mold, USE.NAMES = FALSE)\n if (!is.null(nms)) names(out) <- nms\n out\n}\n\nmap2 <- function(.x, .y, .f, ...) pmap(list(.x, .y), .f, ...)\n\nmap2_lgl <- function(.x, .y, .f, ...) {\n .purrr_pmap_mold(list(.x, .y), .f, ..., mold = logical(1L))\n}\n\nmap2_int <- function(.x, .y, .f, ...) {\n .purrr_pmap_mold(list(.x, .y), .f, ..., mold = integer(1L))\n}\n\nmap2_dbl <- function(.x, .y, .f, ...) {\n .purrr_pmap_mold(list(.x, .y), .f, ..., mold = double(1L))\n}\n\nmap2_chr <- function(.x, .y, .f, ...) {\n .purrr_pmap_mold(list(.x, .y), .f, ..., mold = character(1L))\n}\n\nimap <- function(.x, .f, ...) {\n nms <- names(.x)\n if (is.null(nms)) {\n .l <- list(.x, seq_along(.x))\n } else {\n .l <- list(.x, nms)\n }\n pmap(.l, .f, ...)\n}\n\n.purrr_imap_mold <- function(.x, .f, ..., mold) {\n if (is.null(nms <- names(.x))) {\n .l <- list(.x, seq_along(.x))\n } else {\n .l <- list(.x, nms)\n }\n .purrr_pmap_mold(.l, .f, ..., mold = mold)\n}\n\nimap_lgl <- function(.l, .f, ...) {\n .purrr_imap_mold(.l, .f, ..., mold = logical(1L))\n}\n\nimap_int <- function(.l, .f, ...) {\n .purrr_imap_mold(.l, .f, ..., mold = integer(1L))\n}\n\nimap_dbl <- function(.l, .f, ...) {\n .purrr_imap_mold(.l, .f, ..., mold = double(1L))\n}\n\nimap_chr <- function(.l, .f, ...) {\n .purrr_imap_mold(.l, .f, ..., mold = character(1L))\n}\n\nlist_transpose <- function(.l) {\n if (!length(.l)) return(.l) # styler: off\n inner_names <- names(.subset2(.l, 1L))\n if (is.null(inner_names)) {\n fields <- seq_along(.subset2(.l, 1L))\n } else {\n fields <- inner_names\n names(fields) <- fields\n .l <- lapply(.l, function(x) {\n if (is.null(names(x))) names(x) <- inner_names # styler: off\n x\n })\n }\n\n # This way missing fields are subsetted as `NULL` instead of causing\n # an error\n .l <- lapply(.l, as.list)\n\n lapply(fields, function(i) lapply(.l, .subset2, i))\n}\n\n# nocov end\n"], ["/ggalign/R/alignpatch-free-lab.R", "#' @param labs Which axis labs to be free? A string containing one or more of\n#' `r oxford_and(.tlbr)`.\n#' @return\n#' - `free_lab`: A modified version of `plot` with a `free_lab` class.\n#' @export\n#' @rdname free\nfree_lab <- function(plot, labs = \"tlbr\") {\n UseMethod(\"free_lab\")\n}\n\n#' @export\nfree_lab.ggplot <- function(plot, labs = \"tlbr\") {\n assert_position(labs)\n attr(plot, \"free_labs\") <- labs\n add_class(plot, \"free_lab\")\n}\n\n#' @export\nfree_lab.alignpatches <- free_lab.ggplot\n\n#' @export\nfree_lab.free_align <- function(plot, labs = \"tlbr\") {\n assert_position(labs)\n labs <- setdiff_position(labs, attr(plot, \"free_axes\"))\n if (!nzchar(labs)) return(plot) # styler: off\n NextMethod()\n}\n\n#' @export\nfree_lab.free_borders <- function(plot, labs = \"tlbr\") {\n assert_position(labs)\n labs <- setdiff_position(labs, attr(plot, \"free_borders\"))\n if (!nzchar(labs)) return(plot) # styler: off\n NextMethod()\n}\n\n#' @export\nfree_lab.free_lab <- function(plot, labs = \"tlbr\") {\n assert_position(labs)\n attr(plot, \"free_labs\") <- union_position(attr(plot, \"free_labs\"), labs)\n plot\n}\n\n#' @export\nfree_lab.default <- function(plot, labs = \"tlbr\") {\n cli_abort(\"Cannot use with {.obj_type_friendly {plot}}\")\n}\n\n####################################################\n#' @importFrom ggplot2 ggproto ggproto_parent\n#' @export\nalignpatch.free_lab <- function(x) {\n Parent <- NextMethod()\n ggproto(\n \"PatchFreeLab\", Parent,\n free_labs = setup_pos(attr(x, \"free_labs\")),\n collect_guides = function(self, guides, gt = self$gt) {\n ans <- ggproto_parent(Parent, self)$collect_guides(\n guides = guides, gt = gt\n )\n self$gt <- ggproto_parent(Parent, self)$free_lab(\n labs = self$free_labs, gt = self$gt\n )\n ans\n },\n free_lab = function(self, labs, gt = self$gt) {\n if (length(labs <- vec_set_difference(labs, self$free_labs))) {\n gt <- ggproto_parent(Parent, self)$free_lab(\n labs = labs, gt = gt\n )\n }\n gt\n }\n )\n}\n"], ["/ggalign/R/alignpatch-free-space.R", "#' @param spaces Which border spaces should be removed? A string containing one\n#' or more of `r oxford_and(.tlbr)`.\n#' @return\n#' - `free_space`: A modified version of `plot` with a `free_space` class.\n#' @export\n#' @rdname free\nfree_space <- function(plot, spaces = \"tlbr\") {\n UseMethod(\"free_space\")\n}\n\n#' @export\nfree_space.default <- function(plot, spaces = \"tlbr\") {\n cli_abort(\"Cannot use with {.obj_type_friendly {plot}}\")\n}\n\n#' @export\nfree_space.ggplot <- function(plot, spaces = \"tlbr\") {\n assert_position(spaces)\n attr(plot, \"free_spaces\") <- spaces\n add_class(plot, \"free_space\")\n}\n\n#' @export\nfree_space.alignpatches <- free_space.ggplot\n\n#' @export\nfree_space.free_align <- function(plot, spaces = \"tlbr\") {\n assert_position(spaces)\n spaces <- setdiff_position(spaces, attr(plot, \"free_axes\"))\n if (!nzchar(spaces)) {\n return(plot)\n }\n NextMethod()\n}\n\n#' @export\nfree_space.free_space <- function(plot, spaces = \"tlbr\") {\n assert_position(spaces)\n attr(plot, \"free_spaces\") <- union_position(\n attr(plot, \"free_spaces\"), spaces\n )\n plot\n}\n\n##########################################################\n#' @importFrom ggplot2 ggproto ggproto_parent\n#' @importFrom grid unit\n#' @export\nalignpatch.free_space <- function(x) {\n Parent <- NextMethod()\n ggproto(\n \"PatchFreeSpace\", Parent,\n free_spaces = split_position(attr(x, \"free_spaces\")),\n get_sizes = function(self, free = NULL, gt = self$gt) {\n ggproto_parent(Parent, self)$get_sizes(\n union(free, self$free_spaces),\n gt = gt\n )\n }\n )\n}\n"], ["/ggalign/R/alignpatch-free-guide.R", "#' @param guides A string containing one or more of\n#' `r oxford_and(c(.tlbr, \"i\"))` indicates which side of guide legends should be\n#' collected for the plot. If `NULL`, no guide legends will be collected.\n#' @return\n#' - `free_guide`: A modified version of `plot` with a `free_guide` class.\n#' @export\n#' @rdname free\nfree_guide <- function(plot, guides = \"tlbr\") {\n UseMethod(\"free_guide\")\n}\n\n#' @export\nfree_guide.ggplot <- function(plot, guides = \"tlbr\") {\n if (!is.null(guides)) assert_guides(guides)\n attr(plot, \"free_guides\") <- guides\n add_class(plot, \"free_guide\")\n}\n\n#' @export\nfree_guide.alignpatches <- free_guide.ggplot\n\n#' @export\nfree_guide.free_guide <- function(plot, guides = \"tlbr\") {\n if (is.null(guides)) {\n attr(plot, \"free_guides\") <- NULL\n } else {\n assert_guides(guides)\n if (is.null(old <- attr(plot, \"free_guides\", exact = TRUE))) {\n attr(plot, \"free_guides\") <- guides\n } else {\n attr(plot, \"free_guides\") <- union_position(old, guides)\n }\n }\n plot\n}\n\n################################################################\n#' @importFrom ggplot2 ggproto ggproto_parent\n#' @export\nalignpatch.free_guide <- function(x) {\n Parent <- NextMethod()\n if (!is.null(free_guides <- attr(x, \"free_guides\", exact = TRUE))) {\n free_guides <- setup_guides(free_guides)\n }\n ggproto(\"PatchFreeGuide\", Parent,\n set_guides = function(self, guides) free_guides\n )\n}\n"], ["/ggalign/R/utils-rd.R", "rd_layout <- function() {\n sprintf(\"%s or [`stack_layout()`] object\", rd_quad())\n}\n\nrd_quad <- function() \"[`quad_layout()`]/[`ggheatmap()`]\"\n\nrd_chain_what <- function() {\n paste(\n \"A single number or string of the plot elements in the layout.\",\n \"If `NULL`, will remove any active context\"\n )\n}\n\nrd_quad_position <- function(action) {\n sprintf(\n \"A string of %s indicates which annotation stack should be %s\",\n oxford_or(.TLBR),\n action\n )\n}\n\nrd_layout_data <- function() {\n paste(\n \"Default dataset to use for the layout. If not specified, it must be\",\n \"supplied in each plot added to the layout\"\n )\n}\n\nrd_gg_aesthetics <- function(...) {\n ans <- ggfun(\"rd_aesthetics\")(...)\n ans <- sub(\"link[=\", \"link[ggplot2:\", ans, fixed = TRUE)\n sub(\"(vignette\\\\([^)]+)\\\\)\", \"\\\\1, package = \\\"ggplot2\\\")\", ans)\n}\n"], ["/ggalign/R/layout-quad-operator.R", "# `subtract` operates at layout-level\n#' @keywords internal\nquad_layout_subtract <- function(object, quad, object_name) {\n UseMethod(\"quad_layout_subtract\")\n}\n\n#' @export\nquad_layout_subtract.default <- function(object, quad, object_name) {\n if (is.null(context <- quad@active)) context <- c(.TLBR, list(NULL))\n for (active in context) {\n if (is.null(active)) {\n quad <- quad_body_add(object, quad, object_name)\n } else if (!is.null(slot(quad, active))) {\n slot(quad, active) <- chain_layout_subtract(\n object, slot(quad, active), object_name\n )\n }\n }\n quad\n}\n\n# for object can set at layout level\n#' @export\nquad_layout_subtract.ggalign_scheme <- function(object, quad, object_name) {\n if (is.null(context <- quad@active)) {\n quad <- update_layout_scheme(object, quad, object_name)\n } else {\n slot(quad, context) <- update_layout_scheme(\n object, slot(quad, context), object_name\n )\n }\n quad\n}\n\n#' @export\nquad_layout_subtract.ggalign_with_quad <- function(object, quad, object_name) {\n old <- quad@active\n context <- quad_operated_context(object, old, \"-\")\n object <- .subset2(object, \"object\")\n object_name <- .subset2(object, \"object_name\")\n # `subtract` operates at layout-level\n if (is.null(context)) {\n quad@active <- context\n quad <- quad_layout_subtract(object, quad, object_name)\n } else {\n for (active in context) {\n if (is.null(active)) {\n quad <- quad_body_add(object, quad, object_name)\n } else if (!is.null(slot(quad, active))) {\n slot(quad, active) <- chain_layout_subtract(\n object, slot(quad, active), object_name\n )\n }\n }\n }\n quad@active <- old\n quad\n}\n\n###############################################################\n#' @keywords internal\nquad_layout_and_add <- function(object, quad, object_name) {\n UseMethod(\"quad_layout_and_add\")\n}\n\n#' @export\nquad_layout_and_add.default <- function(object, quad, object_name) {\n quad <- quad_body_add(object, quad, object_name)\n for (position in .TLBR) {\n stack <- slot(quad, position)\n if (is.null(stack)) next\n slot(quad, position) <- chain_layout_and_add(\n object, stack, object_name\n )\n }\n quad\n}\n\n#' @export\nquad_layout_and_add.ggalign_with_quad <- function(object, quad, object_name) {\n object <- .subset2(object, \"object\")\n object_name <- .subset2(object, \"object_name\")\n NextMethod()\n}\n\n#' @export\nquad_layout_and_add.theme <- function(object, quad, object_name) {\n ans <- NextMethod()\n # to align with `patchwork`, we also modify the layout theme\n # when using `&` to add the theme object.\n ans@theme <- ggfun(\"add_theme\")(ans@theme, object)\n ans\n}\n"], ["/ggalign/R/object-name.R", "format_object_name <- function(name, format = NULL) {\n if (is.null(format)) {\n name\n } else {\n sprintf(\"{.%s %s}\", format, name)\n }\n}\n\nobject_name <- function(object, format) UseMethod(\"object_name\")\n\n#' @export\nobject_name.StackLayout <- function(object, format = \"fn\") {\n ans <- format_object_name(object@name, format)\n if (!is.null(position <- .subset2(object@heatmap, \"position\"))) {\n ans <- sprintf(\"the %s annotation %s\", position, ans)\n } else {\n ans <- sprintf(\"the %s %s\", object@direction, ans)\n }\n ans\n}\n\n#' @export\nobject_name.CircleLayout <- function(object, format = \"fn\") {\n format_object_name(object@name, format)\n}\n\n#' @export\nobject_name.QuadLayout <- function(object, format = \"fn\") {\n format_object_name(object@name, format)\n}\n\n#' @export\nobject_name.CraftBox <- function(object, format = \"fn\") {\n object_name(object@craftsman, format)\n}\n\n#' @export\nobject_name.Craftsman <- function(object, format = \"fn\") {\n format_object_name(snake_class(object), format)\n}\n\n#' @export\nobject_name.AlignGg <- function(object, format = \"fn\") {\n format_object_name(\"ggalign\", format)\n}\n\n#' @export\nobject_name.CrossGg <- function(object, format = \"fn\") {\n format_object_name(\"ggcross\", format)\n}\n\n#' @export\nobject_name.FreeGg <- function(object, format = \"fn\") {\n format_object_name(\"ggfree\", format)\n}\n\n#' @export\nobject_name.MarkGg <- function(object, format = \"fn\") {\n format_object_name(\"ggmark\", format)\n}\n"], ["/ggalign/R/ggalign-package.R", "#' @keywords internal\n\"_PACKAGE\"\n\n## usethis namespace: start\n#' @import vctrs\n#' @importFrom lifecycle deprecated\n#' @importFrom rlang .data .env\n#' @importFrom cli cli_abort cli_warn cli_inform\n## usethis namespace: end\nNULL\n\n# enable usage of @name in package code\n#' @rawNamespace if (getRversion() < \"4.3.0\") importFrom(\"S7\", \"@\")\nNULL\n"], ["/ggalign/R/zzz.R", "#' @importFrom S7 methods_register\n.onLoad <- function(libname, pkgname) {\n # register ggplot2 theme elements\n theme_elements()\n\n # register method for\n s3_register(\"ggrastr::rasterise\", \"CraftBox\")\n s3_register(\"ggrastr::rasterise\", \"QuadLayout\")\n s3_register(\"ggrastr::rasterise\", \"ChainLayout\")\n\n methods_register()\n invisible()\n}\n"], ["/ggalign/R/rasterise.R", "rasterise.QuadLayout <- function(input, ...) {\n input@plot <- ggrastr::rasterise(input = input@plot, ...)\n for (position in .TLBR) {\n stack <- slot(input, position)\n if (is.null(stack)) next\n slot(input, position) <- ggrastr::rasterise(input = stack, ...)\n }\n input\n}\n\nrasterise.ChainLayout <- function(input, ...) {\n input@plot_list <- lapply(input@plot_list, ggrastr::rasterise, ...)\n input\n}\n\nrasterise.CraftBox <- function(input, ...) {\n if (!is.null(plot <- input@plot)) {\n input@plot <- ggrastr::rasterise(input = plot, ...)\n }\n input\n}\n\n##########################################################\n#' @export\nraster_magick0.QuadLayout <- function(x, ...) {\n x@plot <- raster_magick0(x = x@plot, ...)\n for (position in .TLBR) {\n stack <- slot(x, position)\n if (is.null(stack)) next\n slot(x, position) <- raster_magick0(x = stack, ...)\n }\n x\n}\n\n#' @export\nraster_magick0.ChainLayout <- function(x, ...) {\n x@plot_list <- lapply(x@plot_list, raster_magick0, ...)\n x\n}\n\n\n#' @export\nraster_magick0.CraftBox <- function(x, ...) {\n if (!is.null(plot <- input@plot)) {\n input@plot <- raster_magick0(x = plot, ...)\n }\n input\n}\n"]], "task_instance_info": {"created_time": "2025-08-21 01:13:42", "created_task_model": "DeepSeek-R1", "function_skeleton": "function(cnd) {}", "code_description": "This code segment functions to: Handle conversion errors during matrix creation by generating user-friendly messages specifying acceptable input types and terminating execution with context-aware error reporting."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```r\n[TASK_BEGIN]\nfunction(cnd) {\n cli::abort(\n message = glue::glue(\"Can't convert {data_arg} to a matrix.\"),\n class = \"ggtrace_fortify_matrix_error\",\n call = call\n )\n}\n[TASK_END]\n```", "inference_time": "2025-08-21 01-13-55"}, "editdistance_info": {"edit_distance": 20.2703, "calculate_time": "2025-08-21 01:13:55", "true_code_clean": "function(cnd) {\n cli_abort(\n paste0(\n \"{.arg {data_arg}} must be a {.cls matrix}, \",\n \"or an object coercible by {.fn fortify_matrix}, or a valid \",\n \"{.cls matrix}-like object coercible by {.fn as.matrix}\"\n ),\n call = call\n )\n }", "predict_code_clean": "function(cnd) {\n cli::abort(\n message = glue::glue(\"Can't convert {data_arg} to a matrix.\"),\n class = \"ggtrace_fortify_matrix_error\",\n call = call\n )\n}"}} {"repo_name": "ggalign", "file_name": "/ggalign/R/ggcross.R", "inference_info": {"prefix_code": "#' Connect two layout crosswise\n#'\n#' @description\n#' `ggcross` resets the layout ordering index of a [`stack_cross()`]. This\n#' allows you to add other `align_*` objects to define a new layout ordering\n#' index. Any objects added after `ggcross` will use this updated layout\n#' ordering index. This feature is particularly useful for creating `tanglegram`\n#' visualizations. `ggcross()` is an alias of `ggcross()`.\n#'\n#' @inheritParams ggalign\n#' @section ggplot2 specification:\n#' `ggcross()` initializes a ggplot `data` and `mapping`.\n#'\n#' `ggcross()` always applies a default mapping for the axis of the data index\n#' in the layout. This mapping is `aes(y = .data$.y)` for horizontal stack\n#' layout (including left and right annotation) and `aes(x = .data$.x)` for\n#' vertical stack layout (including top and bottom annotation).\n#'\n#' The data in the underlying `ggplot` object will contain following columns:\n#'\n#' - `.panel`: The panel for the aligned axis. Refers to the `x-axis` for\n#' vertical `stack_layout()` (including top and bottom annotations), and the\n#' `y-axis` for horizontal `stack_layout()` (including left and right\n#' annotations).\n#'\n#' - `.names` ([`vec_names()`][vctrs::vec_names]) and `.index`\n#' ([`vec_size()`][vctrs::vec_size()]/[`NROW()`]): Character names (if\n#' available) and the integer index of the original data.\n#'\n#' - `.hand`: a factor indicates the index groups.\n#'\n#' - `.x`/`.y` and `.discrete_x`/`.discrete_y`: Integer indices for `x`/`y`\n#' coordinates, and a factor of the data labels (only applicable when names\n#' exist).\n#'\n#' It is recommended to use `.x`/`.y`, or `.discrete_x`/`.discrete_y` as the\n#' `x`/`y` mapping.\n#'\n#' @importFrom ggplot2 ggplot aes\n#' @export\nggcross <- function(mapping = aes(), size = NULL,\n no_axes = NULL, active = NULL) {\n active <- update_active(active, new_active(use = TRUE))\n no_axes <- no_axes %||%\n getOption(sprintf(\"%s.align_no_axes\", pkg_nm()), default = TRUE)\n cross(\n CrossGg,\n plot = ggplot(mapping = mapping),\n schemes = default_schemes(th = theme_no_strip()),\n size = size, no_axes = no_axes, active = active\n )\n}\n\n#' @importFrom ggplot2 ggproto\nCrossGg <- ggproto(\"CrossGg\", \n CraftCross,\n interact_layout = function(self, layout) {\n if (!is_cross_layout(layout)) {\n cli_abort(c(\n sprintf(\n \"Cannot add %s to %s\",\n object_name(self), self$layout_name\n ),\n i = sprintf(\n \"%s can only be used in {.fn stack_cross}\",\n object_name(self)\n )\n ))\n }\n\n # udpate cross_points\n layout@cross_points <- c(layout@cross_points, length(layout@plot_list))\n\n # update old design list\n layout@odesign <- c(layout@odesign, list(layout@design))\n\n # we keep the names from the layout data for usage\n self$labels <- vec_names(layout@data)\n layout\n },\n setup_design = function(self, design) {\n design[\"index\"] <- list(NULL) # always reset the index\n design\n },\n setup_plot = function(self, plot) {\n ggadd_default(plot, mapping = switch_direction(\n self$direction, aes(y = .data$.y), aes(x = .data$.x)\n ))\n },\n #' @importFrom stats reorder\n build_plot = function(self, plot, design, extra_design = NULL,\n previous_design = NULL) {\n if (is.null(.subset2(design, \"nobs\"))) {\n cli_abort(sprintf(\n \"you must initialize %s before drawing %s\",\n self$layout_name, object_name(self)\n ), call = self$call)\n }\n direction <- self$direction\n index <- vec_c(\n .subset2(previous_design, \"index\"),\n .subset2(design, \"index\")\n )\n data <- data_frame0(\n .panel = vec_c(\n .subset2(previous_design, \"panel\"),\n .subset2(design, \"panel\")\n ),\n .index = index,\n # ggcross() only reset ordering index, labels should be the same\n .names = .subset(self$labels, index),\n .hand = if (is_horizontal(direction)) {\n factor(\n vec_rep_each(\n c(\"left\", \"right\"),\n c(\n .subset2(previous_design, \"nobs\"),\n .subset2(design, \"nobs\")\n )\n ),\n c(\"left\", \"right\")\n )\n } else {\n factor(\n vec_rep_each(\n c(\"top\", \"bottom\"),\n c(\n .subset2(previous_design, \"nobs\"),\n .subset2(design, \"nobs\")\n )\n ),\n c(\"bottom\", \"top\")\n )\n }\n )\n axis <- to_coord_axis(direction)\n coord_name <- paste0(\".\", axis)\n data[[coord_name]] <- vec_c(\n seq_len(.subset2(previous_design, \"nobs\")),\n seq_len(.subset2(design, \"nobs\"))\n )\n if (!is.null(.subset2(data, \".names\"))) {\n data[[paste0(\".discrete_\", axis)]] <- reorder(\n .subset2(data, \".names\"),\n .subset2(data, coord_name),\n order = FALSE\n )\n }\n plot <- gguse_data(plot, data)\n plot + switch_direction(\n direction,\n default_expansion(x = expansion()),\n default_expansion(y = expansion())\n )\n },\n finish_plot = ", "suffix_code": ",\n summary = function(self, plot) {\n header <- ggproto_parent(Craftsman, self)$summary(plot)\n c(header, \" Reset the ordering index and Add plot\")\n }\n)\n", "middle_code": "function(self, plot, schemes, theme) {\n direction <- self$direction\n if (isTRUE(self$no_axes)) {\n schemes$scheme_theme <- .subset2(schemes, \"scheme_theme\") +\n theme_no_axes(switch_direction(direction, \"y\", \"x\"))\n }\n plot <- plot_add_schemes(plot, schemes)\n if (is_horizontal(direction)) {\n theme <- theme(\n panel.spacing.y = calc_element(\"panel.spacing.y\", theme)\n )\n } else {\n theme <- theme(\n panel.spacing.x = calc_element(\"panel.spacing.x\", theme)\n )\n }\n plot <- plot + theme\n ggremove_margin(plot, direction) + theme_recycle()\n }", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "r", "sub_task_type": null}, "context_code": [["/ggalign/R/ggalign.R", "#' Add ggplot by Aligning discrete or continuous variable\n#'\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' `ggalign()` is similar to `ggplot` in that it initializes a `ggplot` data and\n#' `mapping`. `ggalign()` allowing you to provide data in various formats,\n#' including matrices, data frames, or simple vectors. By default, it will\n#' inherit from the layout. If a function, it will apply with the layout matrix.\n#' `ggalign()` focuses on integrating plots into a layout by aligning the axes.\n#'\n#' @param data The following options can be used:\n#' - `NULL`: No data is set.\n#' - [`waiver()`][ggplot2::waiver]: Inherits the data from the layout matrix.\n#' - A `function` (including purrr-like lambda syntax): Applied to the layout\n#' matrix to transform the data before use. To transform the final plot\n#' data, please use [`scheme_data()`].\n#' - A `matrix`, `data.frame`, or atomic vector.\n#' @inheritParams ggplot2::ggplot\n#' @param ... <[dyn-dots][rlang::dyn-dots]> Additional arguments passed to\n#' [`fortify_data_frame()`].\n#' @param size The relative size of the plot, can be specified as a\n#' [`unit()`][grid::unit]. Note that for [`circle_layout()`], all size values\n#' will be interpreted as relative sizes, as this layout type adjusts based on\n#' the available space in the circular arrangement.\n#' @param no_axes `r lifecycle::badge('experimental')` Logical; if `TRUE`,\n#' removes axes elements for the alignment axis using [`theme_no_axes()`]. By\n#' default, will use the option-\n#' `r code_quote(sprintf(\"%s.align_no_axes\", pkg_nm()))`.\n#' @param active A [`active()`] object that defines the context settings when\n#' added to a layout.\n#' @section ggplot2 specification:\n#' `ggalign` initializes a ggplot object. The underlying data is created using\n#' [`fortify_data_frame()`]. Please refer to it for more details.\n#'\n#' When aligning discrete variables, `ggalign()` always applies a default\n#' mapping for the axis of the data index in the layout. Specifically:\n#'\n#' - `aes(y = .data$.y)` is used for the horizontal `stack_layout()` (including\n#' left and right annotations).\n#' - `aes(x = .data$.x)` is used for the vertical `stack_layout()` (including\n#' top and bottom annotations) and `circle_layout()`.\n#'\n#' The following columns will be added to the data frame to align discrete\n#' variables:\n#'\n#' - `.panel`: The panel for the aligned axis. Refers to the `x-axis` for\n#' vertical `stack_layout()` (including top and bottom annotations), and the\n#' `y-axis` for horizontal `stack_layout()` (including left and right\n#' annotations).\n#'\n#' - `.names` ([`vec_names()`][vctrs::vec_names]) and `.index`\n#' ([`vec_size()`][vctrs::vec_size()]/[`NROW()`]): Character names (if\n#' available) and the integer index of the original data.\n#'\n#' - `.x`/`.y` and `.discrete_x`/`.discrete_y`: Integer indices for `x`/`y`\n#' coordinates, and a factor of the data labels (only applicable when names\n#' exist).\n#'\n#' It is recommended to use `.x`/`.y`, or `.discrete_x`/`.discrete_y` as the\n#' `x`/`y` mapping.\n#'\n#' If the data inherits from [`quad_layout()`]/[`ggheatmap()`], additional\n#' columns will be added:\n#'\n#' - `.extra_panel`: Provides the panel information for the column (left or\n#' right annotation) or row (top or bottom annotation).\n#' - `.extra_index`: The index information for the column (left or right\n#' annotation) or row (top or bottom annotation).\n#'\n#' @inheritSection align Discrete Axis Alignment\n#' @examples\n#' ggheatmap(matrix(rnorm(81), nrow = 9)) +\n#' anno_top() +\n#' ggalign() +\n#' geom_point(aes(y = value))\n#'\n#' ggheatmap(matrix(rnorm(81), nrow = 9)) +\n#' anno_top(size = 0.5) +\n#' align_dendro(k = 3L) +\n#' ggalign(data = NULL, size = 0.2) +\n#' geom_tile(aes(y = 1L, fill = .panel))\n#'\n#' @importFrom ggplot2 ggplot aes\n#' @importFrom rlang list2\n#' @export\nggalign <- function(data = waiver(), mapping = aes(), ..., size = NULL,\n no_axes = NULL, active = NULL) {\n if (inherits(data, \"uneval\")) {\n cli_abort(c(\n \"{.arg data} cannot be {.obj_type_friendly {data}}\",\n \"i\" = \"Have you misspelled the {.arg data} argument in {.fn ggalign}\"\n ))\n }\n no_axes <- no_axes %||%\n getOption(sprintf(\"%s.align_no_axes\", pkg_nm()), default = TRUE)\n assert_active(active)\n active <- update_active(active, new_active(use = TRUE))\n new_craftbox(\n AlignGg,\n input_data = allow_lambda(data),\n data_params = list2(...),\n plot = ggplot(mapping = mapping),\n size = size,\n schemes = default_schemes(data, th = theme_no_strip()),\n no_axes = no_axes, active = active\n )\n}\n\n#' @importFrom rlang inject\n#' @importFrom ggplot2 ggproto ggplot\nAlignGg <- ggproto(\"AlignGg\", Craftsman,\n interact_layout = function(self, layout) {\n layout_name <- self$layout_name\n input_data <- self$input_data\n object_name <- object_name(self)\n layout_data <- layout@data\n\n # inherit data from the layout\n if (is.function(input_data)) {\n if (is.null(layout_data)) {\n cli_abort(c(\n sprintf(\n \"{.arg data} in %s cannot be a function\",\n object_name\n ),\n i = sprintf(\"no data was found in %s\", layout_name)\n ))\n }\n data <- input_data(layout_data)\n } else if (is.waive(input_data)) {\n data <- layout_data %|w|% NULL\n # for data inherit from the layout, and the layout data is from\n # the quad-layout, we'll integrate the `extra_design`\n self$use_extra_design <- is_stack_layout(layout) &&\n isTRUE(layout@heatmap$quad_matrix)\n } else {\n data <- input_data\n }\n plot_data <- inject(\n fortify_data_frame(data, !!!self$data_params, call = self$call)\n )\n\n # for discrete design, # we need ensure the nobs is the same\n if (is_discrete_design(design <- layout@design)) {\n if (!is.null(data)) {\n if (is.null(layout_nobs <- design$nobs)) {\n layout_nobs <- NROW(data)\n if (layout_nobs == 0L) {\n cli_abort(\"{.arg data} cannot be empty\",\n call = self$call\n )\n }\n } else if (NROW(data) != layout_nobs) {\n cli_abort(sprintf(\n \"%s (nobs: %d) is not compatible with the %s (nobs: %d)\",\n object_name, NROW(data), layout_name, layout_nobs\n ))\n }\n design[\"nobs\"] <- list(layout_nobs)\n\n # we always add `.index` to align the observations\n # For matrix-like object\n if (!is.data.frame(data) &&\n vec_is(dim(data), integer(), size = 2L)) {\n plot_data$.index <- vec_rep(seq_len(NROW(data)), NCOL(data))\n } else {\n plot_data$.index <- seq_len(NROW(data))\n }\n layout@design <- design\n self$labels <- vec_names(data) %||% vec_names(layout_data)\n # always remove names, we'll add it in `build_plot()`\n plot_data$.names <- NULL\n } else {\n self$labels <- vec_names(layout_data)\n }\n self$add_mapping <- TRUE\n }\n self$data <- ggalign_data_restore(plot_data, layout_data)\n layout\n },\n setup_plot = function(self, plot) {\n direction <- self$direction\n ggadd_default(\n plot,\n mapping = if (isTRUE(self$add_mapping)) {\n switch_direction(\n direction,\n aes(y = .data$.y),\n aes(x = .data$.x)\n )\n },\n theme = if (is.null(self$data)) {\n # remove the title and text of axis vertically with the layout\n theme_no_axes(switch_direction(direction, \"x\", \"y\"))\n }\n ) + switch_direction(\n direction,\n ggplot2::labs(y = NULL),\n ggplot2::labs(x = NULL)\n )\n },\n\n #' @importFrom stats reorder\n build_plot = function(self, plot, design, extra_design = NULL,\n previous_design = NULL) {\n data <- self$data\n\n # if inherit from the parent layout\n if (isTRUE(self$use_extra_design) &&\n is_discrete_design(extra_design) &&\n !is.null(.subset2(extra_design, \"nobs\"))) {\n # if the data is inherit from the `quad_layout()`\n # the data must be a matrix\n extra_plot_data <- data_frame0(\n .extra_panel = .subset2(extra_design, \"panel\"),\n .extra_index = .subset2(extra_design, \"index\")\n )\n } else {\n extra_plot_data <- NULL\n }\n\n if (is_continuous_design(design)) {\n if (!is.null(data) && !is.null(extra_plot_data)) {\n data <- full_join(data, extra_plot_data,\n by.x = \".column_index\", by.y = \".extra_index\"\n )\n }\n return(gguse_data(plot, data))\n } else if (is.null(.subset2(design, \"nobs\"))) {\n cli_abort(c(\n sprintf(\n \"you must initialize %s before drawing %s\",\n self$layout_name, object_name(self)\n ),\n i = \"Or you should use {.fn ggfree}\"\n ), call = self$call)\n }\n direction <- self$direction\n axis <- to_coord_axis(direction)\n panel <- .subset2(design, \"panel\")\n index <- .subset2(design, \"index\")\n coord_name <- paste0(\".\", axis)\n plot_data <- data_frame0(\n .panel = panel,\n .index = index,\n # `data_frame0` will omit `NULL`\n .names = .subset(self$labels, index)\n )\n plot_data[[coord_name]] <- seq_along(index)\n if (!is.null(.subset2(plot_data, \".names\"))) {\n plot_data[[paste0(\".discrete_\", axis)]] <- reorder(\n .subset2(plot_data, \".names\"),\n .subset2(plot_data, coord_name),\n order = FALSE\n )\n }\n\n if (!is.null(extra_plot_data)) {\n plot_data <- cross_join(plot_data, extra_plot_data)\n if (!is.null(data)) {\n plot_data <- full_join(data, plot_data,\n by.x = c(\".column_index\", \".index\"),\n by.y = c(\".extra_index\", \".index\")\n )\n }\n } else if (!is.null(data)) {\n plot_data <- full_join(data, plot_data, by = \".index\")\n }\n gguse_data(plot, ggalign_data_restore(plot_data, data))\n },\n\n # let Craftsman to add schemes and theme acoordingly\n finish_plot = function(self, plot, schemes, theme) {\n direction <- self$direction\n # remove axis titles, text, ticks used for alignment\n if (isTRUE(self$no_axes)) {\n schemes$scheme_theme <- .subset2(schemes, \"scheme_theme\") +\n theme_no_axes(switch_direction(direction, \"y\", \"x\"))\n }\n plot <- plot_add_schemes(plot, schemes)\n if (is_horizontal(direction)) {\n theme <- theme(\n panel.spacing.y = calc_element(\"panel.spacing.y\", theme)\n )\n } else {\n theme <- theme(\n panel.spacing.x = calc_element(\"panel.spacing.x\", theme)\n )\n }\n plot <- plot + theme\n ggremove_margin(plot, direction) + theme_recycle()\n },\n summary = function(self, plot) {\n header <- ggproto_parent(Craftsman, self)$summary(plot)\n c(header, \" Add plot by Aligning discrete or continuous variable\")\n }\n)\n\n#' Create ggplot object with layout panel data\n#'\n#' @description\n#' `r lifecycle::badge(\"deprecated\")`\n#'\n#' This function was deprecated because we realised that it's a special case of\n#' the [`ggalign()`] function. Please use `ggalign(data = NULL)` instead.\n#' @export\n#' @keywords internal\nalign_panel <- function(...) {\n lifecycle::deprecate_stop(\"0.0.5\", \"align_panel()\", \"ggalign(data = NULL)\")\n}\n\n#' @export\n#' @rdname align_panel\nggpanel <- function(...) {\n lifecycle::deprecate_stop(\"0.0.5\", \"ggpanel()\", \"ggalign(data = NULL)\")\n}\n"], ["/ggalign/R/craft-cross-mark.R", "#' Add a plot to annotate observations\n#'\n#' @inheritParams cross_none\n#' @inheritParams ggmark\n#'\n#' @section ggplot2 Specification:\n#' The `cross_mark` function initializes a `ggplot` object. The underlying data\n#' contains following columns:\n#'\n#' - `.panel`: the panel for the aligned axis. It means `x-axis` for vertical\n#' stack layout (including top and bottom annotation), `y-axis` for\n#' horizontal stack layout (including left and right annotation).\n#'\n#' - `.names` ([`vec_names()`][vctrs::vec_names]) and `.index`\n#' ([`vec_size()`][vctrs::vec_size()]/[`NROW()`]): a character names (only\n#' applicable when names exists) and an integer of index of the original\n#' data.\n#'\n#' - `.hand`: A factor with levels `c(\"left\", \"right\")` for horizontal stack\n#' layouts, or `c(\"top\", \"bottom\")` for vertical stack layouts, indicating\n#' the position of the linked observations.\n#'\n#' You can use [`scheme_data()`] to modify the internal data if needed.\n#'\n#' @export\ncross_mark <- function(mark, data = waiver(), ...,\n obs_size = 1, inherit_index = NULL, inherit_panel = NULL,\n inherit_nobs = NULL,\n size = NULL, active = NULL) {\n if (!inherits(mark, \"ggalign_mark_draw\")) {\n cli_abort(\"{.arg mark} must be a {.fn mark_draw} object\")\n }\n assert_obs_size(obs_size)\n assert_active(active)\n active <- update_active(active, new_active(use = TRUE))\n cross(CrossMark,\n data = data, data_params = list2(...),\n mark = mark, obs_size = obs_size,\n plot = ggplot(), size = size,\n schemes = default_schemes(th = theme_panel_border()),\n active = active,\n inherit_nobs = inherit_nobs,\n inherit_panel = inherit_panel,\n inherit_index = inherit_index\n )\n}\n\n#' @importFrom ggplot2 ggproto ggproto_parent\n#' @include craft-cross-.R\nCrossMark <- ggproto(\"CrossMark\", CraftCross,\n interact_layout = function(self, layout) {\n if (!self$in_linear) { # only used for linear coordinate\n cli_abort(c(\n sprintf(\n \"Cannot add %s to %s\",\n object_name(self), layout_name\n ),\n i = sprintf(\n \"%s can only be used in linear layout\",\n object_name(self)\n )\n ))\n }\n ggproto_parent(CraftCross, self)$interact_layout(layout)\n },\n build_plot = function(self, plot, design, extra_design = NULL,\n previous_design = NULL) {\n if (is.null(.subset2(previous_design, \"nobs\"))) {\n cli_abort(\n sprintf(\n \"layout {.field nobs} for %s before %s is not initialized \",\n self$layout_name, object_name(self)\n )\n )\n }\n if (is.null(.subset2(design, \"nobs\"))) {\n cli_abort(\n sprintf(\n \"layout {.field nobs} for %s after %s is not initialized \",\n self$layout_name, object_name(self)\n )\n )\n }\n direction <- self$direction\n\n # parse links --------------------------------------------\n mark <- self$mark\n design1 <- previous_design\n design2 <- design\n full_data1 <- split(\n seq_len(.subset2(design1, \"nobs\")),\n .subset2(design1, \"panel\")\n )\n full_data2 <- split(\n seq_len(.subset2(design2, \"nobs\")),\n .subset2(design2, \"panel\")\n )\n link_index <- make_links_data(\n .subset2(mark, \"links\"),\n design1 = design1, design2 = design2,\n labels1 = self$labels0, labels2 = self$labels\n )\n if (vec_duplicate_any(nms <- names(link_index))) { # nolint\n cli_abort(\n c(\n \"panel names must be unique in {.arg mark}\",\n i = \"duplicated names: {.val {nms[vec_duplicate_detect(nms)]}}\"\n ),\n call = self$call\n )\n }\n data_index <- lapply(link_index, function(link) {\n if (is.null(link)) {\n return(NULL)\n }\n hand1 <- .subset2(link, \"hand1\")\n hand2 <- .subset2(link, \"hand2\")\n list(\n hand1 = .subset2(design1, \"index\")[hand1],\n hand2 = .subset2(design2, \"index\")[hand2]\n )\n })\n\n # prepare data for the plot\n plot_data <- lapply(data_index, function(index) {\n if (is.null(index)) {\n return(NULL)\n }\n hand1 <- .subset2(index, \"hand1\")\n hand2 <- .subset2(index, \"hand2\")\n hand <- switch_direction(\n direction,\n c(\"left\", \"right\"),\n c(\"top\", \"bottom\")\n )\n data_frame0(\n .hand = vec_rep_each(hand, c(length(hand1), length(hand2))),\n .names = vec_c(self$labels0[hand1], self$labels[hand2]),\n .index = vec_c(hand1, hand2)\n )\n })\n plot_data <- vec_rbind(!!!plot_data, .names_to = \".panel\")\n plot_data$.panel <- factor(plot_data$.panel, names(data_index))\n plot_data$.hand <- factor(plot_data$.hand, switch_direction(\n direction, c(\"left\", \"right\"), c(\"bottom\", \"top\")\n ))\n\n # prepare data for the plot ------------------------------\n plot <- gguse_data(plot, plot_data)\n\n # set up facets\n if (nlevels(plot_data$.panel) > 1L) {\n if (inherits(plot$facet, \"FacetGrid\")) {\n facet <- switch_direction(\n direction,\n ggplot2::facet_grid(\n rows = ggplot2::vars(.data$.panel),\n scales = \"free_y\", space = \"free\",\n drop = FALSE, as.table = FALSE\n ),\n ggplot2::facet_grid(\n cols = ggplot2::vars(.data$.panel),\n scales = \"free_x\", space = \"free\",\n drop = FALSE, as.table = FALSE\n )\n )\n } else {\n facet <- switch_direction(\n direction,\n ggplot2::facet_wrap(\n facets = ggplot2::vars(.data$.panel),\n ncol = 1L, as.table = FALSE\n ),\n ggplot2::facet_wrap(\n facets = ggplot2::vars(.data$.panel),\n nrow = 1L, as.table = FALSE\n )\n )\n }\n } else {\n facet <- facet_stack(direction, object_name(self))\n }\n # `free_row` and `free_column` have nothing with `facet_stack`\n # it's safe to use it directly\n plot <- ggmelt_facet(plot, facet, free_row = TRUE, free_column = TRUE)\n plot$ggalign_link_data <- list(\n full_data1 = full_data1,\n full_data2 = full_data2,\n link_index = link_index,\n data_index = data_index,\n direction = direction,\n draw = .subset2(mark, \"draw\"),\n obs_size = self$obs_size\n )\n add_class(plot, \"ggalign_mark_plot\", \"patch_ggplot\")\n },\n finish_plot = function(self, plot, schemes, theme) {\n plot <- plot_add_schemes(plot, schemes)\n\n # save spacing for usage\n spacing <- calc_element(\n switch_direction(\n self$direction,\n \"panel.spacing.y\",\n \"panel.spacing.x\"\n ),\n theme\n ) %||% unit(0, \"mm\")\n\n # save spacing for usage\n plot$ggalign_link_data$spacing1 <-\n plot$ggalign_link_data$spacing2 <- spacing\n\n plot + theme_recycle()\n },\n summary = function(self, plot) {\n header <- ggproto_parent(CraftCross, self)$summary(plot)\n c(header, \" Add plot to annotate observations\")\n }\n)\n\nmark_use_facet <- function(plot, facet) {\n\n}\n"], ["/ggalign/R/ggmark.R", "#' Add a plot to annotate selected observations\n#'\n#' @param mark A [`mark_draw()`] object to define how to draw the links. Like\n#' [`mark_line()`], [`mark_tetragon()`]. Note the names of the pair links will\n#' be used to define the panel names so must be unique.\n#' @inheritParams ggalign\n#' @param group1,group2 A single boolean value indicating whether to use the\n#' panel group information from the layout as the paired groups. By default,\n#' if no specific observations are selected in `mark`, `ggmark()` will\n#' automatically connect all observations and group them according to the\n#' layout's defined groups.\n#' @param obs_size A single numeric value that indicates the size of a single\n#' observation, ranging from `(0, 1]`.\n#' @section ggplot2 specification:\n#' `ggmark` initializes a ggplot object. The underlying data is created using\n#' [`fortify_data_frame()`]. Please refer to it for more details.\n#'\n#' In addition, the following columns will be added to the data frame:\n#'\n#' - `.panel`: the panel for the aligned axis. It means `x-axis` for vertical\n#' stack layout (including top and bottom annotation), `y-axis` for\n#' horizontal stack layout (including left and right annotation).\n#'\n#' - `.names` ([`vec_names()`][vctrs::vec_names]) and `.index`\n#' ([`vec_size()`][vctrs::vec_size()]/[`NROW()`]): a character names (only\n#' applicable when names exists) and an integer of index of the original\n#' data.\n#'\n#' - `.hand`: A factor with levels `c(\"left\", \"right\")` for horizontal stack\n#' layouts, or `c(\"top\", \"bottom\")` for vertical stack layouts, indicating\n#' the position of the linked observations.\n#'\n#' @examples\n#' set.seed(123)\n#' small_mat <- matrix(rnorm(56), nrow = 7)\n#' rownames(small_mat) <- paste0(\"row\", seq_len(nrow(small_mat)))\n#' colnames(small_mat) <- paste0(\"column\", seq_len(ncol(small_mat)))\n#'\n#' # mark_line\n#' ggheatmap(small_mat) +\n#' theme(axis.text.x = element_text(hjust = 0, angle = -60)) +\n#' anno_right() +\n#' align_kmeans(3L) +\n#' ggmark(mark_line(I(1:3) ~ NULL)) +\n#' geom_boxplot(aes(.names, value)) +\n#' theme(plot.margin = margin(l = 0.1, t = 0.1, unit = \"npc\"))\n#'\n#' # mark_tetragon\n#' ggheatmap(small_mat) +\n#' theme(axis.text.x = element_text(hjust = 0, angle = -60)) +\n#' anno_right() +\n#' align_kmeans(3L) +\n#' ggmark(mark_tetragon(I(1:3) ~ NULL)) +\n#' geom_boxplot(aes(.names, value)) +\n#' theme(plot.margin = margin(l = 0.1, t = 0.1, unit = \"npc\"))\n#' @importFrom rlang list2\n#' @export\nggmark <- function(mark, data = waiver(), mapping = aes(), ...,\n group1 = NULL, group2 = NULL,\n obs_size = 1, size = NULL, active = NULL) {\n if (!inherits(mark, \"ggalign_mark_draw\")) {\n cli_abort(\"{.arg mark} must be a {.fn mark_draw} object\")\n }\n assert_obs_size(obs_size)\n assert_active(active)\n active <- update_active(active, new_active(use = TRUE))\n assert_bool(group1, allow_null = TRUE)\n assert_bool(group2, allow_null = TRUE)\n new_craftbox(\n MarkGg,\n # fields added to `MarkGg`\n input_data = allow_lambda(data), # used by AlignGg\n params = list2(...), # used by AlignGg\n mark = mark, # used by MarkGg\n group1 = group1, group2 = group2,\n obs_size = obs_size,\n\n # slot\n plot = ggplot(mapping = mapping),\n size = size,\n schemes = default_schemes(data, th = theme_panel_border()),\n active = active\n )\n}\n\n#' @importFrom ggplot2 ggproto ggplot margin element_rect\nMarkGg <- ggproto(\"MarkGg\", Craftsman,\n free_facet = TRUE,\n free_limits = TRUE,\n interact_layout = function(self, layout) {\n layout_name <- self$layout_name\n if (!self$in_linear) { # only used for linear coordinate\n cli_abort(c(\n sprintf(\n \"Cannot add %s to %s\",\n object_name(self), layout_name\n ),\n i = sprintf(\n \"%s can only be used in linear layout\",\n object_name(self)\n )\n ))\n }\n if (is_layout_continuous(layout)) { # only used for discrete variable\n # ggmark special for discrete variables\n cli_abort(c(\n sprintf(\"Cannot add %s to %s\", object_name(self), layout_name),\n i = sprintf(\"%s cannot align discrete variables\", layout_name)\n ))\n }\n ans <- ggproto_parent(AlignGg, self)$interact_layout(layout)\n self$labels0 <- self$labels # CrossMark uses `labels0`\n ans\n },\n build_plot = function(self, plot, design, extra_design = NULL,\n previous_design = NULL) {\n if (is.null(.subset2(design, \"nobs\"))) {\n cli_abort(sprintf(\n \"you must initialize %s before drawing %s\",\n self$layout_name, object_name(self)\n ), call = self$call)\n }\n mark <- self$mark\n\n # parse links --------------------------------------------\n links <- .subset2(mark, \"links\")\n group1 <- self$group1\n group2 <- self$group2\n position <- self$position\n if (is_empty(links) && is.null(group1) && is.null(group2)) {\n # guess group1 and group2 from position\n if (is.null(position)) { # a normal stack layout\n group1 <- TRUE\n } else if (any(position == c(\"top\", \"left\"))) {\n group2 <- TRUE\n } else {\n group1 <- TRUE\n }\n }\n full_data <- split(\n seq_len(.subset2(design, \"nobs\")),\n .subset2(design, \"panel\")\n )\n if (isTRUE(group1) && isTRUE(group2)) {\n extra_links <- mapply(function(l1, l2) {\n new_pair_link(I(l1), I(l2))\n }, full_data, full_data, SIMPLIFY = FALSE)\n } else if (isTRUE(group1)) {\n extra_links <- lapply(full_data, function(l) {\n new_pair_link(hand1 = I(l))\n })\n } else if (isTRUE(group2)) {\n extra_links <- lapply(full_data, function(l) {\n new_pair_link(hand2 = I(l))\n })\n } else {\n extra_links <- NULL\n }\n\n # unlock the object\n self$unlock()\n self$mark$links <- vec_c(extra_links, links)\n on.exit(self$mark <- mark, add = TRUE) # restore the original `mark`\n on.exit(self$lock(), add = TRUE)\n\n # setup the plot\n plot <- ggproto_parent(CrossMark, self)$build_plot(\n plot,\n design,\n extra_design,\n previous_design %||% design\n )\n plot_data <- plot$data\n\n # prepare data for the plot ------------------------------\n if (!is.null(data <- self$data)) {\n plot_data <- inner_join(plot_data, data, by = \".index\")\n }\n gguse_data(plot, ggalign_data_restore(plot_data, data))\n },\n finish_plot = function(self, plot, schemes, theme) {\n ggproto_parent(CrossMark, self)$finish_plot(plot, schemes, theme)\n },\n summary = function(self, plot) {\n header <- ggproto_parent(Craftsman, self)$summary(plot)\n c(header, \" Add plot to annotate observations\")\n }\n)\n"], ["/ggalign/R/layout-align.R", "#' Set Expansion for the Layout\n#'\n#' @description\n#' To align axes, it is important to keep the expansion consistent across all\n#' plots in the layout. You can add a `layout_expand` object to the layout. For\n#' the `quad_layout()` function, you must specify `x` and `y` arguments. For\n#' other layouts, you can pass the expansion values using `...` directly.\n#'\n#' @param ... A list of range expansion constants, used to add padding around\n#' the data to ensure they are placed some distance away from the axes. Use the\n#' convenience function [`expansion()`][ggplot2::expansion()] to generate the\n#' values.\n#' @param x,y Same as `...`, but specifically for `quad_layout()`.\n#'\n#' @importFrom rlang list2\n#' @keywords internal\nlayout_expand <- function(..., x = waiver(), y = waiver()) {\n if (...length() > 0L && (!is.waive(x) || !is.waive(y))) {\n cli_abort(\n \"Cannot mix the usage of {.arg ...} with {.arg x}/{.arg y} argument\"\n )\n }\n if (...length() > 0L) {\n ans <- list2(...)\n names(ans) <- NULL\n } else {\n ans <- list(x = x, y = y)\n }\n structure(ans, class = \"ggalign_layout_expand\")\n}\n\n#' Set continuous limits for the layout\n#'\n#' @description\n#' To align continuous axes, it is important to keep the limits consistent\n#' across all plots in the layout. You can set the limits by passing a function\n#' directly to the `limits` or `xlim`/`ylim` argument, using `...` only.\n#' Alternatively, you can add a `continuous_limits()` object to the layout. For\n#' the `quad_layout()` function, you must specify `x`/`y` arguments. For other\n#' layouts, you should pass the limits using `...` directly.\n#'\n#' @param ... A list of two numeric values, specifying the left/lower limit and\n#' the right/upper limit of the scale.\n#' @inheritParams layout_expand\n#' @importFrom rlang list2\n#' @export\ncontinuous_limits <- function(..., x = waiver(), y = waiver()) {\n if (...length() > 0L && (!is.waive(x) || !is.waive(y))) {\n cli_abort(\n \"Cannot mix the usage of {.arg ...} with {.arg x}/{.arg y} argument\"\n )\n }\n if (...length() > 0L) {\n ans <- list2(...)\n names(ans) <- NULL\n } else {\n ans <- list(x = x, y = y)\n }\n structure(ans, class = c(\"continuous_limits\", \"layout_design\"))\n}\n\n# layout params are used to align the observations\ndiscrete_design <- function(panel = NULL, index = NULL, nobs = NULL) {\n structure(\n list(panel = panel, index = index, nobs = nobs),\n class = c(\"discrete_design\", \"layout_design\")\n )\n}\n\n################################################################\nis_continuous_design <- function(x) {\n is.null(x) || inherits(x, \"continuous_limits\")\n}\n\nis_discrete_design <- function(x) inherits(x, \"discrete_design\")\n\n#' Layout can align ordinal variable or continuous variable\n#'\n#' @param x A `LayoutProto` object.\n#' @noRd\nis_layout_discrete <- function(x, ...) UseMethod(\"is_layout_discrete\")\n\nis_layout_continuous <- function(x, ...) UseMethod(\"is_layout_continuous\")\n\n################################################################\n# Initialize the index and panel\n# Reorder the panel based the ordering index and\nsetup_design <- function(design) {\n # for continuous axis, do noting special\n if (is_continuous_design(design)) return(design) # styler: off\n # if `nobs` is not initialized, it means no `Align` object exist\n # it's not necessary to initialize the `panel` and `index`\n # this is for `stack_layout` which may have no data\n if (is.null(nobs <- .subset2(design, \"nobs\"))) {\n return(design)\n }\n panel <- .subset2(design, \"panel\") %||% factor(rep_len(1L, nobs))\n index <- .subset2(design, \"index\") %||% reorder_index(panel)\n discrete_design(panel[index], index, nobs)\n}\n\nreorder_index <- function(panel, index = NULL) {\n index <- index %||% seq_along(panel)\n unlist(split(index, panel[index]), recursive = FALSE, use.names = FALSE)\n}\n\n############################################################\n#' @keywords internal\nupdate_design <- function(layout, ..., design, object_name) {\n UseMethod(\"update_design\")\n}\n\n#' @importFrom methods slot slot<-\n#' @export\nupdate_design.QuadLayout <- function(layout, ..., direction, design,\n object_name) {\n slot(layout, direction) <- design\n if (is_horizontal(direction)) {\n if (!is.null(left <- layout@left)) {\n layout@left <- update_design(left,\n design = design, object_name = object_name\n )\n }\n if (!is.null(right <- layout@right)) {\n layout@right <- update_design(right,\n design = design, object_name = object_name,\n from_head = TRUE\n )\n }\n } else {\n if (!is.null(top <- layout@top)) {\n layout@top <- update_design(top,\n design = design, object_name = object_name\n )\n }\n if (!is.null(bottom <- layout@bottom)) {\n layout@bottom <- update_design(bottom,\n design = design, object_name = object_name,\n from_head = TRUE\n )\n }\n }\n layout\n}\n\n#' @importFrom methods slot slot<-\n#' @export\nupdate_design.StackLayout <- function(layout, ..., design, object_name) {\n layout@design <- design\n layout@plot_list <- lapply(layout@plot_list, function(plot) {\n if (is_craftbox(plot)) return(plot) # styler: off\n update_design(plot,\n direction = layout@direction,\n design = design\n )\n })\n layout\n}\n\n#' @export\nupdate_design.CircleLayout <- update_design.StackLayout\n\n#' @importFrom methods slot slot<-\n#' @export\nupdate_design.StackCross <- function(layout, ..., design, object_name,\n from_head = FALSE) {\n # `design` must be a discrete_design()\n design_list <- c(layout@odesign, list(layout@design))\n\n # for cross_points, the updating will span it, but only update the panel\n # information\n cross_points <- layout@cross_points\n\n # the break_points set breaks, updating won't span the break points\n break_points <- layout@break_points\n\n plot_list <- layout@plot_list\n n <- length(plot_list)\n points <- c(cross_points, n)\n point_index <- seq_along(points)\n if (!from_head) point_index <- rev(point_index)\n for (i in point_index) {\n cross_point <- .subset(points, i)\n\n # we first update the design in the updated tail\n # it means the first design when `from_head` is `TRUE`\n # the last design when `from_head` is `FALSE`\n if ((from_head && i == 1L) || (!from_head && cross_point == n)) {\n new_design <- design\n } else if (!from_head && any(cross_point == break_points)) {\n break\n } else {\n # for design not in updated tail, we'll only update `panel` and\n # `nobs`, we check the new panel doesn't break the original index\n new_nobs <- .subset2(design, \"nobs\")\n new_panel <- .subset2(design, \"panel\")\n new_design <- .subset2(design_list, i)\n # we check the new panel don't disrupt the ordering index\n if (!is.null(new_panel) &&\n !is.null(old_index <- .subset2(new_design, \"index\"))) {\n # we always prevent from reordering twice.\n new_index <- reorder_index(new_panel, old_index)\n if (!all(old_index == new_index)) {\n cli_abort(sprintf(\n \"%s disrupt the previously established ordering index of %s (%d)\",\n object_name, object_name(layout), i\n ))\n }\n new_design[\"index\"] <- list(new_index)\n }\n new_design[\"nobs\"] <- list(new_nobs)\n new_design[\"panel\"] <- list(new_panel)\n }\n design_list[i] <- list(new_design)\n\n # we then update the design for each plot\n if (i == 1L) {\n subset <- seq_len(cross_point)\n } else {\n subset <- (.subset(points, i - 1L) + 1L):cross_point\n }\n\n layout@plot_list[subset] <- lapply(\n plot_list[subset], function(plot) {\n if (is_craftbox(plot)) {\n return(plot)\n }\n update_design(plot,\n direction = layout@direction,\n design = new_design\n )\n }\n )\n if (from_head && any(cross_point == break_points)) break\n }\n layout@odesign <- vec_slice(design_list, seq_len(length(design_list) - 1L))\n layout@design <- design_list[[length(design_list)]]\n layout\n}\n\n############################################################\nmelt_discrete_design <- function(old, new, old_name, new_name,\n call = caller_call()) {\n old_nobs <- .subset2(old, \"nobs\")\n new_nobs <- .subset2(new, \"nobs\")\n if (is.null(new_nobs)) { # no `nobs` provided\n nobs <- old_nobs\n } else if (is.null(old_nobs)) {\n nobs <- new_nobs\n } else if (!identical(new_nobs, old_nobs)) {\n cli_abort(sprintf(\n \"%s (nobs: %d) is not compatible with the %s (nobs: %d)\",\n new_name, new_nobs, old_name, old_nobs\n ), call = call)\n } else {\n nobs <- new_nobs\n }\n\n # check panel\n old_panel <- .subset2(old, \"panel\")\n new_panel <- .subset2(new, \"panel\")\n\n if (is.null(new_panel)) { # no panel provided\n panel <- old_panel\n } else if (!is.null(old_panel) && !(new_panel %nest% old_panel)) {\n cli_abort(sprintf(\n \"%s disrupt the previously established panel groups of %s\",\n new_name, old_name\n ), call = call)\n } else {\n panel <- new_panel\n }\n\n # check index\n old_index <- .subset2(old, \"index\")\n new_index <- .subset2(new, \"index\")\n if (is.null(new_index)) {\n index <- old_index\n } else {\n index <- new_index\n }\n\n # we always make the index following the panel\n if (!is.null(panel) && !is.null(index)) {\n index <- reorder_index(panel, index)\n }\n\n # we always prevent from reordering twice.\n if (!is.null(old_index) && !all(old_index == index)) {\n cli_abort(sprintf(\n \"%s disrupt the previously established ordering index of %s\",\n new_name, old_name\n ), call = call)\n }\n discrete_design(panel, index, nobs)\n}\n\n#######################################################################\n# ggplot2 add default scales in `compute_aesthetics` process\n# then ggplot2 transform all scales\n# layout:\n# in ggplot_build\n# - `setup`:\n# - call `facet$setup_params`\n# - attach `plot_env`\n# - call `facet$setup_data`\n# - call `facet$compute_layout`\n# - call `coord$setup_layout`\n# - call `facet$map_data`\n# - `train_position`: (run twice)\n# - call `facet$init_scales`\n# - call `facet$train_scales`\n# - `setup_panel_params`\n# - call `coord$modify_scales`: we align scales here, since this step\n# scales have been trained\n# - call `coord$setup_panel_params`: `view_scales_from_scale()`\n# - `map_position`\n# - `setup_panel_guides`\n# - call `coord$setup_panel_guides`\n# - call `coord$train_panel_guides`\n# in ggplot_gtable\n# - `layout$render`:\n# - call `facet$draw_back`\n# - call `facet$draw_front`\n# - call `coord$draw_panel` for each panel\n# - call `facet$draw_panels`: only once\n# - call `facet$init_gtable`:\n# - call `facet$attach_axes`:\n# - call `coord$render_axis_h`:\n# - call `guide$draw`:\n# - call `coord$render_axis_v`:\n# - call `guide$draw`:\n# - call `facet$attach_strips`:\n\n#' Set `limits`, `breaks`, `labels` for each panel\n#'\n#' @param x,y design for the layout.\n#' @keywords internal\n#' @noRd\nggalign_design <- function(x = NULL, y = NULL,\n xlabels = NULL, ylabels = NULL,\n xlim = TRUE, ylim = TRUE) {\n structure(\n list(\n x = x, y = y,\n xlabels = xlabels, ylabels = ylabels,\n xlim = xlim, ylim = ylim\n ),\n class = \"ggalign_design\"\n )\n}\n\nsetup_discrete_limits <- function(axis, design, n_panels) {\n panel <- .subset2(design, \"panel\")\n index <- .subset2(design, \"index\")\n if (n_panels == 1L) {\n list(range(index) + c(-0.5, 0.5))\n } else {\n # For y-axis, ggplot arrange panel from top to bottom,\n # we always choose to reverse the panel order\n if (axis == \"y\") panel <- fct_rev(panel)\n lapply(split(seq_along(index), panel), function(plot_index) {\n range(plot_index) + c(-0.5, 0.5)\n })\n }\n}\n\n#' @importFrom ggplot2 ggplot_add ggproto ggproto_parent\n#' @export\nggplot_add.ggalign_design <- function(object, plot, object_name, ...) {\n x_design <- .subset2(object, \"x\")\n y_design <- .subset2(object, \"y\")\n if (is.null(x_design) && is.null(y_design)) {\n return(plot)\n }\n ParentCoord <- plot$coordinates\n plot$coordinates <- ggproto(\n NULL, ParentCoord,\n num_of_panels = NULL,\n panel_counter = NULL,\n n_row_panels = NULL, # should be the number of panels in y\n n_column_panels = NULL, # should be the number of panels in x\n setup_layout = function(self, layout, params) {\n # we always initialize the number of panels and a panel counter\n self$num_of_panels <- vec_unique_count(.subset2(layout, \"PANEL\"))\n self$panel_counter <- 0L\n self$n_column_panels <- vec_unique_count(.subset2(layout, \"COL\"))\n self$n_row_panels <- vec_unique_count(.subset2(layout, \"ROW\"))\n if (.subset2(object, \"xlim\") && !is.null(x_design)) {\n if (is_discrete_design(x_design)) {\n self$xlim_list <- setup_discrete_limits(\n \"x\", x_design, self$n_column_panels\n )\n } else {\n self$xlim_list <- x_design\n }\n }\n if (.subset2(object, \"ylim\") && !is.null(y_design)) {\n if (is_discrete_design(y_design)) {\n self$ylim_list <- setup_discrete_limits(\n \"y\", y_design, self$n_row_panels\n )\n } else {\n self$ylim_list <- y_design\n }\n }\n # call the parent method\n ggproto_parent(ParentCoord, self)$setup_layout(layout, params)\n },\n # take the tricks to modify scales in place\n modify_scales = function(self, scales_x, scales_y) {\n # for each scale, we set the `breaks` and `labels`\n if (is_discrete_design(x_design)) {\n align_discrete_scales(\n \"x\", scales_x, x_design,\n labels = .subset2(object, \"xlabels\"),\n n_panels = self$n_column_panels,\n circle_layout = inherits(ParentCoord, \"CoordRadial\")\n )\n }\n if (is_discrete_design(y_design)) {\n align_discrete_scales(\n \"y\", scales_y, y_design,\n labels = .subset2(object, \"ylabels\"),\n n_panels = self$n_row_panels,\n circle_layout = inherits(ParentCoord, \"CoordRadial\")\n )\n }\n ggproto_parent(ParentCoord, self)$modify_scales(scales_x, scales_y)\n },\n setup_panel_params = function(self, scale_x, scale_y, params = list()) {\n # `setup_panel_params()` will utilize the `limits`\n # set limits here to ensure each plot will have the same limits\n cur_panel <- self$panel_counter + 1L\n if (!is.null(self$xlim_list)) {\n xlim <- .subset2(\n self$xlim_list,\n recycle_whole(cur_panel, self$n_column_panels)\n )\n if (is_discrete_design(x_design) && scale_x$is_discrete() &&\n !is.null(scale_x$range$range)) {\n # for discrete scale, the limits starts from zero in each\n # panel\n xlim <- xlim - (min(xlim) - 0.5)\n }\n if (inherits(self, \"CoordRadial\")) {\n self$limits$theta <- xlim\n } else {\n self$limits$x <- xlim\n }\n }\n if (!is.null(self$ylim_list)) {\n ylim <- .subset2(\n self$ylim_list,\n recycle_each(cur_panel, self$n_column_panels)\n )\n if (is_discrete_design(y_design) && scale_y$is_discrete() &&\n !is.null(scale_y$range$range)) {\n # for discrete scale, the limits starts from zero in each\n # panel\n ylim <- ylim - (min(ylim) - 0.5)\n }\n if (inherits(self, \"CoordRadial\")) {\n self$limits$r <- ylim\n } else {\n self$limits$y <- ylim\n }\n }\n self$panel_counter <- cur_panel\n ggproto_parent(ParentCoord, self)$setup_panel_params(\n scale_x = scale_x, scale_y = scale_y, params = params\n )\n }\n )\n plot\n}\n\nalign_discrete_scales <- function(axis, scales, design, labels, n_panels,\n circle_layout) {\n panel <- .subset2(design, \"panel\")\n index <- .subset2(design, \"index\")\n\n if (n_panels == 1L) {\n panel <- factor(vec_rep(1L, length(index)))\n } else {\n # For y-axis, ggplot arrange panel from top to bottom,\n # we always choose to reverse the panel order\n if (axis == \"y\") panel <- fct_rev(panel)\n }\n if (is.null(labels)) {\n data_labels <- NULL\n } else {\n data_labels <- split(labels, panel)\n }\n data_index <- split(index, panel)\n plot_index <- split(seq_along(index), panel)\n default_expand <- ggplot2::expansion()\n for (i in seq_along(scales)) {\n scale <- .subset2(scales, i)\n # we always use the discrete scale to determine labels and breaks\n # https://github.com/tidyverse/ggplot2/blob/7fb4c382f9ea332844d469663a8047355a88dd7a/R/scale-.R#L927\n # setup breaks and labels --------------------\n if (is.null(data_labels) &&\n is.waive(scale$labels) &&\n is.waive(scale$breaks)) {\n # special case for data have no labels\n # By default we also remove the breaks\n scale$breaks <- NULL\n scale$labels <- NULL\n } else {\n dindex <- .subset2(data_index, i)\n pindex <- .subset2(plot_index, i)\n labels <- .subset2(data_labels, i)\n scale$breaks <- get_discrete_breaks(scale, pindex, dindex, labels)\n scale$labels <- get_discrete_labels(\n scale, scale$breaks, pindex, dindex, labels\n )\n }\n\n # by default we elways remove any expansion\n # we don't allow the set of expansion for discrete variables\n # otherwise, ggmark and `cross_mark` won't work properly\n if (!circle_layout) scale$expand <- default_expand\n\n # for continuous scale, we don't allow the trans\n # if (!scale$is_discrete() && !identical(scale$trans$name, \"identity\")) {\n # cli_warn(sprintf(\n # \"{.arg trans} must be {.field identity} in {.code %s}\",\n # deparse(scale$call)\n # ))\n # scale$trans <- scales::as.transform(\"identity\")\n # }\n }\n}\n\n#' @importFrom rlang is_empty\nget_discrete_breaks <- function(scale, pindex, dindex, labels) {\n if (scale$is_empty()) return(numeric()) # styler: off\n breaks <- scale$breaks\n if (identical(breaks, NA)) {\n cli_abort(c(\n \"Invalid {.arg breaks} specification.\",\n i = \"Use {.code NULL}, not {.code NA}.\"\n ), call = scale$call)\n }\n if (is.null(breaks)) {\n return(NULL)\n }\n if (is.waive(breaks)) {\n if (scale$is_discrete() &&\n !is.null(labels) &&\n !is.null(scale$range$range) &&\n all(scale$range$range %in% labels)) {\n ans <- labels\n } else {\n ans <- pindex\n }\n } else {\n if (is.null(labels)) {\n limits <- dindex\n } else {\n limits <- labels\n }\n if (is.function(breaks)) {\n breaks <- breaks(limits)\n }\n\n if (is.factor(breaks) || is.character(breaks)) {\n # we interpreted the character breaks as the names of the original\n # matrix data.\n pos <- match(\n as.character(limits),\n vec_cast(breaks, character(),\n x_arg = \"breaks\", call = scale$call\n )\n )\n } else {\n # By default, we interpreted the breaks as the data index\n # If wrapped with `I()`, we interpreted it as the plot index\n if (inherits(breaks, \"AsIs\")) { # plot index\n pos <- match(pindex, vec_cast(breaks, integer(),\n x_arg = \"breaks\", call = scale$call\n ))\n } else { # data index\n pos <- match(dindex, vec_cast(breaks, integer(),\n x_arg = \"breaks\", call = scale$call\n ))\n }\n }\n index <- which(!is.na(pos))\n if (is_empty(index)) {\n return(NULL)\n }\n pos <- pos[index]\n if (scale$is_discrete() &&\n !is.null(labels) &&\n !is.null(scale$range$range) &&\n all(scale$range$range %in% labels)) {\n ans <- structure(labels[index], index = index, pos = pos)\n } else {\n ans <- structure(pindex[index], index = index, pos = pos)\n }\n }\n ans\n}\n\n#' @importFrom rlang is_empty\nget_discrete_labels <- function(scale, breaks, pindex, dindex, labels) {\n scale_labels <- scale$labels\n if (is_empty(breaks) || is.null(scale_labels)) { # if no breaks, no labels\n return(NULL)\n }\n\n if (identical(scale_labels, NA)) {\n cli_abort(c(\n \"Invalid {.arg labels} specification.\",\n i = \"Use {.code NULL}, not {.code NA}.\"\n ), call = scale$call)\n }\n\n # Need to ensure that if breaks were dropped\n if (!is.null(index <- attr(breaks, \"index\"))) {\n dindex <- dindex[index]\n labels <- labels[index]\n }\n\n # if layout have no names, use the data index directly\n # re-defined the breaks, the plot use the coordinates index\n # we interpreted user input as the data index\n if (is.null(labels)) {\n user_breaks <- dindex\n } else {\n user_breaks <- labels\n }\n if (is.waive(scale_labels)) { # By default, use the breaks\n user_breaks\n } else if (is.function(scale_labels)) {\n scale_labels(user_breaks)\n } else if (!is.null(names(scale_labels))) {\n # If labels have names, use them to match with breaks\n map <- match(as.character(user_breaks), names(scale_labels))\n user_breaks[map] <- scale_labels[!is.na(map)]\n user_breaks\n } else {\n # Need to ensure that if breaks were dropped, corresponding labels\n # are too\n if (is.null(pos <- attr(breaks, \"pos\"))) {\n if (inherits(scale_labels, \"AsIs\")) { # already in the plot index\n # we sort the `pos` so labels ordering won't be changed\n scale_labels <- scale_labels[pindex]\n } else { # in the data index\n scale_labels <- scale_labels[dindex]\n }\n } else {\n if (inherits(scale_labels, \"AsIs\")) { # already in the plot index\n # we sort the `pos` so labels ordering won't be changed\n scale_labels <- scale_labels[sort(pos)]\n } else { # in the data index\n scale_labels <- scale_labels[pos]\n }\n }\n scale_labels\n }\n}\n\n######################################################\n# this will remove the old coordinate,\n# so always run firstly\ngguse_linear_coord <- function(plot, layout_name) {\n coord <- plot$coordinates\n if (!inherits(coord, \"CoordTrans\") && !coord$is_linear()) {\n cli_warn(c(\n sprintf(\n \"{.fn %s} is not supported in %s\",\n snake_class(coord), layout_name\n ),\n i = \"Will use {.fn coord_cartesian} instead\"\n ))\n plot$coordinates <- ggplot2::coord_cartesian()\n }\n plot\n}\n\ngguse_circle_coord <- function(plot, coord, ..., layout_name) {\n if (inherits(plot_coord <- plot$coordinates, \"CoordRadial\")) {\n out <- ggproto(\n NULL, plot_coord,\n theta = coord$theta,\n r = coord$r,\n arc = coord$arc,\n direction = coord$direction,\n r_axis_inside = coord$r_axis_inside,\n expand = coord$expand,\n ...,\n setup_panel_params = circle_panel_params\n )\n } else {\n if (!isTRUE(plot$coordinates$default)) {\n cli_warn(c(\n sprintf(\n \"{.fn %s} is not supported in %s\",\n snake_class(plot_coord), layout_name\n ),\n i = sprintf(\"Will use {.fn %s} instead\", snake_class(coord))\n ))\n }\n if (!inherits(coord, \"CoordCircle\")) {\n out <- ggproto(NULL, coord, ...,\n setup_panel_params = circle_panel_params\n )\n } else {\n out <- ggproto(NULL, coord, ...)\n }\n }\n out\n}\n\n######################################################\n#' @importFrom ggplot2 ggproto\nggfacet_modify <- function(plot, ...) {\n ParentFacet <- plot$facet\n plot$facet <- ggproto(NULL, ParentFacet, ...)\n plot\n}\n\ngguse_facet <- function(plot, facet) {\n plot$facet <- facet\n plot\n}\n\nggmelt_facet <- function(plot, facet, ...) {\n gguse_facet(plot, melt_facet(facet, plot$facet, ...))\n}\n\n#' @param use A template facet object which will be used.\n#' @param facet User provided facet object.\n#' @noRd\nmelt_facet <- function(use, facet, ...) UseMethod(\"melt_facet\")\n\n#' @export\nmelt_facet.NULL <- function(use, facet, ...) {\n facet\n}\n\n#' @importFrom ggplot2 ggproto\n#' @export\nmelt_facet.FacetGrid <- function(use, facet, ...,\n free_row = FALSE,\n free_column = FALSE) {\n if (inherits(facet, \"FacetGrid\")) {\n # re-dispatch parameters\n params <- facet$params\n if (length(use$params$rows) || !free_row) {\n params$rows <- use$params$rows\n }\n if (length(use$params$cols) || !free_column) {\n params$cols <- use$params$cols\n }\n if (!free_row) { # Don't allow user change the rows\n params$free$y <- use$params$free$y\n params$space_free$y <- use$params$space_free$y\n }\n if (!free_column) { # Don't allow user change the cols\n params$free$x <- use$params$free$x\n params$space_free$x <- use$params$space_free$x\n }\n\n params$drop <- use$params$drop\n params$as.table <- use$params$as.table\n\n # if the use is free, it must be free\n ggproto(NULL, facet, params = params)\n } else {\n use\n }\n}\n\n#' @importFrom ggplot2 ggproto\n#' @export\nmelt_facet.FacetWrap <- function(use, facet, ...) {\n if (inherits(facet, \"FacetWrap\")) {\n # re-dispatch parameters\n params <- facet$params\n\n # we always fix the grid rows and cols\n params$facets <- use$params$facets\n params$nrow <- use$params$nrow\n params$ncol <- use$params$ncol\n params$drop <- use$params$drop\n params$as.table <- use$params$as.table\n ggproto(NULL, facet, params = params)\n } else {\n use\n }\n}\n\n#' @export\nmelt_facet.FacetNull <- function(use, facet, ...) {\n if (inherits(facet, \"FacetNull\")) {\n facet\n } else {\n use\n }\n}\n\n#' @export\nmelt_facet.FacetStack <- function(use, facet, ...) {\n if (inherits(facet, \"FacetGrid\")) {\n params <- facet$params\n if (is_horizontal(.subset2(use, \"direction\"))) {\n # for horizontal stack, we cannot facet by rows\n if (!is.null(params$rows)) {\n cli_warn(sprintf(\n \"Cannot facet by rows in %s\",\n .subset2(use, \"object_name\")\n ))\n params$rows <- NULL\n }\n } else if (!is.null(params$cols)) {\n # for vertical stack, we cannot facet by cols\n cli_warn(sprintf(\n \"Cannot facet by cols in %s\",\n .subset2(use, \"object_name\")\n ))\n params$cols <- NULL\n }\n ggproto(NULL, facet, params = params)\n } else if (inherits(facet, \"FacetWrap\")) {\n params <- facet$params\n if (is_horizontal(.subset2(use, \"direction\"))) {\n # for horizontal stack, we cannot facet by rows\n if (is.null(params$nrow)) {\n params$nrow <- 1L\n } else if (params$nrow > 1L) {\n cli_warn(sprintf(\n \"Cannot wrap facet by rows in %s\",\n .subset2(use, \"object_name\")\n ))\n params$nrow <- 1L\n }\n } else if (!is.null(params$cols)) {\n # for vertical stack, we cannot facet by cols\n if (is.null(params$ncol)) {\n params$ncol <- 1L\n } else if (params$ncol > 1L) {\n cli_warn(sprintf(\n \"Cannot wrap facet by cols in %s\",\n .subset2(use, \"object_name\")\n ))\n params$ncol <- 1L\n }\n }\n } else if (inherits(facet, \"FacetNull\")) {\n facet\n } else {\n ggplot2::facet_null()\n }\n}\n\nfacet_stack <- function(direction, object_name) {\n structure(\n list(direction = direction, object_name = object_name),\n class = \"FacetStack\"\n )\n}\n\n#' @export\nmelt_facet.FacetQuad <- function(use, facet, ...,\n free_row = FALSE,\n free_column = FALSE) {\n if (inherits(facet, \"FacetGrid\")) {\n if (free_row || free_column) {\n params <- facet$params\n if (!free_row && !is.null(params$rows)) {\n cli_warn(sprintf(\n \"Cannot facet by rows in %s\",\n .subset2(use, \"layout_name\")\n ))\n params$rows <- NULL\n # for horizontal stack, we cannot facet by rows\n }\n if (!free_column && !is.null(params$cols)) {\n cli_warn(sprintf(\n \"Cannot facet by cols in %s\",\n .subset2(use, \"layout_name\")\n ))\n params$cols <- NULL\n }\n ggproto(NULL, facet, params = params)\n } else {\n ggplot2::facet_null()\n }\n } else if (inherits(facet, \"FacetNull\")) {\n facet\n } else {\n ggplot2::facet_null()\n }\n}\n\nfacet_quad <- function(layout_name) {\n structure(list(layout_name = layout_name), class = \"FacetQuad\")\n}\n"], ["/ggalign/R/ggfree.R", "#' Add ggplot to layout without alignment\n#'\n#' @description\n#' `r lifecycle::badge('experimental')`\n#'\n#' The `ggfree()` function allows you to incorporate a ggplot object into your\n#' layout. Unlike `ggalign()`, which aligns every axis value precisely,\n#' `ggfree()` focuses on integrating plots into the layout without enforcing\n#' strict axis alignment.\n#'\n#' @inheritParams ggalign\n#'\n#' @section ggplot2 specification:\n#' `ggalign` initializes a ggplot object. The underlying data is created using\n#' [`fortify_data_frame()`]. Please refer to this method for more details.\n#'\n#' When used in `quad_layout()`/`ggheatmap()`, if the data is inherited from the\n#' `quad_layout()` and the other direction aligns discrete variables, following\n#' columns will be added:\n#'\n#' - `.extra_panel`: Provides the panel information for the column (left or\n#' right annotation) or row (top or bottom annotation).\n#' - `.extra_index`: The index information for the column (left or right\n#' annotation) or row (top or bottom annotation).\n#'\n#' @examples\n#' ggheatmap(matrix(rnorm(56), nrow = 7)) +\n#' anno_top() +\n#' align_dendro() +\n#' ggfree(mtcars, aes(wt, mpg)) +\n#' geom_point()\n#' @export\nggfree <- function(data = waiver(), ..., size = NULL, active = NULL) {\n UseMethod(\"ggfree\", data)\n}\n\n#' @inheritParams ggplot2::ggplot\n#' @importFrom ggplot2 ggplot\n#' @export\n#' @rdname ggfree\nggfree.default <- function(data = waiver(), mapping = aes(), ...,\n size = NULL, active = NULL) {\n data <- fortify_data_frame(data = data, ...)\n new_free_gg(\n plot = ggplot(data = NULL, mapping = mapping),\n data = data,\n size = size,\n active = active\n )\n}\n\n#' @export\nggfree.uneval <- function(data = waiver(), ...) {\n cli_abort(c(\n \"{.arg data} cannot be {.obj_type_friendly {data}}\",\n \"i\" = \"Have you misspelled the {.arg data} argument in {.fn ggalign}\"\n ))\n}\n\n#' @export\nggfree.ggplot <- function(data = waiver(), ..., size = NULL, active = NULL) {\n rlang::check_dots_empty()\n plot <- data\n # In ggplot2, `waiver()` was regard to no data\n data <- plot$data %|w|% NULL\n plot <- gguse_data(plot, waiver())\n new_free_gg(plot, data, size = size, active = active)\n}\n\nnew_free_gg <- function(plot, data, size, active,\n call = caller_call()) {\n assert_active(active, allow_null = TRUE, call = call)\n active <- update_active(active, new_active(use = TRUE))\n new_craftbox(\n FreeGg,\n # new field for FreeGg\n input_data = data,\n # slots for the plot\n plot = plot,\n size = size,\n active = active,\n schemes = default_schemes(data),\n call = call\n )\n}\n\n#' @importFrom ggplot2 ggproto\nFreeGg <- ggproto(\"FreeGg\", Craftsman,\n free_facet = TRUE,\n free_limits = TRUE,\n interact_layout = function(self, layout) {\n layout_data <- layout@data\n if (is.waive(input_data <- self$input_data)) { # inherit from the layout\n data <- layout_data\n self$labels <- vec_names(layout_data)\n\n # for data inherit from the layout, and the design is for discrete\n # variable, we'll integrate the design into the plot data\n self$use_design <- is_stack_layout(layout)\n\n # if the layout data is from the quad-layout, we use the discrete\n # `design`\n self$use_extra_design <- is_stack_layout(layout) &&\n isTRUE(layout@heatmap$quad_matrix)\n } else if (is.function(input_data)) {\n if (is.null(layout_data)) {\n cli_abort(c(\n sprintf(\n \"{.arg data} in %s cannot be a function\",\n object_name(self)\n ),\n i = sprintf(\"no data was found in %s\", self$layout_name)\n ))\n }\n data <- input_data(layout_data)\n } else {\n data <- input_data\n }\n self$data <- ggalign_data_restore(\n fortify_data_frame(data, call = self$call), layout_data\n )\n layout\n },\n build_plot = function(self, plot, design, extra_design = NULL,\n previous_design = NULL) {\n if (is.function(data <- self$data)) {\n data <- NULL\n }\n if (is.null(data)) {\n return(gguse_data(plot, data))\n }\n if (isTRUE(self$use_extra_design) &&\n is_discrete_design(extra_design) &&\n !is.null(.subset2(extra_design, \"nobs\"))) {\n extra_plot_data <- data_frame0(\n .extra_panel = .subset2(extra_design, \"panel\"),\n .extra_index = .subset2(extra_design, \"index\")\n )\n } else {\n extra_plot_data <- NULL\n }\n\n # if inherit from the parent layout\n if (isTRUE(self$use_design) &&\n is_discrete_design(design) &&\n !is.null(.subset2(design, \"nobs\"))) {\n plot_data <- data_frame0(\n .panel = .subset2(design, \"panel\"),\n .index = .subset2(design, \"index\"),\n .names = .subset(self$labels, .subset2(design, \"index\"))\n )\n if (!is.null(extra_plot_data)) {\n plot_data <- cross_join(plot_data, extra_plot_data)\n data <- full_join(data, plot_data,\n by.x = c(\".column_index\", \".row_index\"),\n by.y = c(\".extra_index\", \".index\")\n )\n } else {\n data <- full_join(data, plot_data,\n by.x = \".row_index\", by.y = \".index\"\n )\n }\n } else if (!is.null(extra_plot_data)) {\n data <- full_join(data, extra_plot_data,\n by.x = \".column_index\", by.y = \".extra_index\"\n )\n }\n gguse_data(plot, data)\n },\n summary = function(self, plot) {\n header <- ggproto_parent(Craftsman, self)$summary(plot)\n c(header, \" Add plot without alignment\")\n }\n)\n"], ["/ggalign/R/craft-align-.R", "#' Create a New `CraftBox` Object with `CraftAlign` craftsman\n#'\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' An `CraftAlign` object interacts with the `Layout` object to reorder or split\n#' observations and, in some cases, add plot components to the `Layout`.\n#'\n#' @param align An `CraftAlign` object.\n#' @param ... Additional fields passed to the `align` object.\n#' @param plot A ggplot object.\n#' @inheritParams ggalign\n#' @param schemes Options for `schemes`:\n#' - `NULL`: Used when `align` do not add a plot.\n#' - [`waiver()`][ggplot2::waiver]: Try to infer `schemes` based on `data`.\n#' @param call The `call` used to construct the `align` object, for\n#' reporting messages.\n#'\n#' @section Discrete Axis Alignment:\n#' It is important to note that we consider rows as observations, meaning\n#' `vec_size(data)`/`NROW(data)` must match the number of observations along the\n#' axis used for alignment (x-axis for a vertical stack layout, y-axis for a\n#' horizontal stack layout).\n#'\n#' @return A new `CraftBox` object.\n#' @examples\n#' align_dendro()\n#' @importFrom rlang caller_call current_call\n#' @importFrom ggplot2 ggproto\n#' @export\n#' @keywords internal\nalign <- function(align, data = NULL, ..., plot = NULL,\n size = NULL, schemes = NULL, no_axes = NULL,\n active = NULL, call = caller_call()) {\n if (override_call(call)) {\n call <- current_call()\n }\n\n # check arguments ---------------------------------------------\n data <- allow_lambda(data)\n no_axes <- no_axes %||%\n getOption(sprintf(\"%s.align_no_axes\", pkg_nm()), default = TRUE)\n schemes <- schemes %|w|% default_schemes(data)\n\n new_craftbox(\n craftsman = align,\n\n # additional field for `align` object\n no_axes = no_axes,\n ...,\n\n # Following fields will be initialzed when added into the layout\n # and will be saved and accessed across the plot rendering process\n direction = NULL,\n position = NULL,\n data = NULL, # Used to save the modified `input_data`\n statistics = NULL, # `$compute` method\n labels = NULL, # the original `vec_names()` of the `input_data`\n\n # the input data\n input_data = data,\n\n # object slots\n plot = plot,\n active = active,\n size = size,\n schemes = schemes,\n\n # call\n call = call\n )\n}\n\n#' @details\n#' Each of the `Align*` objects is just a [`ggproto()`][ggplot2::ggproto]\n#' object, descended from the top-level `CraftAlign`, and each implements\n#' various methods and fields.\n#'\n#' To create a new type of `Align*` object, you typically will want to\n#' override one or more of the following:\n#' - `setup_params`: Prepare parameter or check parameters used by this plot.\n#' - `setup_data`: Prepare data used by this plot.\n#' - `compute`: A method used to compute statistics.\n#' - `align`: A method used to group observations into panel or reorder\n#' observations.\n#' - `draw`: A method used to draw the plot. Must return a `ggplot` object.\n#' @importFrom ggplot2 ggproto\n#' @export\n#' @format NULL\n#' @usage NULL\n#' @rdname align\n#' @include craftbox-.R\nCraftAlign <- ggproto(\"CraftAlign\", Craftsman,\n interact_layout = function(self, layout) {\n # check plot is compatible with the layout\n if (is_layout_continuous(layout)) {\n layout_name <- self$layout_name\n # `CraftAlign` object is special for discrete variables\n cli_abort(c(\n sprintf(\"Cannot add %s to %s\", object_name(self), layout_name),\n i = sprintf(\"%s cannot align discrete variables\", layout_name)\n ))\n }\n layout\n },\n setup_design = function(self, design) {\n old_panel <- .subset2(design, \"panel\")\n old_index <- .subset2(design, \"index\")\n # prepare the data -------------------------------\n # compute statistics ---------------------------------\n self$statistics <- self$compute(panel = old_panel, index = old_index)\n\n # make the new layout -------------------------------\n panel_and_index <- self$align(panel = old_panel, index = old_index)\n\n # check panel\n layout_name <- self$layout_name\n nobs <- .subset2(design, \"nobs\")\n new_panel <- .subset2(panel_and_index, 1L)\n if (!is.null(new_panel)) {\n if (!is.atomic(new_panel)) {\n cli_abort(c(\n sprintf(\n \"invalid layout panels defined by %s\",\n object_name(self)\n ),\n i = \"layout panels must be an atomic vector\"\n ))\n } else if (anyNA(new_panel)) {\n cli_abort(sprintf(\n \"layout panels defined by %s contain `NA`\",\n object_name(self)\n ))\n } else if (is.null(nobs)) {\n # we have defined panel, but don't define the `nobs`\n cli_abort(sprintf(\n \"%s defined the panels but not define {.field nobs}\", object_name(self)\n ))\n } else if (length(new_panel) != nobs) {\n # we have defined panel, but don't define the `nobs`\n cli_abort(sprintf(\n \"layout panels defined by %s (nobs: %d) is not compatible with the nobs: %d\",\n object_name(self), length(new_panel), nobs\n ))\n } else if (!is.null(old_panel) && !(new_panel %nest% old_panel)) {\n cli_abort(sprintf(\n \"%s disrupt the previously established panel groups of %s\",\n object_name(self), layout_name\n ))\n }\n } else if (!is.null(old_panel)) {\n # push developer to reset the panel in the layout\n cli_abort(c(\n sprintf(\"invalid %s\", object_name(self)),\n i = sprintf(\n \"%s reset the {.field panel}, but don't change the {.field panel} of the layout\", object_name(self)\n )\n ))\n }\n panel <- new_panel\n if (!is.null(panel) && !is.factor(panel)) panel <- factor(panel)\n\n # check index\n new_index <- .subset2(panel_and_index, 2L)\n if (!is.null(new_index)) {\n if (!is.integer(new_index)) {\n cli_abort(c(\n sprintf(\n \"invalid layout ordering index defined by %s\", object_name(self)\n ),\n i = \"layout ordering index must be an integer\"\n ))\n } else if (anyNA(new_index)) {\n cli_abort(sprintf(\n \"layout ordering index defined by %s contain `NA`\",\n object_name(self)\n ))\n } else if (is.null(nobs)) {\n # we have defined panel, but don't define the `nobs`\n cli_abort(sprintf(\n \"%s defined the ordering index but not define nobs\", object_name(self)\n ))\n } else if (length(new_index) != nobs) {\n # we have defined index, but don't define the `nobs`\n cli_abort(sprintf(\n \"layout ordering index defined by %s (nobs: %d) is not compatible with the nobs (%d)\",\n object_name(self), length(new_index), nobs\n ))\n }\n } else if (!is.null(old_index)) {\n # push developer to reset the `index` in the layout\n cli_abort(c(\n sprintf(\"invalid %s\", object_name(self)),\n i = sprintf(\n \"%s reset the {.field index}, but don't change the {.field index} of the layout\",\n object_name(self)\n )\n ))\n }\n index <- new_index\n\n # we always make the index following the panel\n if (!is.null(panel) && !is.null(index)) {\n index <- reorder_index(panel, index)\n }\n\n # we always prevent from reordering twice.\n if (!is.null(old_index) && !all(old_index == index)) {\n cli_abort(sprintf(\n \"%s disrupt the previously established ordering index of %s\",\n object_name(self), layout_name\n ))\n }\n discrete_design(panel, index, nobs)\n },\n\n # Following fields should be defined for the new `CraftAlign` object.\n # argument name in these function doesn't matter.\n compute = function(self, panel, index) NULL,\n\n # Group heamap row/column and reorder, Must return a list of 2:\n # - the first one should be the groups for heatmap row/column, the factor\n # levels will determine the panel order, so it should always follow the\n # index if you don't want the panel levels break the index. See\n # `AlignDendro` for example.\n # - the second one should be the heatmap row/column order index, and will\n # determine the order in each grouped panel.\n #\n # See `$setup_design()` method for details\n # There will have following situations (the input is old index and old\n # panel):\n #\n # 1. old index is NULL and old panel is NULL, there is nothing wrong to\n # define any new index or panel\n # 2. old index is `NULL` and old panel is not `NULL`, in this way, new\n # index must follow the old panel.\n #\n # For new `CraftAlign` object, which can do clustering, we must\n # abort, if it can not do sub-clustering, if it can do sub-clustering, we\n # should know if we want to change the order between the groups (panel\n # levels).\n #\n # Please check `AlignGroup` object and `CraftAlign` object\n # For dendrogram, it can do sub-clustering within each group, it also\n # allows reordering between groups (it provide `reorder_group` argument),\n # so the new panel levels may be not the same with old panel\n #\n # For `CraftAlign` object reordering the heatmap rows/columns.\n # usually we provide a `strict` argument, to allow reorder heatmap within\n # group only. See `AlignOrder2`.\n #\n # 3. old index is not `NULL`, no matter whether old panel is `NULL` or not,\n # in this way, we should always ensure the new index won't change the old\n # index, this will be checked in `$setup_design()` method.\n align = function(self, panel, index) list(panel, index),\n\n # let Craftsman to add schemes and theme acoordingly\n finish_plot = function(self, plot, schemes, theme) {\n ggproto_parent(AlignGg, self)$finish_plot(plot, schemes, theme)\n },\n summary = function(self, plot) {\n header <- ggproto_parent(Craftsman, self)$summary(plot)\n oo <- self$summary_align()\n nms <- c(\"plot\", \"reorder\", \"split\")\n content <- c(\n if (is.null(plot)) \"no\" else \"yes\",\n if (isTRUE(oo[1L])) \"yes\" else \"no\",\n if (isTRUE(oo[2L])) \"yes\" else \"no\"\n )\n nms <- format(nms, justify = \"right\")\n content <- format(content, justify = \"left\")\n content <- paste0(\" \", nms, \": \", content)\n c(header, content)\n },\n\n # Summary the action of `Align`\n #\n # @return A logical vector of length 2, indicating:\n # - Whether the object reorders the observations.\n # - Whether the object splits the observations into groups.\n # @keywords internal\n summary_align = function(self) c(FALSE, FALSE)\n)\n"], ["/ggalign/R/craft-align-phylo.R", "#' Plot Phylogenetics tree\n#'\n#' @param phylo A [`phylo`][ape::as.phylo] object.\n#' @param ... <[dyn-dots][rlang::dyn-dots]> Additional arguments passed to\n#' [`geom_segment()`][ggplot2::geom_segment].\n#' @param ladderize A single string of `r oxford_or(c(\"left\", \"right\"))`,\n#' indicating whether to ladderize the tree. Ladderizing arranges the tree so\n#' that the smallest clade is positioned on the `\"right\"` or the `\"left\"`. By\n#' default, `NULL` means the tree will not be ladderized.\n#' @inheritParams fortify_data_frame.phylo\n#' @inheritParams ggalign\n#' @export\nalign_phylo <- function(phylo, ..., ladderize = NULL, type = \"rectangle\",\n center = FALSE, tree_type = NULL,\n no_axes = NULL, active = NULL,\n size = NULL) {\n if (!is.null(ladderize)) {\n ladderize <- arg_match0(ladderize, c(\"left\", \"right\"))\n rlang::check_installed(\"ape\", \"to ladderize phylogenetics tree\")\n }\n assert_s3_class(phylo, \"phylo\")\n assert_active(active)\n active <- update_active(active, new_active(use = TRUE))\n align(\n align = AlignPhylo,\n phylo = phylo,\n ladderize = ladderize,\n no_axes = no_axes,\n plot = ggplot() +\n ggplot2::geom_segment(\n mapping = aes(\n x = .data$x, y = .data$y,\n xend = .data$xend, yend = .data$yend\n ),\n ...,\n stat = \"identity\",\n data = function(data) ggalign_attr(data, \"edge\")\n ),\n data_params = list(type = type, center = center, tree_type = tree_type),\n active = active,\n size = size\n )\n}\n\nAlignPhylo <- ggproto(\"AlignPhylo\", CraftAlign,\n interact_layout = function(self, layout) {\n layout <- ggproto_parent(CraftAlign, self)$interact_layout(layout)\n\n # we keep the names from the layout data for usage\n tip_labels <- self$phylo$tip.label\n if (is.null(tip_labels)) {\n cli_abort(\n \"{.arg phylo} must have tip labels to match the layout data\",\n call = self$call\n )\n } else if (vec_duplicate_any(tip_labels)) {\n cli_abort(\n \"{.arg phylo} cannot have duplicated tip labels\",\n call = self$call\n )\n }\n\n # we ensure the layout data has names to match the phylo tree\n if (is.null(layout_labels <- vec_names(layout@data))) {\n cli_abort(c(\n sprintf(\n \"Cannot add %s to %s\", object_name(self),\n self$layout_name\n ),\n i = sprintf(\n \"%s has no labels (rownames) to match {.arg phylo}\",\n self$layout_name\n )\n ))\n } else if (vec_duplicate_any(layout_labels)) {\n cli_abort(c(\n sprintf(\n \"Cannot add %s to %s\", object_name(self),\n self$layout_name\n ),\n i = sprintf(\"%s has duplicated labels\", self$layout_name)\n ))\n }\n assert_mismatch_nobs(\n self, .subset2(layout@design, \"nobs\"), vec_size(tip_labels),\n arg = \"phylo\"\n )\n\n # we keep the names from the layout data for usage\n self$labels <- layout_labels\n layout\n },\n compute = function(self, panel, index) {\n phylo <- self$phylo\n # R CMD check won't give error even we don't add `ape` to the dependency\n if (!is.null(self$ladderize)) {\n phylo <- ape::ladderize(phylo,\n right = identical(self$ladderize, \"right\")\n )\n }\n inject(fortify_data_frame.phylo(\n data = phylo, !!!self$data_params,\n data_arg = \"phylo\", call = self$call\n ))\n },\n align = function(self, panel, index) {\n data <- self$statistics\n tip <- vec_slice(data, .subset2(data, \"tip\"))\n ordered <- .subset2(tip, \"label\")[order(.subset2(tip, \"x\"))]\n index <- match(ordered, self$labels)\n if (!is.null(panel) && nlevels(panel) > 1L &&\n !all(index == reorder_index(panel, index))) {\n layout_name <- self$layout_name\n object_name <- object_name(self)\n cli_abort(c(\n sprintf(\"Cannot add %s to %s\", object_name, layout_name),\n i = sprintf(\n \"Group of %s will disrupt the ordering index of %s\", layout_name, object_name\n )\n ), call = self$call)\n }\n list(panel, index)\n },\n setup_plot = function(self, plot) {\n ggadd_default(plot, aes(x = .data$x, y = .data$y)) + switch_direction(\n self$direction,\n ggplot2::labs(x = \"timing\"),\n ggplot2::labs(y = \"timing\")\n )\n },\n build_plot = function(self, plot, design, extra_design = NULL,\n previous_design = NULL) {\n if (!is.null(panel <- .subset2(design, \"panel\")) &&\n nlevels(panel) > 1L) {\n layout_name <- self$layout_name\n object_name <- object_name(self)\n cli_abort(c(\n sprintf(\"Cannot add %s to %s\", object_name, layout_name),\n i = sprintf(\"%s cannot span multiple panels\", object_name)\n ))\n }\n\n data <- self$statistics\n edge <- ggalign_attr(data, \"edge\")\n node <- data\n node$.panel <- unique(panel)\n edge$.panel <- unique(panel)\n\n # add names\n if (!is.null(node$label)) {\n node$.names <- node$label\n }\n if (!is.null(edge$label)) {\n edge$.names <- edge$label\n }\n if (is_horizontal(self$direction)) {\n edge <- rename(\n edge,\n c(x = \"y\", xend = \"yend\", y = \"x\", yend = \"xend\")\n )\n node <- rename(node, c(x = \"y\", y = \"x\"))\n }\n plot <- gguse_data(plot, ggalign_data_set(node, edge = edge))\n position <- self$position\n if (!self$in_linear || # for circular layout\n # for top annotation, reverse y-axis\n (!is.null(position) && position == \"top\")) {\n plot <- reverse_continuous_axis(plot, \"y\")\n } else if (!is.null(position) && position == \"right\") {\n # for right annotation, reverse x-axis\n plot <- reverse_continuous_axis(plot, \"x\")\n }\n\n # always turn off clip, this is what dendrogram dependends on\n old_coord <- plot$coordinates\n if (!identical(old_coord$clip, \"off\")) {\n # to prevent from changing the input of user.\n plot$coordinates <- ggproto(NULL, old_coord, clip = \"off\")\n }\n plot\n },\n summary_align = function(self) c(TRUE, FALSE)\n)\n\n#' Build a matrix from `phylo` object\n#'\n#' @description This method allows a [`phylo`][ape::as.phylo] object to be\n#' directly input into `stack_discrete()` or `circle_discrete()`. This makes it\n#' possible to add [`align_phylo()`] to the stack independently, as\n#' [`align_phylo()`] requires the layout to have labels.\n#' @inheritParams rlang::args_dots_empty\n#' @param data A [`phylo`][ape::as.phylo] object.\n#' @inheritParams fortify_matrix\n#' @return A one-column matrix where the tip labels are the values, and the row\n#' names will also be the tip labels.\n#' @family fortify_matrix\n#' @export\nfortify_matrix.phylo <- function(data, ..., data_arg = caller_arg(data),\n call = NULL) {\n call <- call %||% current_call()\n rlang::check_dots_empty(call = call)\n if (is.null(labels <- data$tip.label)) {\n cli_abort(\n \"{.arg {data_arg}} must have tip labels to match the layout data\",\n call = call\n )\n }\n as.matrix(vec_set_names(labels, labels))\n}\n\n#' @inherit fortify_data_frame.default title description\n#' @inheritParams rlang::args_dots_empty\n#' @inheritParams fortify_data_frame.dendrogram\n#' @param tree_type A single string, one of\n#' `r oxford_or(c(\"phylogram\", \"cladogram\"))`, indicating the type of tree.\n#' - `phylogram`: Represents a phylogenetic tree where branch lengths indicate\n#' evolutionary distance or time.\n#' - `cladogram`: Represents a tree where branch lengths are not used, or the\n#' branches do not reflect evolutionary time.\n#'\n#' Usually, you don't need to modify this.\n#'\n#' @param tip_pos The x-coordinates of the tip. Must be the same length\n#' of the number of tips in `tree`.\n#' @return A `data frame` with the node coordinates:\n#' - `.index`: the original index in the tree for the the tip/node.\n#' - `label`: the tip/node label text.\n#' - `x` and `y`: x-axis and y-axis coordinates for the tip/node.\n#' - `tip`: A logical value indicates whether current node is a tip.\n#' @section ggalign attributes:\n#' `edge`: A `data frame` for edge coordinates:\n#'\n#' - `x` and `y`: x-axis and y-axis coordinates for the start node of the edge.\n#' - `xend` and `yend`: the x-axis and y-axis coordinates of the terminal node\n#' for edge.\n#' @family fortify_data_frame\n#' @export\nfortify_data_frame.phylo <- function(data, ..., type = \"rectangle\",\n center = FALSE,\n tree_type = NULL, tip_pos = NULL,\n data_arg = NULL, call = NULL) {\n call <- call %||% current_call()\n data_arg <- data_arg %||% \"data\"\n rlang::check_dots_empty(call = call)\n type <- arg_match0(type, c(\"rectangle\", \"triangle\"))\n rectangle <- type == \"rectangle\"\n edge <- data$edge\n edge_lengths <- data$edge.length\n if (!is.null(tree_type)) {\n tree_type <- arg_match0(tree_type,\n c(\"phylogram\", \"cladogram\"),\n error_call = call\n )\n if (tree_type == \"phylogram\" && is.null(edge_lengths)) {\n cli_warn(c(\n \"Cannot use {.code tree_type = 'phylogram'}\",\n \"No branch length found in {.arg {data_arg}}\"\n ))\n tree_type <- \"cladogram\"\n }\n }\n if (identical(tree_type, \"cladogram\")) {\n edge_lengths <- NULL\n }\n parent <- edge[, 1L, drop = TRUE]\n child <- edge[, 2L, drop = TRUE]\n tip_labels <- data$tip.label\n node_labels <- data$node.label\n N <- length(tip_labels)\n if (is.null(tip_pos)) {\n tip_pos <- seq_len(N)\n } else if (length(tip_pos) != N) {\n cli_abort(\n \"{.arg tip_pos} must have the same length as the number of tips in {.arg {data_arg}}\",\n call = call\n )\n }\n i <- 0L # tip index\n phylo_data <- function(index, level, timing) {\n if (any(select <- parent == index)) {\n # recursively for each child\n data <- list(index = child[select])\n # if we have edge length, timing should be available\n if (!is.null(edge_lengths)) {\n data <- c(data, list(timing = timing + edge_lengths[select]))\n }\n data <- list_transpose(.mapply(\n function(index, timing = NULL) {\n phylo_data(index, level = level + 1L, timing = timing)\n },\n data, NULL\n ))\n\n # integrate the data for each child\n node <- vec_rbind(!!!.subset2(data, \"node\"))\n edge <- vec_rbind(!!!.subset2(data, \"edge\"))\n\n # all coordinate for direct children nodes -------------\n direct_leaves_x <- unlist(\n .subset2(data, \"x\"),\n recursive = FALSE, use.names = FALSE\n )\n direct_leaves_y <- unlist(\n .subset2(data, \"y\"),\n recursive = FALSE, use.names = FALSE\n )\n\n # prepare node data ------------------------------------\n # all x coordinate for children nodes ------------------\n # used if center is `TRUE`, we'll calculate the center position\n # among all children nodes\n leaves <- vec_slice(node, .subset2(node, \"tip\")) # all leaves\n\n # x coordinate for current node: the midpoint\n if (center) {\n x <- sum(range(.subset2(leaves, \"x\"))) / 2L\n } else {\n x <- sum(range(direct_leaves_x)) / 2L\n }\n\n # y coordinate for current node\n if (is.null(edge_lengths) && is.null(timing)) {\n y <- min(direct_leaves_y) * level / (level + 1L)\n } else {\n y <- timing\n }\n\n # there is no node data for the root\n node <- vec_rbind(data_frame0(\n .index = index,\n label = node_labels[index - N],\n x = x, y = y, tip = FALSE\n ), node)\n\n # if it's the `rectangle`\n if (rectangle) {\n # vertical lines\n vertical_lines <- data_frame0(\n x = direct_leaves_x,\n xend = direct_leaves_x,\n y = y,\n yend = direct_leaves_y\n )\n added_edge <- vec_rbind(\n vertical_lines,\n # horizontal line\n data_frame0(\n x = x,\n xend = direct_leaves_x,\n y = y,\n yend = y\n )\n )\n } else {\n added_edge <- data_frame0(\n x = x,\n xend = direct_leaves_x,\n y = y,\n yend = direct_leaves_y\n )\n }\n if (is.null(edge)) {\n edge <- added_edge\n } else {\n edge <- vec_rbind(added_edge, edge)\n }\n list(node = node, edge = edge, x = x, y = y)\n } else if (any(select <- child == index)) { # for the tip\n i <<- i + 1L\n x <- tip_pos[i]\n if (is.null(edge_lengths)) {\n y <- 1L\n } else {\n y <- timing\n }\n\n list(\n node = data_frame0(\n .index = index,\n label = tip_labels[index],\n x = x,\n y = y,\n tip = TRUE\n ),\n edge = NULL,\n x = x, y = y\n )\n } else {\n cli_abort(\"Invalid {.cls phylo} provided in {.arg {data_arg}}\",\n call = call\n )\n }\n }\n\n # from ape::is.rooted, this should be the most ancester\n ans <- phylo_data(N + 1L, 0L, timing = 0)\n ggalign_data_set(.subset2(ans, \"node\"), edge = .subset2(ans, \"edge\"))\n}\n"], ["/ggalign/R/craft-cross-link.R", "#' Add a plot to connect selected observations\n#'\n#' @param link A [`link_draw()`] object that defines how to draw the links,\n#' such as [`link_line()`].\n#' @param on_top A boolean value indicating whether to draw the link on top of\n#' the plot panel (`TRUE`) or below (`FALSE`).\n#' @inheritParams cross_none\n#' @inheritParams ggmark\n#'\n#' @section ggplot2 Specification:\n#' The `cross_link` function initializes a `ggplot` object but does not\n#' initialize any data. Using [`scheme_data()`] to change the internal data if\n#' needed.\n#'\n#' @export\ncross_link <- function(link, data = waiver(), ...,\n on_top = TRUE, obs_size = 1,\n inherit_index = NULL, inherit_panel = NULL,\n inherit_nobs = NULL,\n size = NULL, active = NULL) {\n if (!inherits(link, \"ggalign_link_draw\")) {\n cli_abort(\"{.arg link} must be a {.fn link_draw} object\")\n }\n assert_obs_size(obs_size)\n assert_active(active)\n active <- update_active(active, new_active(use = TRUE))\n cross(CrossLink,\n data = data, data_params = list2(...),\n link = link, obs_size = obs_size,\n plot = ggplot(), size = size,\n schemes = default_schemes(),\n active = active,\n on_top = on_top,\n inherit_nobs = inherit_nobs,\n inherit_panel = inherit_panel,\n inherit_index = inherit_index\n )\n}\n\n#' @importFrom ggplot2 ggproto ggproto_parent\n#' @importFrom grid gTree\n#' @include craft-cross-.R\nCrossLink <- ggproto(\"CrossLink\", CraftCross,\n interact_layout = function(self, layout) {\n if (!self$in_linear) { # only used for linear coordinate\n cli_abort(c(\n sprintf(\n \"Cannot add %s to %s\",\n object_name(self), layout_name\n ),\n i = sprintf(\n \"%s can only be used in linear layout\",\n object_name(self)\n )\n ))\n }\n ggproto_parent(CraftCross, self)$interact_layout(layout)\n },\n build_plot = function(self, plot, design, extra_design = NULL,\n previous_design = NULL) {\n if (is.null(.subset2(previous_design, \"nobs\"))) {\n cli_abort(\n sprintf(\n \"layout {.field nobs} for %s before %s is not initialized \",\n self$layout_name, object_name(self)\n )\n )\n }\n if (is.null(.subset2(design, \"nobs\"))) {\n cli_abort(\n sprintf(\n \"layout {.field nobs} for %s after %s is not initialized \",\n self$layout_name, object_name(self)\n )\n )\n }\n\n direction <- self$direction\n position <- self$position\n\n # parse links --------------------------------------------\n link <- self$link\n design1 <- previous_design\n design2 <- design\n full_data1 <- split(\n seq_len(.subset2(design1, \"nobs\")),\n .subset2(design1, \"panel\")\n )\n full_data2 <- split(\n seq_len(.subset2(design2, \"nobs\")),\n .subset2(design2, \"panel\")\n )\n links <- .subset2(link, \"links\")\n # set default links for link_line()\n if (is_empty(links) &&\n inherits(link, \"ggalign_link_line\") &&\n identical(.subset2(design1, \"nobs\"), .subset2(design2, \"nobs\"))) {\n links <- lapply(seq_len(.subset2(design1, \"nobs\")), function(i) {\n rlang::new_formula(i, i)\n })\n links <- pair_links(!!!links)\n }\n link_index <- make_links_data(\n links,\n design1 = design1, design2 = design2,\n labels1 = self$labels0, labels2 = self$labels\n )\n data_index <- lapply(link_index, function(index) {\n if (is.null(index)) {\n return(NULL)\n }\n hand1 <- .subset2(index, \"hand1\")\n hand2 <- .subset2(index, \"hand2\")\n list(\n hand1 = .subset2(design1, \"index\")[hand1],\n hand2 = .subset2(design2, \"index\")[hand2]\n )\n })\n plot$ggalign_link_data <- list(\n full_data1 = full_data1,\n full_data2 = full_data2,\n link_index = link_index,\n data_index = data_index,\n direction = direction,\n draw = .subset2(link, \"draw\"),\n obs_size = self$obs_size\n )\n plot\n },\n finish_plot = function(self, plot, schemes, theme) {\n plot <- plot_add_schemes(plot, schemes)\n\n # save spacing for usage\n spacing <- calc_element(\n switch_direction(\n self$direction,\n \"panel.spacing.y\",\n \"panel.spacing.x\"\n ),\n theme\n ) %||% unit(0, \"mm\")\n\n # setup the grob\n grob <- inject(gTree(\n !!!plot$ggalign_link_data,\n spacing1 = spacing,\n spacing2 = spacing,\n cl = \"ggalignLinkTree\"\n ))\n plot$ggalign_link_data <- NULL\n\n # insert the grob\n plot <- plot + inset(grob, on_top = self$on_top)\n ggremove_margin(plot, self$direction) + theme_recycle()\n },\n summary = function(self, plot) {\n header <- ggproto_parent(CraftCross, self)$summary(plot)\n c(header, \" Add plot to connect selected observations\")\n }\n)\n"], ["/ggalign/R/craft-align-dendrogram.R", "#' Plot dendrogram tree\n#'\n#' @param ... <[dyn-dots][rlang::dyn-dots]> Additional arguments passed to\n#' [`geom_segment()`][ggplot2::geom_segment].\n#' @param plot_dendrogram A boolean value indicates whether plot the dendrogram\n#' tree.\n#' @param plot_cut_height A boolean value indicates whether plot the cut height.\n#' @section ggplot2 specification:\n#' `align_dendro` initializes a ggplot `data` and `mapping`.\n#'\n#' The internal `ggplot` object will always use a default mapping of\n#' `aes(x = .data$x, y = .data$y)`.\n#'\n#' The default ggplot data is the `node` coordinates with `edge` data attached\n#' in [`ggalign`][ggalign_attr()] attribute, in addition, a\n#' [`geom_segment`][ggplot2::geom_segment] layer with a data frame of the `edge`\n#' coordinates will be added when `plot_dendrogram = TRUE`.\n#'\n#' See [`fortify_data_frame.dendrogram()`] for details.\n#' @param merge_dendrogram A single boolean value, indicates whether we should\n#' merge multiple dendrograms, only used when previous groups have been\n#' established. Default: `FALSE`.\n#' @inheritParams align_hclust\n#' @inheritParams fortify_data_frame.dendrogram\n#' @inheritParams ggalign\n#' @inheritSection align Discrete Axis Alignment\n#' @examples\n#' # align_dendro will always add a plot area\n#' ggheatmap(matrix(rnorm(81), nrow = 9)) +\n#' anno_top() +\n#' align_dendro()\n#' ggheatmap(matrix(rnorm(81), nrow = 9)) +\n#' anno_top() +\n#' align_dendro(k = 3L)\n#'\n#' @importFrom ggplot2 aes\n#' @importFrom rlang list2\n#' @export\nalign_dendro <- function(mapping = aes(), ...,\n distance = \"euclidean\",\n method = \"complete\",\n use_missing = \"pairwise.complete.obs\",\n reorder_dendrogram = FALSE,\n merge_dendrogram = FALSE,\n reorder_group = FALSE,\n k = NULL, h = NULL, cutree = NULL,\n plot_dendrogram = TRUE,\n plot_cut_height = NULL, root = NULL,\n center = FALSE, type = \"rectangle\",\n size = NULL, data = NULL,\n no_axes = NULL, active = NULL) {\n assert_bool(plot_cut_height, allow_null = TRUE)\n assert_bool(merge_dendrogram)\n\n # setup the default value for `plot_cut_height`\n plot_cut_height <- plot_cut_height %||% (\n # we by default don't draw the height of the user-provided cutree\n # since function like `dynamicTreeCut` will merge tree\n (!is.null(k) || !is.null(h)) && is.null(cutree)\n )\n plot <- ggplot(mapping = mapping)\n if (plot_dendrogram) {\n plot <- plot + ggplot2::geom_segment(\n mapping = aes(\n x = .data$x, y = .data$y,\n xend = .data$xend, yend = .data$yend\n ),\n ...,\n stat = \"identity\",\n data = function(data) ggalign_attr(data, \"edge\")\n )\n }\n assert_active(active)\n active <- update_active(active, new_active(use = TRUE))\n .align_hclust(\n align = AlignDendro,\n distance = distance,\n method = method,\n use_missing = use_missing,\n merge_dendro = merge_dendrogram,\n plot_cut_height = plot_cut_height,\n type = type, root = root, center = center,\n reorder_dendrogram = reorder_dendrogram,\n reorder_group = reorder_group,\n schemes = default_schemes(th = theme_no_strip()),\n k = k, h = h, cutree = cutree, data = data, active = active,\n size = size, no_axes = no_axes, plot = plot\n )\n}\n\n#' @importFrom ggplot2 aes ggplot\n#' @importFrom rlang inject\n#' @include craft-align-hclust.R\nAlignDendro <- ggproto(\"AlignDendro\", AlignHclust,\n setup_plot = function(self, plot) {\n ggadd_default(plot, aes(x = .data$x, y = .data$y)) + switch_direction(\n self$direction,\n ggplot2::labs(x = \"height\"),\n ggplot2::labs(y = \"height\")\n )\n },\n build_plot = function(self, plot, design, extra_design = NULL,\n previous_design = NULL) {\n plot_cut_height <- self$plot_cut_height\n center <- self$center\n type <- self$type\n root <- self$root\n panel <- .subset2(design, \"panel\")\n index <- .subset2(design, \"index\")\n\n statistics <- .subset2(self, \"statistics\")\n direction <- self$direction\n priority <- switch_direction(direction, \"left\", \"right\")\n dendrogram_panel <- self$panel[index]\n if (!is.null(dendrogram_panel) &&\n # we allow to change the panel level name, but we prevent\n # from changing the underlying factor level (the underlying\n # ordering)\n !all(as.integer(dendrogram_panel) == as.integer(panel))) {\n cli_abort(\"you cannot do sub-splitting in dendrogram groups\")\n }\n\n if (self$multiple_tree) {\n branches <- levels(panel)\n data <- vector(\"list\", length(statistics))\n start <- 0L\n for (i in seq_along(data)) {\n tree <- .subset2(statistics, i)\n n <- stats::nobs(tree)\n end <- start + n\n data[[i]] <- fortify_data_frame(\n tree,\n priority = priority,\n center = center,\n type = type,\n leaf_pos = seq(start + 1L, end),\n leaf_braches = rep_len(.subset(branches, i), n),\n reorder_branches = FALSE,\n root = root,\n double = TRUE,\n call = self$call\n )\n start <- end\n }\n data <- lapply(\n list(\n node = data,\n edge = lapply(data, ggalign_attr, \"edge\")\n ),\n function(dat) {\n ans <- vec_rbind(!!!dat, .names_to = \"parent\")\n ans$.panel <- factor(.subset2(ans, \".panel\"), branches)\n ans\n }\n )\n edge <- .subset2(data, \"edge\")\n node <- .subset2(data, \"node\")\n } else {\n if (nlevels(panel) > 1L && type == \"triangle\" && self$in_linear) {\n cli_warn(c(paste(\n \"{.arg type} of {.arg triangle}\",\n \"is not well support for facet dendrogram\"\n ), i = \"will use {.filed rectangle} dendrogram instead\"))\n type <- \"rectangle\"\n }\n data <- fortify_data_frame(\n statistics,\n priority = priority,\n center = center,\n type = type,\n leaf_braches = as.character(panel),\n # panel has been reordered by the dendrogram index\n reorder_branches = FALSE,\n root = root,\n double = TRUE,\n call = self$call\n )\n edge <- ggalign_attr(data, \"edge\")\n node <- data\n }\n\n # add names\n if (!is.null(self$labels)) {\n node$.names <- .subset(self$labels, .subset2(node, \".index\"))\n }\n if (is_horizontal(direction)) {\n edge <- rename(\n edge,\n c(x = \"y\", xend = \"yend\", y = \"x\", yend = \"xend\")\n )\n node <- rename(node, c(x = \"y\", y = \"x\"))\n }\n\n # we do some tricks, since ggplot2 won't remove the attributes\n # we attach the `edge` data\n plot <- gguse_data(plot, ggalign_data_set(node, edge = edge))\n\n if (plot_cut_height && !is.null(height <- .subset2(self, \"height\"))) {\n plot <- plot +\n switch_direction(\n direction,\n ggplot2::geom_vline(\n xintercept = height, linetype = \"dashed\"\n ),\n ggplot2::geom_hline(\n yintercept = height, linetype = \"dashed\"\n )\n )\n }\n position <- .subset2(self, \"position\")\n if (!self$in_linear || # for circular layout\n # for bottom annotation, reverse y-axis\n (!is.null(position) && position == \"bottom\")) {\n plot <- reverse_continuous_axis(plot, \"y\")\n } else if (!is.null(position) && position == \"left\") {\n # for left annotation, reverse x-axis\n plot <- reverse_continuous_axis(plot, \"x\")\n }\n\n # always turn off clip, this is what dendrogram dependends on\n old_coord <- plot$coordinates\n if (!identical(old_coord$clip, \"off\")) {\n # to prevent from changing the input of user.\n plot$coordinates <- ggproto(NULL, old_coord, clip = \"off\")\n }\n plot\n }\n)\n\ntree_one_node <- function(index, label) {\n structure(\n index,\n class = \"dendrogram\",\n leaf = TRUE,\n height = 0,\n label = label,\n members = 1L\n )\n}\n\n# this function won't set the right `midpoint`, but `dendrogram_data` function\n# won't use it, so, it has no hurt to use.\nmerge_dendrogram <- function(parent, children) {\n if (is.null(parent)) { # if no parent, call the merge function from `stats`\n return(Reduce(function(x, y) {\n merge(x, y, adjust = \"none\")\n }, children))\n }\n children_heights <- vapply(\n children, attr, numeric(1L), \"height\",\n USE.NAMES = FALSE\n )\n parent_branch_heights <- tree_branch_heights(parent)\n cutoff_height <- max(children_heights) + min(parent_branch_heights) * 0.5\n .merge_dendrogram <- function(dend) {\n if (stats::is.leaf(dend)) { # base version, leaf should be the index\n .subset2(children, dend)\n } else { # for a branch, we should update the members, height\n attrs <- attributes(dend)\n # we recursively run for each node of current branch\n dend <- lapply(dend, .merge_dendrogram)\n heights <- vapply(dend, attr, numeric(1L), \"height\",\n USE.NAMES = FALSE\n )\n n_members <- vapply(dend, attr, integer(1L), \"members\",\n USE.NAMES = FALSE\n )\n # we update height and members\n attrs$height <- .subset2(attrs, \"height\") + max(heights)\n attrs$members <- sum(n_members)\n attributes(dend) <- attrs\n dend\n }\n }\n ans <- .merge_dendrogram(parent)\n attr(ans, \"cutoff_height\") <- cutoff_height\n ans\n}\n\n#' @importFrom stats reorder\nreorder_dendrogram <- function(dend, wts) {\n if (inherits(dend, \"hclust\")) dend <- stats::as.dendrogram(dend)\n reorder(x = dend, wts = wts, agglo.FUN = mean)\n}\n\ntree_branch_heights <- function(dend) {\n if (stats::is.leaf(dend)) {\n return(NULL)\n } else {\n c(\n attr(dend, \"height\"),\n unlist(lapply(dend, tree_branch_heights), FALSE, FALSE)\n )\n }\n}\n"], ["/ggalign/R/craft-cross-.R", "cross <- function(cross = NULL, data = waiver(),\n data_params = list(), ...,\n inherit_index = NULL,\n inherit_panel = NULL,\n inherit_nobs = NULL,\n plot = NULL, active = NULL, size = NULL, schemes = NULL,\n data_arg = caller_arg(data),\n call = caller_call()) {\n if (override_call(call)) {\n call <- current_call()\n }\n new_craftbox(\n craftsman = cross %||% CraftCross,\n data = allow_lambda(data), data_params = data_params,\n ...,\n inherit_nobs = inherit_nobs,\n inherit_panel = inherit_panel,\n inherit_index = inherit_index,\n plot = plot, active = active, size = size, schemes = schemes,\n data_arg = data_arg, call = call\n )\n}\n\n#' @importFrom ggplot2 ggproto ggproto_parent\n#' @include craftbox-.R\nCraftCross <- ggproto(\n \"CraftCross\", Craftsman,\n free_facet = TRUE,\n free_limits = TRUE,\n data_params = NULL,\n inherit_nobs = NULL,\n inherit_panel = NULL,\n inherit_index = NULL,\n interact_layout = function(self, layout) {\n # 1. check layout is `*_cross()`\n # 2. add `cross_points`\n # 3. add `odesign`\n # 4. define `labels`, we'll rename the `labels` to `labels0`\n layout <- ggproto_parent(CrossGg, self)$interact_layout(layout)\n\n # will define `labels0`\n self$labels0 <- self$labels\n\n # check the previous (between two `break_points`) define has been\n # initialized\n if (length(layout@break_points) &&\n is.null(.subset2(layout@design, \"nobs\"))) {\n cli_abort(sprintf(\n \"layout {.field nobs} for %s must be initialized before adding %s\",\n self$layout_name, object_name(self)\n ))\n }\n\n # setup data\n layout_data <- layout@data\n design <- layout@design\n\n if (is.waive(input_data <- self$data)) { # inherit from the layout\n data <- layout_data\n # `data` is NULL, `inherit_nobs` can be `TRUE` or `FALSE`, we by\n # default regard `inherit_nobs` as `TRUE`\n if (is.null(data) && isFALSE(self$inherit_nobs)) {\n design[\"nobs\"] <- list(NULL)\n }\n\n # `data` is not `NULL`, the `nobs` will always be the same with\n # previous design, nothing to do\n } else {\n if (is.function(input_data)) {\n if (is.null(layout_data)) {\n cli_abort(c(\n sprintf(\n \"{.arg data} in %s cannot be a function\",\n object_name(self)\n ),\n i = sprintf(\"no data was found in %s\", self$layout_name)\n ))\n }\n data <- input_data(layout_data)\n } else {\n data <- input_data\n }\n data <- inject(\n fortify_matrix(\n data, !!!self$data_params,\n data_arg = self$data_arg,\n call = self$call\n )\n ) %|w|% NULL\n if (isTRUE(self$inherit_nobs)) { # we require inherit nobs\n # we check if the data match original data dimention\n if (!is.null(data) &&\n !is.null(.subset2(design, \"nobs\")) &&\n NROW(data) != .subset2(design, \"nobs\")) {\n cli_abort(c(\n sprintf(\n \"%s (nobs: %d) is not compatible with the %s (nobs: %d)\",\n object_name(self), NROW(data), layout_name, layout_nobs\n ),\n i = \"try to set {.code inherit_nobs = FALSE}\"\n ))\n }\n } else { # for `FALSE` and `NULL`\n if (is.null(data)) {\n design[\"nobs\"] <- list(NULL)\n } else {\n if (NROW(data) == 0L) {\n cli_abort(\"{.arg data} cannot be empty\",\n call = self$call\n )\n }\n design[\"nobs\"] <- list(NROW(data))\n }\n }\n }\n\n # we keep the names from the layout data for usage\n self$labels <- vec_names(data)\n\n # determine if we should inherit panel\n # by default, `inherit_panel = FALSE`\n if (isTRUE(self$inherit_panel)) {\n if (is.null(self$labels0)) {\n cli_abort(c(\n \"Cannot inherit panel from the layout\",\n i = \"No labels found in the layout data\"\n ))\n }\n if (is.null(self$labels)) {\n cli_abort(c(\n \"Cannot inherit panel from the layout\",\n i = \"No labels found in the current {.arg data}\"\n ))\n }\n if (!all(self$labels %in% self$labels0)) {\n cli_abort(c(\n \"Cannot inherit panel from the layout\",\n i = \"Some labels in the current data are not found in the previous layout data\"\n ))\n }\n if (!is.null(panel <- .subset2(design, \"panel\"))) {\n design[\"panel\"] <- list(\n droplevels(panel[match(self$labels, self$labels0)])\n )\n }\n } else {\n design[\"panel\"] <- list(NULL)\n }\n\n # determine if we should inherit panel\n # by default, `inherit_index = FALSE`\n if (isTRUE(self$inherit_index)) {\n if (is.null(self$labels0)) {\n cli_abort(c(\n \"Cannot inherit ordering index from the layout\",\n i = \"No labels found in the previous layout data\"\n ))\n }\n\n if (is.null(self$labels)) {\n cli_abort(c(\n \"Cannot inherit ordering index from the layout\",\n i = \"No labels found in the current {.arg data}\"\n ))\n }\n\n if (!all(self$labels %in% self$labels0)) {\n cli_abort(c(\n \"Cannot inherit ordering index from the layout\",\n i = \"Some labels in the current data are not found in the previous layout data\"\n ))\n }\n\n if (!is.null(index <- .subset2(design, \"index\"))) {\n new_index <- order(match(\n self$labels,\n vec_slice(self$labels0, index)\n ))\n\n # we always make the index following the panel\n if (!is.null(panel <- .subset2(design, \"panel\"))) {\n new_index <- reorder_index(panel, new_index)\n }\n design[\"index\"] <- list(new_index)\n }\n } else {\n design[\"index\"] <- list(NULL)\n }\n\n # reset layout data\n layout@data <- data # don't restore the attribute\n\n # update the design\n layout@design <- design\n\n # udpate break_points\n layout@break_points <- c(layout@break_points, length(layout@plot_list))\n layout\n }\n)\n"], ["/ggalign/R/layout-quad-build.R", "#' @importFrom grid unit.c\n#' @export\nggalign_build.QuadLayout <- function(x) {\n x <- default_layout(x)\n patches <- quad_build(x)\n plots <- .subset2(patches, \"plots\")\n sizes <- .subset2(patches, \"sizes\")\n design <- list(\n top = area(1, 2),\n left = area(2, 1),\n main = area(2, 2),\n bottom = area(3, 2),\n right = area(2, 3)\n )\n sizes <- imap(list(\n height = c(\"top\", \"main\", \"bottom\"),\n width = c(\"left\", \"main\", \"right\")\n ), function(x, name) {\n out <- .subset(sizes, x)\n out$main <- .subset2(.subset2(out, \"main\"), name)\n out <- .subset(\n out,\n !vapply(.subset(plots, x), is.null, logical(1L), USE.NAMES = FALSE)\n )\n do.call(unit.c, out)\n })\n keep <- !vapply(plots, is.null, logical(1L), USE.NAMES = FALSE)\n design <- trim_area(vec_c(!!!vec_set_names(vec_slice(design, keep), NULL)))\n titles <- x@titles\n align_plots(\n !!!.subset(plots, keep),\n design = design,\n heights = .subset2(sizes, \"height\"),\n widths = .subset2(sizes, \"width\"),\n guides = .subset2(.subset2(x@schemes, \"scheme_align\"), \"guides\"),\n theme = x@theme\n ) + layout_title(\n title = .subset2(titles, \"title\"),\n subtitle = .subset2(titles, \"subtitle\"),\n caption = .subset2(titles, \"caption\")\n )\n}\n\nquad_build <- function(quad, schemes = NULL, theme = NULL,\n direction = NULL) {\n UseMethod(\"quad_build\")\n}\n\n#######################################################################\n#' @param schemes,theme Parameters from parent layout\n#' @importFrom ggplot2 aes\n#' @importFrom rlang is_empty\n#' @importFrom grid unit is.unit unit.c\n#' @export\n#' @noRd\nquad_build.QuadLayout <- function(quad, schemes = NULL, theme = NULL,\n direction = NULL) {\n data <- quad@data\n row_design <- setup_design(quad@horizontal)\n column_design <- setup_design(quad@vertical)\n if (is.function(data)) {\n cli_abort(c(\n \"{.arg data} cannot be a {.cls function}\",\n i = sprintf(\n \"Did you want to add %s to a {.fn stack_layout}?\",\n object_name(quad)\n )\n ))\n }\n if (is_discrete_design(row_design) &&\n is.null(.subset2(row_design, \"nobs\"))) {\n cli_abort(sprintf(\n \"you must initialize %s before drawing the main plot\",\n object_name(quad),\n ))\n }\n if (is_discrete_design(column_design) &&\n is.null(.subset2(column_design, \"nobs\"))) {\n cli_abort(sprintf(\n \"you must initialize %s before drawing the main plot\",\n object_name(quad),\n ))\n }\n schemes <- inherit_parent_layout_schemes(quad, schemes)\n if (is.null(direction)) {\n spacing <- NULL\n } else if (is_horizontal(direction)) {\n spacing <- \"y\"\n } else {\n spacing <- \"x\"\n }\n theme <- inherit_parent_layout_theme(quad, theme, spacing = spacing)\n\n # prepare action for vertical and horizontal stack layout\n vertical_align <- horizontal_align <- the_align <-\n .subset2(schemes, \"scheme_align\")\n if (!is.null(layout_labs <- .subset2(the_align, \"free_labs\")) &&\n !is.waive(layout_labs)) {\n # prepare labs for child stack layout\n horizontal_align$free_labs <- gsub(\"[lr]\", \"\", layout_labs)\n vertical_align$free_labs <- gsub(\"[tb]\", \"\", layout_labs)\n if (!nzchar(horizontal_align$free_labs)) {\n horizontal_align[\"free_labs\"] <- list(NULL)\n }\n if (!nzchar(vertical_align$free_labs)) {\n vertical_align[\"free_labs\"] <- list(NULL)\n }\n }\n\n # inherit from the parent stack layout\n if (!is.null(layout_spaces <- .subset2(the_align, \"free_spaces\")) &&\n !is.waive(layout_spaces)) {\n horizontal_align$free_spaces <- gsub(\"[lr]\", \"\", layout_spaces)\n vertical_align$free_spaces <- gsub(\"[tb]\", \"\", layout_spaces)\n if (!nzchar(horizontal_align$free_spaces)) {\n horizontal_align[\"free_spaces\"] <- list(NULL)\n }\n if (!nzchar(vertical_align$free_spaces)) {\n vertical_align[\"free_spaces\"] <- list(NULL)\n }\n }\n\n # plot annotations ----------------------------\n stack_list <- lapply(.TLBR, function(position) {\n if (is_empty(stack <- slot(quad, position))) {\n return(list(plot = NULL, size = NULL))\n }\n pschemes <- schemes\n # inherit from horizontal align or vertical align\n if (is_horizontal(to_direction(position))) {\n extra_design <- column_design\n pschemes$scheme_align <- horizontal_align\n } else {\n extra_design <- row_design\n pschemes$scheme_align <- vertical_align\n }\n plot <- stack_build(\n stack,\n schemes = pschemes,\n theme = theme,\n extra_design = extra_design\n )\n if (is.null(plot)) {\n size <- NULL\n } else {\n size <- stack@sizes\n }\n list(plot = plot, size = size)\n })\n names(stack_list) <- .TLBR\n stack_list <- list_transpose(stack_list)\n plots <- .subset2(stack_list, 1L) # the annotation plot itself\n sizes <- .subset2(stack_list, 2L) # annotation size\n\n # read the plot ---------------------------------------\n p <- quad@plot\n\n # setup the facet -----------------------------------\n do_row_facet <- is_discrete_design(row_design) &&\n nlevels(.subset2(row_design, \"panel\")) > 1L\n do_column_facet <- is_discrete_design(column_design) &&\n nlevels(.subset2(column_design, \"panel\")) > 1L\n\n if (do_row_facet && do_column_facet) {\n default_facet <- ggplot2::facet_grid(\n rows = ggplot2::vars(.data$.panel_y),\n cols = ggplot2::vars(.data$.panel_x),\n scales = \"free\", space = \"free\",\n drop = FALSE, as.table = FALSE\n )\n free_row <- FALSE\n free_column <- FALSE\n } else if (do_row_facet) {\n default_facet <- ggplot2::facet_grid(\n rows = ggplot2::vars(.data$.panel_y),\n scales = \"free_y\", space = \"free\",\n drop = FALSE, as.table = FALSE\n )\n free_row <- FALSE\n free_column <- is_continuous_design(column_design)\n } else if (do_column_facet) {\n default_facet <- ggplot2::facet_grid(\n cols = ggplot2::vars(.data$.panel_x),\n scales = \"free_x\", space = \"free\",\n drop = FALSE, as.table = FALSE\n )\n free_row <- is_continuous_design(row_design)\n free_column <- FALSE\n } else {\n default_facet <- facet_quad(object_name(quad))\n free_row <- is_continuous_design(row_design)\n free_column <- is_continuous_design(column_design)\n }\n\n # set the facets and coord ---------------------------\n # we don't align observations for `quad_free()`\n # add default data ----------------------------------\n p <- gguse_data(p, quad_build_data(data, row_design, column_design))\n p <- gguse_linear_coord(p, object_name(quad))\n p <- ggmelt_facet(p, default_facet,\n free_row = free_row, free_column = free_column\n )\n p <- p +\n ggalign_design(\n x = column_design, y = row_design,\n xlabels = .subset(\n colnames(data),\n .subset2(column_design, \"index\")\n ),\n ylabels = .subset(\n vec_names(data),\n .subset2(row_design, \"index\")\n )\n )\n\n # add action ----------------------------------------\n p <- plot_add_schemes(p, inherit_schemes(quad@body_schemes, schemes))\n if (do_row_facet) {\n p <- p + theme(panel.spacing.y = calc_element(\"panel.spacing.y\", theme))\n }\n if (do_column_facet) {\n p <- p + theme(panel.spacing.x = calc_element(\"panel.spacing.x\", theme))\n }\n p <- p + theme_recycle()\n\n # collect all plots and sizes ----------------------\n plots <- append(plots, list(main = p), 2L)\n sizes <- append(\n sizes,\n list(main = list(width = quad@width, height = quad@height)),\n 3L\n )\n list(plots = plots, sizes = sizes)\n}\n\n#' @importFrom stats reorder\nquad_build_data <- function(data, row_design, column_design) {\n if (is.null(data) ||\n (is_continuous_design(row_design) &&\n is_continuous_design(column_design))) {\n return(data)\n }\n if (is_discrete_design(row_design)) {\n row_panel <- .subset2(row_design, \"panel\")\n row_index <- .subset2(row_design, \"index\")\n row_data <- data_frame0(\n .panel_y = row_panel,\n .index_y = row_index,\n .y = seq_along(row_index)\n )\n }\n if (is_discrete_design(column_design)) {\n column_panel <- .subset2(column_design, \"panel\")\n column_index <- .subset2(column_design, \"index\")\n column_data <- data_frame0(\n .panel_x = column_panel,\n .index_x = column_index,\n .x = seq_along(column_index)\n )\n }\n if (is_discrete_design(row_design) && is_discrete_design(column_design)) {\n panel_data <- cross_join(row_data, column_data)\n by.x <- c(\".column_index\", \".row_index\")\n by.y <- c(\".index_x\", \".index_y\")\n } else if (is_discrete_design(column_design)) {\n panel_data <- column_data\n by.x <- \".column_index\"\n by.y <- \".index_x\"\n } else {\n panel_data <- row_data\n by.x <- \".row_index\"\n by.y <- \".index_y\"\n }\n ans <- fortify_data_frame.matrix(data)\n ans <- full_join(ans, panel_data, by.x = by.x, by.y = by.y)\n if (!is.null(.subset2(ans, \".row_names\")) &&\n is_discrete_design(row_design)) {\n ans$.discrete_y <- reorder(\n .subset2(ans, \".row_names\"),\n .subset2(ans, \".y\"),\n order = FALSE\n )\n }\n if (!is.null(.subset2(ans, \".column_names\")) &&\n is_discrete_design(column_design)) {\n ans$.discrete_x <- reorder(\n .subset2(ans, \".column_names\"),\n .subset2(ans, \".x\"),\n order = FALSE\n )\n }\n ggalign_data_restore(ans, data)\n}\n"], ["/ggalign/R/layout-chain-stack-cross.R", "#' Arrange plots crosswise horizontally or vertically\n#'\n#' @description\n#' `r lifecycle::badge('experimental')`\n#'\n#' The `stack_cross` function is derived from [`stack_discrete()`] and allows\n#' for different layout ordering indices within a single layout.\n#'\n#' Two aliases are provided for convenience:\n#' - `stack_crossv`: A special case of `stack_cross` that sets\n#' `direction = \"v\"` for vertical alignment.\n#' - `stack_crossh`: A special case of `stack_cross` that sets\n#' `direction = \"h\"` for horizontal alignment.\n#'\n#' @param data `r rd_layout_data()`, [`fortify_matrix()`] will be used to\n#' convert the data to a matrix.\n#' @param ... Additional arguments passed to [`fortify_matrix()`].\n#' @inheritParams stack_layout\n#' @seealso [`ggcross()`]\n#' @export\nstack_cross <- function(direction, data = NULL, ...,\n theme = NULL, sizes = NA) {\n UseMethod(\"stack_cross\", data)\n}\n\n#' @export\n#' @rdname stack_cross\nstack_crossv <- function(data = NULL, ...) {\n stack_cross(data = data, direction = \"v\", ...)\n}\n\n#' @export\n#' @rdname stack_cross\nstack_crossh <- function(data = NULL, ...) {\n stack_cross(data = data, direction = \"h\", ...)\n}\n\n#' @include layout-chain-stack-.R\nmethods::setClass(\n \"StackCross\",\n contains = \"StackLayout\",\n # A list of old design\n list(odesign = \"list\", cross_points = \"integer\", break_points = \"integer\"),\n prototype = list(\n odesign = list(),\n cross_points = integer(),\n break_points = integer()\n )\n)\n\n#' @export\nstack_cross.default <- function(direction, data = NULL, ...) {\n ans <- stack_discrete(data = data, direction = direction, ...)\n ans <- methods::as(ans, \"StackCross\")\n ans@name <- \"stack_cross\"\n ans\n}\n\n#' @importFrom grid unit.c\n#' @importFrom rlang is_empty is_string\nresolve_stack_layout.StackCross <- function(stack, schemes, theme,\n extra_design) {\n # check if we should initialize the layout observations\n layout_design <- stack@design\n if (is_discrete_design(layout_design) &&\n is.null(.subset2(layout_design, \"nobs\")) &&\n any(vapply(plot_list, is_cross_plot, logical(1L), USE.NAMES = FALSE))) {\n cli_abort(sprintf(\n \"You must initialize the layout observations to plot the %s\",\n object_name(stack)\n ))\n }\n plot_list <- stack@plot_list\n\n direction <- stack@direction\n position <- .subset2(stack@heatmap, \"position\")\n plot_list <- vec_chop(\n plot_list,\n sizes = diff(c(0L, stack@cross_points, length(plot_list)))\n )\n design_list <- c(stack@odesign, list(layout_design))\n\n # build the stack\n composer <- stack_composer(direction)\n\n # for `free_spaces`, if we have applied it in the whole stack layout we\n # shouln't use it for a single plot. Otherwise, the guide legends collected\n # by the layout will overlap with the axis of the plot in the layout.\n #\n # this occurs in the annotation stack (`position` is not `NULL`).\n stack_spaces <- .subset2(.subset2(schemes, \"scheme_align\"), \"free_spaces\")\n if (is_string(stack_spaces) && !is.null(position)) {\n released_spaces <- stack_spaces\n } else {\n released_spaces <- NULL\n }\n previous_design <- NULL\n for (i in seq_along(plot_list)) {\n plots <- .subset2(plot_list, i)\n\n # prepare design for current group\n design <- .subset2(design_list, i)\n design <- setup_design(design)\n\n if (is_empty(plots)) {\n previous_design <- design\n next\n }\n\n # we remove the plot without actual plot area\n keep <- vapply(plots, function(plot) {\n # we remove objects without plot area\n # Now, only `CraftBox` will contain `NULL`\n !is_craftbox(plot) || !is.null(plot@plot)\n }, logical(1L), USE.NAMES = FALSE)\n plots <- .subset(plots, keep)\n\n if (is_empty(plots)) {\n previous_design <- design\n next\n }\n\n # we reorder the plots based on the `order` slot\n plot_order <- vapply(plots, function(plot) {\n # always keep cross() in the start\n if (is_cross_plot(plot)) {\n 1L\n } else if (is_craftbox(plot)) {\n .subset2(plot@active, \"order\")\n } else {\n .subset2(plot@plot_active, \"order\")\n }\n }, integer(1L), USE.NAMES = FALSE)\n plots <- .subset(plots, make_order(plot_order))\n composer <- stack_composer_add(\n plots,\n stack = stack,\n composer,\n schemes = schemes,\n theme = theme,\n design = design,\n extra_design = extra_design,\n direction = direction,\n position = position,\n released_spaces = released_spaces,\n previous_design = previous_design\n )\n previous_design <- design\n }\n composer\n}\n"], ["/ggalign/R/layout-chain-.R", "# Used by both `circle_layout()` and `stack_layout()`\n#' @keywords internal\n#' @include layout-.R\nmethods::setClass(\n \"ChainLayout\",\n contains = \"LayoutProto\",\n list(\n data = \"ANY\",\n name = \"character\", # used to provide message\n plot_list = \"list\", # save the list of plots\n design = \"ANY\" # used to align axis\n )\n)\n\n#' Finalize plot modifications from a ChainLayout object.\n#'\n#' This generic function lets a ChainLayout apply any final transformations\n#' to the composed plot before returning it. It does not extract or store\n#' the plot, but instead allows the layout to inject custom modifications\n#' (e.g., spacing guides, annotations, alignment fixes) at the last step.\n#'\n#' @param layout A ChainLayout object.\n#' @param plot The plot being finalized.\n#' @keywords internal\nchain_decorate <- function(layout, plot) UseMethod(\"chain_decorate\")\n\n#' @export\nchain_decorate.ChainLayout <- function(layout, plot) plot\n\n#' @export\nis_layout_discrete.ChainLayout <- function(x, ...) {\n is_discrete_design(x@design)\n}\n\n#' @export\nis_layout_continuous.ChainLayout <- function(x, ...) {\n is_continuous_design(x@design)\n}\n\n#############################################################\n# To-DO: Use double dispatch\n#' @keywords internal\nchain_layout_add <- function(object, layout, object_name) {\n UseMethod(\"chain_layout_add\")\n}\n\n#' @export\nchain_layout_add.layout_title <- function(object, layout, object_name) {\n layout@titles <- update_non_waive(layout@titles, object)\n layout\n}\n\n#' @export\nchain_layout_add.list <- function(object, layout, object_name) {\n for (o in object) layout <- chain_layout_add(o, layout, object_name)\n layout\n}\n\n#' @export\nchain_layout_add.NULL <- function(object, layout, object_name) {\n layout\n}\n\n#' @export\nchain_layout_add.CraftBox <- function(object, layout, object_name) {\n craftsman <- object@craftsman\n # To-Do: Use S7 and double dispatch\n if (is.null(active_index <- layout@active) ||\n is_craftbox(plot <- .subset2(layout@plot_list, active_index))) {\n # unlock the object\n craftsman$unlock()\n\n # we lock the `Craftsman` object to prevent user from modifying this\n # object in `$build_plot()` method, we shouldn't do any calculations in\n # `$build_plot()` method\n on.exit(craftsman$lock())\n\n # initialize the necessary parameters for `Craftsman` object\n if (is_stack_layout(layout)) {\n craftsman$direction <- layout@direction\n craftsman$position <- .subset2(layout@heatmap, \"position\")\n } else if (is_circle_layout(layout)) {\n # we treat circle layout as a vertical stack layout\n craftsman$direction <- \"vertical\"\n }\n craftsman$in_linear <- is_linear(layout)\n craftsman$layout_name <- object_name(layout)\n\n # firstly, we let the object do some changes in the layout\n layout <- craftsman$interact_layout(layout)\n\n # this step, the object will act with the stack layout\n # group rows into panel or reorder rows, we can also\n # initialize object data\n new_design <- craftsman$setup_design(layout@design)\n\n # initialize the plot object\n object@plot <- craftsman$setup_plot(object@plot)\n\n layout <- chain_add_plot(layout, object, object@active, object_name)\n } else { # should be a QuadLayout object\n plot <- quad_layout_add(object, plot, object_name)\n layout@plot_list[[active_index]] <- plot\n new_design <- slot(plot, layout@direction)\n }\n update_design(layout, design = new_design, object_name = object_name)\n}\n\n#' @export\nchain_layout_add.continuous_limits <- function(object, layout, object_name) {\n if (is_discrete_design(layout@design)) {\n cli_abort(c(\n sprintf(\n \"Cannot add {.var {object_name}} to %s\",\n object_name(layout)\n ),\n i = sprintf(\n \"%s cannot align continuous variables\",\n object_name(layout)\n )\n ))\n }\n update_design(layout, design = object, object_name = object_name)\n}\n\n#' @export\nchain_layout_add.ggplot <- function(object, layout, object_name) {\n chain_layout_add(ggfree(data = object), layout, object_name)\n}\n\n# Add ggplot2 elements\n#' @export\nchain_layout_add.default <- function(object, layout, object_name) {\n if (is.null(active_index <- layout@active)) {\n cli_abort(c(\n sprintf(\n \"Cannot add {.var {object_name}} to %s\",\n object_name(layout)\n ),\n i = \"No active plot component\",\n i = paste(\n \"Did you forget to initialize a {.cls ggplot} object\",\n \"with {.fn ggalign} or {.fn ggfree}?\"\n )\n ))\n }\n plot <- .subset2(layout@plot_list, active_index)\n if (is_craftbox(plot)) {\n plot <- chain_plot_add(plot, object, object_name, TRUE)\n } else {\n plot <- quad_layout_add(object, plot, object_name)\n }\n layout@plot_list[[active_index]] <- plot\n layout\n}\n\n#' @export\nchain_layout_add.layout_theme <- function(object, layout, object_name) {\n if (is.null(active_index <- layout@active) ||\n is_craftbox(plot <- .subset2(layout@plot_list, active_index))) {\n layout@theme <- update_layout_theme(layout@theme, object)\n } else {\n layout@plot_list[[active_index]] <- quad_layout_add(\n object, plot, object_name\n )\n }\n layout\n}\n\nchain_plot_add <- function(plot, object, object_name, force) {\n # if `align` has plot, we added the object\n if (force || !is.null(plot@plot)) {\n plot <- craftbox_add(object, plot, object_name)\n }\n plot\n}\n\nchain_add_plot <- function(layout, plot, active, object_name) {\n # set up context index\n plot_list <- layout@plot_list\n if (.subset2(active, \"use\")) {\n active_index <- length(plot_list) + 1L\n } else {\n active_index <- layout@active\n }\n # check the name is unique\n if (!is.na(name <- .subset2(active, \"name\"))) {\n if (any(names(plot_list) == name)) {\n cli_warn(\n \"Adding {.var {object_name}} will replace existing {.field {name}} plot\"\n )\n }\n plot_list[[name]] <- plot\n } else {\n plot_list <- c(plot_list, list(plot))\n }\n\n # add QuadLayout\n layout@plot_list <- plot_list\n layout@active <- active_index\n layout\n}\n\nswitch_chain_plot <- function(layout, what, call = caller_call()) {\n if (!is.waive(what)) {\n if (!is.null(what)) {\n what <- vec_as_location2(\n what,\n vec_size(layout@plot_list),\n vec_names(layout@plot_list),\n missing = \"error\",\n arg = \"what\", call = call\n )\n }\n layout@active <- what\n }\n layout\n}\n\n##############################################################\n# for `stack_layout()` only\n#' @export\nchain_layout_add.ggalign_with_quad <- function(object, layout, object_name) {\n if (!is_stack_layout(layout)) {\n cli_abort(sprintf(\n \"Cannot add {.var {object_name}} to %s\",\n object_name(layout)\n ))\n }\n if (is.null(active_index <- layout@active) ||\n is_craftbox(plot <- .subset2(layout@plot_list, active_index))) {\n cli_abort(c(\n sprintf(\n \"Cannot add {.var {object_name}} to %s\",\n object_name(layout)\n ),\n i = \"Did you forget to add a {.fn quad_layout}?\"\n ))\n } else {\n layout@plot_list[[active_index]] <- quad_layout_add(\n object, plot, object_name\n )\n }\n layout\n}\n\n#' @export\nchain_layout_add.quad_active <- chain_layout_add.ggalign_with_quad\n\n#' @export\nchain_layout_add.quad_anno <- chain_layout_add.quad_active\n\n#' @export\nchain_layout_add.StackLayout <- chain_layout_add.quad_active\n\n#' @export\nchain_layout_add.StackCross <- function(object, layout, object_name) {\n if (!is_stack_layout(layout)) {\n cli_abort(sprintf(\n \"Cannot add {.var {object_name}} to %s\",\n object_name(layout)\n ))\n }\n\n # preventing from adding `stack_cross` with the same direction in this way,\n # `stack_cross()` cannot be added to the heatmap annotation parallelly with\n # the `stack_layout()`\n if (identical(object@direction, layout@direction)) {\n cli_abort(c(\n sprintf(\n \"Cannot add {.var {object_name}} to %s\",\n object_name(layout)\n ),\n i = \"Cannot add {.fn stack_cross} with the same direction as {.fn stack_discrete}.\"\n ))\n }\n NextMethod() # call StackLayout method\n}\n\n#' @export\nchain_layout_add.stack_switch <- function(object, layout, object_name) {\n if (!is_stack_layout(layout)) {\n cli_abort(c(\n sprintf(\n \"Cannot add {.var {object_name}} to %s\",\n object_name(layout)\n ),\n i = \"Did you want to add a {.fn circle_switch}?\"\n ))\n }\n layout <- switch_chain_plot(\n layout, .subset2(object, \"what\"),\n quote(stack_switch())\n )\n if (!is.null(sizes <- .subset2(object, \"sizes\"))) {\n layout@sizes <- sizes\n }\n layout\n}\n\n#' @importFrom methods slot\n#' @export\nchain_layout_add.QuadLayout <- function(object, layout, object_name) {\n if (!is_stack_layout(layout)) {\n cli_abort(sprintf(\n \"Cannot add {.var {object_name}} to %s\",\n object_name(layout)\n ))\n }\n\n # preventing from adding `stack_cross` with the same direction\n # `cross_link()` cannot be added to the heatmap annotation\n # parallelly with the `stack_cross()`\n if (is_horizontal(direction <- layout@direction)) {\n if (is_cross_layout(object@left) || is_cross_layout(object@right)) {\n cli_abort(c(\n sprintf(\n \"Cannot add {.var {object_name}} to %s\",\n object_name(layout)\n ),\n i = sprintf(\n \"{.field left} or {.field right} annotation contains %s\",\n \"{.fn stack_cross}\"\n )\n ))\n }\n } else if (is_cross_layout(object@top) || is_cross_layout(object@bottom)) {\n cli_abort(c(\n sprintf(\n \"Cannot add {.var {object_name}} to %s\",\n object_name(layout)\n ),\n i = sprintf(\n \"{.field top} or {.field bottom} annotation contains %s\",\n \"{.fn stack_cross}\"\n )\n ))\n }\n\n # check quad layout is compatible with stack layout\n quad_data <- object@data\n stack_design <- layout@design\n quad_design <- slot(object, direction)\n if (is_continuous_design(quad_design)) {\n if (is_discrete_design(stack_design)) {\n cli_abort(c(\n sprintf(\n \"Cannot add %s to %s\",\n object_name(object), object_name(layout)\n ),\n i = sprintf(\n \"%s cannot align continuous variable\",\n object_name(layout)\n )\n ))\n }\n # `quad_layout()` will align continuous variables,\n # `data` can be `NULL`\n extra_design <- slot(object, vec_set_difference(\n c(\"vertical\", \"horizontal\"), direction\n ))\n allow_null <- is_continuous_design(extra_design)\n if (is.waive(quad_data) || is.function(quad_data)) {\n # check if we should initialize the `quad_layout()` data\n if (is.null(stack_data <- layout@data)) {\n if (allow_null) {\n quad_data <- NULL\n } else {\n cli_abort(c(\n sprintf(\n \"you must provide {.arg data} argument in %s\",\n object_name(object)\n ),\n i = sprintf(\n \"no data was found in %s\",\n object_name(layout)\n )\n ))\n }\n } else {\n data <- stack_data # should be a data frame\n if (is.waive(quad_data)) { # inherit from the stack layout\n if (!allow_null) { # we need a matrix\n cli_abort(c(\n sprintf(\n \"Cannot add %s to %s\",\n object_name(object), object_name(layout)\n ),\n i = sprintf(\n \"{.arg data} in %s is %s, but %s need a {.cls matrix}.\",\n object_name(layout),\n \"{.obj_type_friendly {data}}\",\n object_name(object)\n ),\n i = sprintf(\n \"Try provide {.arg data} in %s\",\n object_name(object)\n )\n ))\n }\n } else { # `quad_data` is a function\n data <- quad_data(data)\n # check the data format is correct\n if (allow_null) { # we need a data frame\n if (!is.data.frame(data)) {\n cli_abort(sprintf(\n \"{.arg data} in %s must return a {.cls data.frame}\",\n object_name(object)\n ))\n }\n } else if (!is.matrix(data)) { # we need a matrix\n cli_abort(sprintf(\n \"{.arg data} in %s must return a {.cls matrix}\",\n object_name(object)\n ))\n } else {\n if (NROW(data) == 0L || ncol(data) == 0L) {\n cli_abort(sprintf(\n \"{.arg data} in %s return an empty matrix\",\n object_name(object)\n ))\n }\n }\n }\n # we initialize the `nobs` of the extra_design for the\n # `quad_layout()`\n if (is_horizontal(direction)) {\n if (is_discrete_design(slot(object, \"vertical\"))) {\n slot(object, \"vertical\")$nobs <- ncol(data)\n }\n } else {\n if (is_discrete_design(slot(object, \"horizontal\"))) {\n slot(object, \"horizontal\")$nobs <- nrow(data)\n }\n }\n }\n # restore the ggalign attribute\n object@data <- ggalign_data_restore(data, stack_data)\n }\n layout_design <- quad_design\n } else if (is_discrete_design(stack_design)) {\n # both `quad_layout()` and `stack_layout()` will align discrete\n # variables\n if (is.waive(quad_data) || is.function(quad_data)) {\n if (is.null(stack_data <- layout@data)) {\n cli_abort(c(\n sprintf(\n \"you must provide {.arg data} argument in %s\",\n object_name(object)\n ),\n i = sprintf(\n \"no data was found in %s\",\n object_name(layout)\n )\n ))\n }\n # set `quad_layout()` data\n data <- switch_direction(direction, stack_data, t(stack_data))\n if (is.function(quad_data)) {\n data <- quad_data(data)\n if (!is.matrix(data)) {\n cli_abort(sprintf(\n \"{.arg data} in %s must return a matrix\",\n object_name(object)\n ))\n }\n if (NROW(data) == 0L || ncol(data) == 0L) {\n cli_abort(sprintf(\n \"{.arg data} in %s return an empty matrix\",\n object_name(object)\n ))\n }\n } else {\n if (NROW(data) == 0L || ncol(data) == 0L) {\n cli_abort(c(\n sprintf(\n \"Cannot use data from %s in %s\",\n object_name(layout), object_name(object)\n ),\n i = sprintf(\n \"{.arg data} in %s is an empty matrix\",\n object_name(layout)\n )\n ))\n }\n }\n # set the `nobs` for `quad_layout()`\n if (is_horizontal(direction)) {\n quad_design$nobs <- nrow(data)\n if (is_discrete_design(slot(object, \"vertical\"))) {\n slot(object, \"vertical\")$nobs <- ncol(data)\n }\n } else {\n quad_design$nobs <- ncol(data)\n if (is_discrete_design(slot(object, \"horizontal\"))) {\n slot(object, \"horizontal\")$nobs <- nrow(data)\n }\n }\n # restore the ggalign attribute\n object@data <- ggalign_data_restore(data, stack_data)\n }\n layout_design <- melt_discrete_design(\n stack_design, quad_design,\n old_name = object_name(layout),\n new_name = object_name\n )\n } else {\n cli_abort(c(\n sprintf(\n \"Cannot add %s to %s\",\n object_name(object), object_name(layout)\n ),\n i = sprintf(\n \"%s cannot align discrete variable\",\n object_name(layout)\n )\n ))\n }\n stack <- chain_add_plot(layout, object, object@plot_active, object_name)\n update_design(\n stack,\n design = layout_design,\n object_name = object_name\n )\n}\n\n##################################################\n#' @export\nchain_layout_add.circle_switch <- function(object, layout, object_name) {\n if (!is_circle_layout(layout)) {\n cli_abort(c(\n sprintf(\n \"Cannot add {.var {object_name}} to %s\",\n object_name(layout)\n ),\n i = \"Did you want to add a {.fn stack_switch}?\"\n ))\n }\n if (!is.waive(radial <- .subset2(object, \"radial\"))) {\n layout@radial <- radial\n }\n if (!is.null(direction <- .subset2(object, \"direction\"))) {\n layout@direction <- direction\n }\n layout <- switch_chain_plot(\n layout, .subset2(object, \"what\"),\n quote(circle_switch())\n )\n layout\n}\n"], ["/ggalign/R/layout-chain-circle-build.R", "#' @export\nggalign_build.CircleLayout <- function(x) {\n x <- default_layout(x)\n circle_build(x)\n}\n\n#' @importFrom utils packageVersion\n#' @importFrom ggplot2 find_panel calc_element ggproto ggplotGrob theme\n#' @importFrom gtable gtable_add_grob gtable_add_padding is.gtable\n#' @importFrom grid unit viewport editGrob\n#' @importFrom rlang is_empty arg_match0\ncircle_build <- function(circle, schemes = NULL, theme = NULL) {\n schemes <- inherit_parent_layout_schemes(circle, schemes)\n theme <- inherit_parent_layout_theme(circle, theme)\n # for empty plot\n base <- ggplot() +\n theme +\n ggplot2::labs(\n title = .subset2(circle@titles, \"title\"),\n subtitle = .subset2(circle@titles, \"subtitle\"),\n caption = .subset2(circle@titles, \"caption\")\n )\n if (is_empty(plot_list <- circle@plot_list)) {\n return(ggplotGrob(base))\n }\n\n # we remove the plot without actual plot area\n keep <- vapply(plot_list, function(plot) {\n !is.null(plot@plot)\n }, logical(1L), USE.NAMES = FALSE)\n plot_list <- .subset(plot_list, keep)\n if (is_empty(plot_list)) return(ggplotGrob(base)) # styler: off\n\n # we reorder the plots based on the `order` slot\n plot_order <- vapply(plot_list, function(plot) {\n .subset2(plot@active, \"order\")\n }, integer(1L), USE.NAMES = FALSE)\n plot_list <- .subset(plot_list, make_order(plot_order))\n\n # plot coordinate\n if (is.null(input_radial <- circle@radial)) {\n radial <- coord_circle(theta = \"x\", r.axis.inside = TRUE)\n } else {\n radial <- ggproto(NULL, input_radial, theta = \"x\", r_axis_inside = TRUE)\n }\n\n sizes <- vapply(plot_list, function(plot) {\n # for circular layout, we only support relative size\n if (is.na(size <- as.numeric(plot@size))) {\n size <- 1\n }\n size\n }, numeric(1L), USE.NAMES = FALSE)\n\n # For each plot track, relative to the total radius (1):\n # 1. total radius: 1\n # 2. total radius for the plot area (for each plot track): 1 - inner_radius\n if (inherits(radial, \"CoordCircle\")) {\n inner_radius <- radial$inner_radius[1L] / 0.5\n outer_radius <- radial$inner_radius[2L] / 0.5\n } else {\n # For `CoordRadial`\n # `0.4` is coord_radial used for scale size in ggplot2 to add extra\n # spaces for axis labels\n # https://github.com/tidyverse/ggplot2/issues/6284\n inner_radius <- radial$inner_radius[1L] / 0.4\n outer_radius <- radial$inner_radius[2L] / 0.4\n }\n plot_track <- sizes / sum(sizes) * (outer_radius - inner_radius)\n\n # For each plot, the plot size is calculated by adding the space for the\n # inner radius of each track.\n N <- length(plot_list)\n index <- seq_len(N)\n direction <- circle@direction\n if (identical(direction, \"outward\")) {\n plot_sizes <- inner_radius + cumsum(plot_track)\n } else {\n plot_sizes <- outer_radius -\n cumsum(c(0, utils::head(plot_track, -1L)))\n # The plots are always build outward, so the order is reversed.\n index <- rev(index)\n }\n\n # For each plot, the inner radius is calculated as the difference between\n # the plot size and its track size.\n plot_inner <- plot_sizes - plot_track\n guides <- vector(\"list\", N)\n plot_table <- NULL\n design <- setup_design(circle@design)\n for (i in index) {\n plot_size <- plot_sizes[[i]]\n plot <- .subset2(plot_list, i)\n craftsman <- plot@craftsman # `Craftsman` object\n plot_schemes <- inherit_schemes(plot@schemes, schemes)\n # the actual plot\n plot <- plot@plot\n\n # we always use `null` facet\n # we won't respect `free_facet` and `free_coord`\n plot_coord <- gguse_circle_coord(\n plot,\n coord = radial,\n # https://github.com/tidyverse/ggplot2/issues/6284\n # Use `0.5` to remove the extra spaces for axis label\n inner_radius = c(\n plot_inner[[i]] / plot_size,\n # for the outmost plot, we respect the outer radius defined by\n # the users, for others, we alway use 1 to remove any spacing\n # between two tracks\n if (i == N) outer_radius else 1\n ) * 0.5,\n layout_name = craftsman$layout_name\n )\n if (!craftsman$free_facet) {\n if (is_discrete_design(design)) {\n if (nlevels(.subset2(design, \"panel\")) > 1L) {\n plot <- plot + facet_sector(\n ggplot2::vars(.data$.panel),\n sector_spacing = circle@sector_spacing %||% (pi / 180),\n drop = FALSE\n )\n } else {\n plot <- ggmelt_facet(plot, ggplot2::facet_null())\n }\n } else {\n if (inherits(plot$facet, \"FacetSector\")) {\n plot <- ggfacet_modify(plot,\n sector_spacing = circle@sector_spacing %||% (pi / 180),\n drop = FALSE\n )\n } else {\n plot <- ggmelt_facet(plot, ggplot2::facet_null())\n }\n }\n }\n plot$coordinates <- plot_coord\n\n # set limits and default scales\n if (!craftsman$free_limits) {\n plot <- plot + ggalign_design(\n x = design,\n xlabels = .subset(craftsman$labels, .subset2(design, \"index\"))\n )\n }\n\n # let `Craftsman` add other components\n plot <- craftsman$build_plot(plot, design = design)\n plot <- craftsman$finish_plot(\n plot,\n schemes = plot_schemes, theme = theme\n )\n plot <- plot + ggplot2::labs(x = NULL, y = NULL) +\n theme(panel.border = element_blank())\n plot <- chain_decorate(circle, plot)\n\n # copied from `ggplot2:::ggplot_gtable`\n data <- ggplot2::ggplot_build(plot)\n plot <- data$plot\n plot_layout <- data$layout\n data <- data$data\n plot_theme <- complete_theme(plot$theme)\n\n geom_grobs <- ggfun(\"by_layer\")(\n function(l, d) l$draw_geom(d, plot_layout),\n plot$layers, data,\n \"converting geom to grob\"\n )\n gt <- plot_layout$render(geom_grobs, data, plot_theme, plot$labels)\n\n # for each inner gtable, we insert it to the panel area of the\n # outter gtable\n #\n # For bbox, `ggplot2::polar_bbox` always take (0.5, 0.5) as origin\n bbox <- ggfun(\"polar_bbox\")(\n plot_layout$coord$arc, margin = c(0, 0, 0, 0),\n inner_radius = plot_layout$coord$inner_radius\n )\n origin <- c(\n scales::rescale(0.5, from = bbox$x),\n scales::rescale(0.5, from = bbox$y)\n )\n spacing <- calc_element(\"panel.spacing.r\", plot_theme)\n\n if (is.null(plot_table)) {\n plot_table <- gt\n } else {\n # define the panel size of the inner track\n rescale_factor <- last_plot_size / plot_size\n\n # the spacer between two plots\n if (identical(direction, \"outward\")) {\n spacer <- last_spacing\n } else {\n spacer <- spacing\n }\n if (inherits(spacer, \"element_blank\") || is.null(spacer)) {\n spacer <- unit(0, \"mm\")\n }\n plot_table <- editGrob(plot_table, vp = viewport(\n width = unit(rescale_factor, \"npc\") - spacer,\n height = unit(rescale_factor, \"npc\") - spacer,\n x = origin[1L], y = origin[2L], just = just,\n default.units = \"native\", clip = \"off\"\n ))\n\n # add the inner track to the panel area of the outter track\n panel_loc <- find_panel(gt)\n plot_table <- gtable_add_grob(\n gt, plot_table,\n t = .subset2(panel_loc, \"t\"),\n l = .subset2(panel_loc, \"l\"),\n b = .subset2(panel_loc, \"b\"),\n r = .subset2(panel_loc, \"r\"),\n name = \"inner-track\"\n )\n }\n\n # build legends\n guides[i] <- list(plot$guides$assemble(plot_theme))\n\n # assign value for next loop\n just <- origin\n last_plot_size <- plot_size # the last plot panel size\n last_spacing <- spacing\n }\n\n # attach the guide legends\n guides <- collect_guides_list(guides, zeroGrob())\n theme$legend.spacing <- theme$legend.spacing %||% unit(0.5, \"lines\")\n theme$legend.spacing.y <- calc_element(\"legend.spacing.y\", theme)\n theme$legend.spacing.x <- calc_element(\"legend.spacing.x\", theme)\n theme$legend.box.spacing <- calc_element(\n \"legend.box.spacing\", theme\n ) %||% unit(0.2, \"cm\")\n legend_box <- .mapply(\n function(guides, guide_pos) assemble_guides(guides, guide_pos, theme),\n list(guides = guides, guide_pos = names(guides)),\n NULL\n )\n names(legend_box) <- names(guides)\n plot_table <- ggfun(\"table_add_legends\")(plot_table, legend_box, theme)\n\n # Title\n title <- element_render(\n theme, \"plot.title\", .subset2(circle@titles, \"title\"),\n margin_y = TRUE, margin_x = TRUE\n )\n title_height <- grobHeight(title)\n\n # Subtitle\n subtitle <- element_render(\n theme, \"plot.subtitle\", .subset2(circle@titles, \"subtitle\"),\n margin_y = TRUE, margin_x = TRUE\n )\n subtitle_height <- grobHeight(subtitle)\n\n # whole plot annotation\n caption <- element_render(\n theme, \"plot.caption\", .subset2(circle@titles, \"caption\"),\n margin_y = TRUE, margin_x = TRUE\n )\n caption_height <- grobHeight(caption)\n\n # positioning of title and subtitle is governed by plot.title.position\n # positioning of caption is governed by plot.caption.position\n # \"panel\" means align to the panel(s)\n # \"plot\" means align to the entire plot (except margins and tag)\n title_pos <- arg_match0(\n theme$plot.title.position %||% \"panel\",\n c(\"panel\", \"plot\"),\n arg_nm = \"plot.title.position\",\n error_call = quote(theme())\n )\n\n caption_pos <- arg_match0(\n theme$plot.caption.position %||% \"panel\",\n values = c(\"panel\", \"plot\"),\n arg_nm = \"plot.caption.position\",\n error_call = quote(theme())\n )\n\n pans <- plot_table$layout[\n grepl(\"^panel\", plot_table$layout$name), ,\n drop = FALSE\n ]\n if (title_pos == \"panel\") {\n title_l <- min(pans$l)\n title_r <- max(pans$r)\n } else {\n title_l <- 1\n title_r <- ncol(plot_table)\n }\n if (caption_pos == \"panel\") {\n caption_l <- min(pans$l)\n caption_r <- max(pans$r)\n } else {\n caption_l <- 1\n caption_r <- ncol(plot_table)\n }\n\n plot_table <- gtable_add_rows(plot_table, subtitle_height, pos = 0)\n plot_table <- gtable_add_grob(plot_table, subtitle,\n name = \"subtitle\",\n t = 1, b = 1, l = title_l, r = title_r, clip = \"off\"\n )\n\n plot_table <- gtable_add_rows(plot_table, title_height, pos = 0)\n plot_table <- gtable_add_grob(plot_table, title,\n name = \"title\",\n t = 1, b = 1, l = title_l, r = title_r, clip = \"off\"\n )\n\n plot_table <- gtable_add_rows(plot_table, caption_height, pos = -1)\n plot_table <- gtable_add_grob(plot_table, caption,\n name = \"caption\",\n t = -1, b = -1, l = caption_l, r = caption_r, clip = \"off\"\n )\n plot_table <- ggfun(\"table_add_tag\")(plot_table, NULL, theme)\n\n # Margins\n plot_margin <- calc_element(\"plot.margin\", theme) %||% margin()\n plot_table <- gtable_add_padding(plot_table, plot_margin)\n\n if (inherits(theme$plot.background, \"element\")) {\n plot_table <- gtable_add_grob(plot_table,\n element_render(theme, \"plot.background\"),\n t = 1, l = 1, b = -1, r = -1, name = \"background\", z = -Inf\n )\n plot_table$layout <- plot_table$layout[\n c(nrow(plot_table$layout), 1:(nrow(plot_table$layout) - 1)),\n ]\n plot_table$grobs <- plot_table$grobs[\n c(nrow(plot_table$layout), 1:(nrow(plot_table$layout) - 1))\n ]\n }\n\n # add alt-text as attribute\n # attr(plot_table, \"alt-label\") <- plot$labels$alt\n strip_pos <- find_strip_pos(plot_table)\n\n # always add strips columns and/or rows\n plot_table <- add_strips(plot_table, strip_pos)\n setup_patch_titles(plot_table, patch_titles = list(\n top = NULL, left = NULL, bottom = NULL, right = NULL\n ), theme = theme)\n}\n"], ["/ggalign/R/mark.R", "#' Define the links to connect the marked observations\n#'\n#' @description\n#' This function allows users to define links between marked observations and\n#' plot panel (e.g., for creating visual connections for related data), which\n#' could help explain the observations.\n#'\n#' @param .draw A function used to draw the links. The function must return a\n#' [`grob()`][grid::grob] object. If the function does not return a valid\n#' `grob`, nothing will be drawn. The input data for the function must contain\n#' two arguments: a data frame for the panel side coordinates and a data frame\n#' for the marked observation coordinates.\n#' @inheritParams .mark_draw\n#' @seealso\n#' - [`mark_line()`]\n#' - [`mark_tetragon()`]\n#' - [`mark_triangle()`]\n#' - [`.mark_draw()`]\n#' @importFrom rlang is_empty inject\n#' @importFrom grid gTree gList\n#' @export\nmark_draw <- function(.draw, ...) {\n if (!is.function(draw <- allow_lambda(.draw))) {\n cli_abort(\"{.arg .draw} must be a function\")\n }\n new_draw <- function(data) {\n ans <- lapply(data, function(dd) {\n draw(.subset2(dd, \"panel\"), .subset2(dd, \"link\"))\n })\n ans <- ans[vapply(ans, is.grob, logical(1L), USE.NAMES = FALSE)]\n if (!is_empty(ans)) {\n gTree(children = inject(gList(!!!ans)))\n }\n }\n .mark_draw(new_draw, ...)\n}\n\n#' @inherit mark_draw title\n#'\n#' @description\n#' A base version of [`mark_draw`], designed for performance optimization. This\n#' function is used to build other `mark_*` functions that manage the drawing of\n#' links between marked observations.\n#'\n#' @param .draw A function used to draw the links. The function must return a\n#' [`grob()`][grid::grob] object. If the function does not return a valid\n#' `grob`, nothing will be drawn. The input data for the function contains a\n#' list, where each item is a list of two data frames: one for the panel side\n#' coordinates (`\"panel\"`) and one for the marked observations coordinates\n#' (`\"link\"`).\n#'\n#' @inheritParams pair_links\n#' @seealso [`mark_draw()`]\n#' @export\n.mark_draw <- function(.draw, ...) {\n if (override_call(call <- caller_call())) {\n call <- current_call()\n }\n if (!is.function(draw <- allow_lambda(.draw))) {\n cli_abort(\"{.arg .draw} must be a function\", call = call)\n }\n links <- pair_links(...)\n structure(list(draw = draw, links = links), class = \"ggalign_mark_draw\")\n}\n\n#' @export\nprint.ggalign_mark_draw <- function(x, ...) {\n header <- sprintf(\"<%s>\", vec_ptype_full(x))\n cat(header, sep = \"\\n\")\n obj_print_data(.subset2(x, \"links\"))\n invisible(x)\n}\n\n#' Link the observations and the panel with a line\n#'\n#' @inheritParams .mark_draw\n#' @param .element A [`element_line()`][ggplot2::element_line] object.\n#' Vectorized fields will be recycled to match the total number of groups, or\n#' you can wrap the element with [`I()`] to recycle to match the drawing\n#' groups. The drawing groups typically correspond to the number of\n#' observations, as each observation will be linked with the plot panel.\n#' @importFrom ggplot2 element_line\n#' @export\nmark_line <- function(..., .element = NULL) {\n assert_s3_class(.element, \"element_line\", allow_null = TRUE)\n default <- calc_element(\"ggalign.line\", complete_theme(theme_get()))\n if (is.null(.element)) {\n .element <- default\n } else {\n .element <- ggplot2::merge_element(.element, default)\n }\n .mark_draw(.draw = function(data) {\n data <- lapply(data, function(d) {\n panel <- .subset2(d, \"panel\")\n link <- .subset2(d, \"link\")\n data_frame0(\n # there is only one row for panel, it's safe to use\n # vec_interleave directly\n x = vec_interleave(\n (panel$x + panel$xend) / 2L,\n (link$x + link$xend) / 2L\n ),\n y = vec_interleave(\n (panel$y + panel$yend) / 2L,\n (link$y + link$yend) / 2L\n )\n )\n })\n if (inherits(.element, \"AsIs\")) {\n .element <- element_rep_len(.element,\n length.out = sum(list_sizes(data)) / 2L\n )\n } else {\n .element <- element_rep_len(.element, length.out = length(data))\n .element <- element_vec_rep_each(.element,\n times = list_sizes(data) / 2L\n )\n }\n data <- vec_rbind(!!!data)\n element_grob(\n .element,\n x = data$x, y = data$y,\n id.lengths = vec_rep(2L, vec_size(data) / 2L),\n default.units = \"native\"\n )\n }, ...)\n}\n\n#' Link the observations and the panel with a quadrilateral\n#'\n#' @inheritParams .mark_draw\n#' @param .element A [`element_polygon()`] object. Vectorized fields will be\n#' recycled to match the total number of groups, or you can wrap the element\n#' with [`I()`] to recycle to match the drawing groups. The drawing groups\n#' are usually the same as the defined groups, but they will differ when the\n#' defined group of observations is separated and cannot be linked with a\n#' single quadrilateral. In such cases, the number of drawing groups will be\n#' larger than the number of defined groups.\n#' @export\nmark_tetragon <- function(..., .element = NULL) {\n assert_s3_class(.element, \"element_polygon\", allow_null = TRUE)\n default <- calc_element(\"ggalign.polygon\", complete_theme(theme_get()))\n if (is.null(.element)) {\n .element <- default\n } else {\n .element <- ggplot2::merge_element(.element, default)\n }\n .mark_draw(.draw = function(data) {\n data <- lapply(data, function(d) {\n panel <- .subset2(d, \"panel\")\n link <- .subset2(d, \"link\")\n\n # find the consecutive groups\n index <- .subset2(link, \"link_index\")\n oindex <- order(index)\n group <- cumsum(c(0L, diff(index[oindex])) != 1L)\n\n # restore the order\n group <- group[order(oindex)]\n\n # split link into groups\n link <- vec_split(link, group)\n\n # for each group, we draw a quadrilateral\n vec_rbind(!!!lapply(.subset2(link, \"val\"), function(dd) {\n data_frame0(\n x = vec_c(panel$x, panel$xend, max(dd$xend), min(dd$x)),\n y = vec_c(panel$y, panel$yend, max(dd$yend), min(dd$y))\n )\n }))\n })\n if (inherits(.element, \"AsIs\")) {\n .element <- element_rep_len(.element,\n length.out = sum(list_sizes(data)) / 4L\n )\n } else {\n .element <- element_rep_len(.element, length.out = length(data))\n .element <- element_vec_rep_each(.element,\n times = list_sizes(data) / 4L\n )\n }\n data <- vec_rbind(!!!data)\n if (vec_size(data)) {\n element_grob(\n .element,\n x = data$x, y = data$y,\n id.lengths = vec_rep(4L, nrow(data) / 4L),\n default.units = \"native\"\n )\n }\n }, ...)\n}\n\n#' Link the observations and the panel with a triangle\n#'\n#' @inheritParams .mark_draw\n#' @param orientation A single string, either `\"plot\"` or `\"observation\"`,\n#' indicating the base of the triangle.\n#' @param .element An [`element_polygon()`] object. Vectorized fields will be\n#' recycled to match the total number of groups, or you can wrap the element\n#' with [`I()`] to recycle to match the drawing groups.\n#' - When `orientation` is `\"plot\"`, the drawing groups typically correspond\n#' to the number of observations.\n#' - When `orientation` is `\"observation\"`, the drawing groups usually match\n#' the defined groups, but will differ if the defined group of observations\n#' is separated and cannot be linked with a single triangle. In this case,\n#' the number of drawing groups will be larger than the number of defined\n#' groups.\n#' @importFrom rlang arg_match0\n#' @export\nmark_triangle <- function(..., orientation = \"plot\", .element = NULL) {\n assert_s3_class(.element, \"element_polygon\", allow_null = TRUE)\n default <- calc_element(\"ggalign.polygon\", complete_theme(theme_get()))\n if (is.null(.element)) {\n .element <- default\n } else {\n .element <- ggplot2::merge_element(.element, default)\n }\n orientation <- arg_match0(orientation, c(\"plot\", \"observation\"))\n .mark_draw(.draw = function(data) {\n data <- lapply(data, function(d) {\n panel <- .subset2(d, \"panel\")\n link <- .subset2(d, \"link\")\n if (identical(orientation, \"plot\")) {\n # for each link, we draw a triangle\n triangle_list <- lapply(vec_seq_along(link), function(i) {\n dd <- vec_slice(link, i)\n data_frame0(\n x = vec_c(panel$x, panel$xend, (dd$x + dd$xend) / 2L),\n y = vec_c(panel$y, panel$yend, (dd$y + dd$yend) / 2L),\n )\n })\n } else {\n # find the consecutive groups\n index <- .subset2(link, \"link_index\")\n oindex <- order(index)\n group <- cumsum(c(0L, diff(index[oindex])) != 1L)\n\n # restore the order\n group <- group[order(oindex)]\n\n # split link into groups\n link <- vec_split(link, group)\n\n # for each group, we draw a triangle\n triangle_list <- lapply(.subset2(link, \"val\"), function(dd) {\n data_frame0(\n x = vec_c(\n (panel$x + panel$xend) / 2L,\n max(dd$xend), min(dd$x)\n ),\n y = vec_c(\n (panel$y + panel$yend) / 2L,\n max(dd$yend), min(dd$y)\n )\n )\n })\n }\n vec_rbind(!!!triangle_list)\n })\n if (inherits(.element, \"AsIs\")) {\n .element <- element_rep_len(.element,\n length.out = sum(list_sizes(data)) / 3L\n )\n } else {\n .element <- element_rep_len(.element, length.out = length(data))\n .element <- element_vec_rep_each(.element,\n times = list_sizes(data) / 3L\n )\n }\n data <- vec_rbind(!!!data)\n if (vec_size(data)) {\n element_grob(\n .element,\n x = data$x, y = data$y,\n id.lengths = vec_rep(3L, nrow(data) / 3L),\n default.units = \"native\"\n )\n }\n }, ...)\n}\n\n#####################################################\n#' @export\n`[.ggalignMarkGtable` <- function(x, i, j) {\n # subset will violate the `ggalignMarkGtable` `shape`\n # we always use the next method\n x <- remove_class(x, \"ggalignMarkGtable\")\n x$ggalign_link_data <- NULL\n NextMethod()\n}\n\n#' @importFrom ggplot2 ggproto\n#' @export\nalignpatch.ggalign_mark_plot <- function(x) {\n ggproto(NULL, PatchAlignMark, plot = x)\n}\n\n#' @importFrom ggplot2 ggproto ggproto_parent\n#' @include alignpatch-ggplot2.R\nPatchAlignMark <- ggproto(\n \"PatchAlignMark\", PatchGgplot,\n patch_gtable = function(self, theme, guides, plot = self$plot) {\n ans <- ggproto_parent(PatchGgplot, self)$patch_gtable(plot = plot)\n # re-define the draw method, we assign new class\n ans <- add_class(ans, \"ggalignMarkGtable\")\n ans$ggalign_link_data <- plot$ggalign_link_data\n ans\n },\n add_plot = function(self, gt, plot, t, l, b, r, name, z = 2L) {\n gtable_add_grob(\n gt,\n grobs = plot,\n # t = 8, l = 6, b = 14, r = 12\n # t = t + 7L, l = l + 5L, b = b - 6L, r = r - 5L,\n t = t + TOP_BORDER, l = l + LEFT_BORDER,\n name = name, z = z\n )\n },\n add_background = function(self, gt, bg, t, l, b, r, name, z = 1L) {\n gtable_add_grob(\n gt,\n grobs = bg,\n t = t + TOP_BORDER, l = l + LEFT_BORDER,\n name = name, z = z\n )\n },\n get_sizes = function(self, free = NULL, gt = self$gt) {\n ggproto_parent(PatchGgplot, self)$get_sizes(.tlbr, gt = gt)\n },\n align_border = function(self, t = NULL, l = NULL, b = NULL, r = NULL,\n gt = self$gt) {\n gt # free from alignment\n }\n)\n\n# preDraw:\n# - makeContext\n# - pushvpgp\n# - preDrawDetails: by default, do noting\n# makeContent:\n# drawDetails:\n# postDraw:\n# - postDrawDetails: by default, do noting\n# - popgrobvp\n#' @importFrom grid makeContent unit convertHeight convertWidth viewport\n#' @importFrom stats reorder\n#' @export\nmakeContent.ggalignMarkGtable <- function(x) {\n # Grab viewport information\n width <- convertWidth(unit(1, \"npc\"), \"mm\", valueOnly = TRUE)\n height <- convertHeight(unit(1, \"npc\"), \"mm\", valueOnly = TRUE)\n\n # Grab grob metadata\n plot_widths <- compute_null_width(.subset2(x, \"widths\"),\n valueOnly = TRUE\n )\n plot_widths <- scales::rescale(plot_widths, c(0, 1), from = c(0, width))\n plot_heights <- compute_null_height(.subset2(x, \"heights\"),\n valueOnly = TRUE\n )\n plot_heights <- scales::rescale(plot_heights, c(0, 1), from = c(0, height))\n\n panel_loc <- find_panel(x)\n data <- .subset2(x, \"ggalign_link_data\")\n full_data1 <- .subset2(data, \"full_data1\")\n full_data2 <- .subset2(data, \"full_data2\")\n direction <- .subset2(data, \"direction\")\n link_index_list <- .subset2(data, \"link_index\")\n data_index_list <- .subset2(data, \"data_index\")\n obs_size <- .subset2(data, \"obs_size\")\n\n # prepare output for current for loop\n coords <- vector(\"list\", 2L)\n names(coords) <- c(\"hand1\", \"hand2\")\n for (link in names(coords)) {\n link_index <- lapply(link_index_list, .subset2, link)\n data_index <- lapply(data_index_list, .subset2, link)\n # early exit and step into next cycle if no link\n if (all(vapply(link_index, is.null, logical(1L), USE.NAMES = FALSE))) {\n coords[link] <- list(link_index)\n next\n }\n full_breaks <- switch(link,\n hand1 = full_data1,\n hand2 = full_data2\n )\n\n spacing <- .subset2(data, switch(link,\n hand1 = \"spacing1\",\n hand2 = \"spacing2\"\n ))\n\n # each value represent an `observation`, for panel space, we use `NA`\n # obs arranged from left to top, and from bottom to top\n points <- unlist(vec_interleave(full_breaks, list(NA)), FALSE, FALSE)\n # remove the last panel space, shouldn't exist\n points <- points[-length(points)]\n sizes <- numeric(length(points))\n n_spacing <- length(full_breaks) - 1L\n\n # then, we define the link grobs\n if (is_horizontal(direction)) { # the link should be in left or right\n spacing <- convertHeight(spacing, \"mm\", valueOnly = TRUE)\n spacing <- scales::rescale(spacing, c(0, 1), from = c(0, height))\n sizes[is.na(points)] <- spacing\n obs_height <- (1 - spacing * n_spacing) / sum(!is.na(points))\n sizes[!is.na(points)] <- obs_height # nobs\n yend <- cumsum(sizes)\n link_x <- switch(link,\n hand1 = 0,\n hand2 = 1\n )\n # by default, the height for each observation is `1`,\n # if we define obs size, we just re-scale it\n removed <- (1 - obs_size) * obs_height\n link_coord <- data_frame0(\n x = link_x, xend = link_x,\n y = yend - sizes + removed / 2L,\n yend = yend - removed / 2L\n )\n link_coord <- vec_slice(link_coord, !is.na(points))\n\n # from bottom to the top, following the ordering of the `breaks`\n panel_index <- seq(\n from = .subset2(panel_loc, \"b\"),\n to = .subset2(panel_loc, \"t\"),\n length.out = length(link_index)\n )\n l_border <- plot_widths[seq_len(.subset2(panel_loc, \"l\") - 1L)]\n r_border <- plot_widths[-seq_len(.subset2(panel_loc, \"r\"))]\n\n # for a gtable, heights are from top to the bottom,\n # we reverse the heights\n # we have reversed the `plot_cum_heights`, so the ordering index\n # should also be reversed\n panel_index <- nrow(x) - panel_index + 1L\n panel_yend <- cumsum(rev(plot_heights))\n panel_x <- switch(link,\n hand1 = sum(l_border),\n hand2 = 1 - sum(r_border)\n )\n panel_coord <- data_frame0(\n x = panel_x,\n xend = panel_x,\n y = (panel_yend - rev(plot_heights))[panel_index],\n yend = panel_yend[panel_index]\n )\n } else { # the link should be in top or bottom\n spacing <- convertWidth(spacing, \"mm\", valueOnly = TRUE)\n spacing <- scales::rescale(spacing, c(0, 1), from = c(0, width))\n sizes[is.na(points)] <- spacing\n obs_width <- (1 - spacing * n_spacing) / sum(!is.na(points))\n sizes[!is.na(points)] <- obs_width\n xend <- cumsum(sizes)\n link_y <- switch(link,\n hand1 = 1,\n hand2 = 0\n )\n # by default, the width for each observation is `1`,\n # if we define obs size, we just re-scale it\n removed <- (1 - obs_size) * obs_width\n link_coord <- data_frame0(\n x = xend - sizes + removed / 2L,\n xend = xend - removed / 2L,\n y = link_y, yend = link_y\n )\n link_coord <- vec_slice(link_coord, !is.na(points))\n\n panel_index <- seq(\n from = .subset2(panel_loc, \"l\"),\n to = .subset2(panel_loc, \"r\"),\n length.out = length(link_index)\n )\n t_border <- plot_heights[seq_len(.subset2(panel_loc, \"t\") - 1L)]\n b_border <- plot_heights[-seq_len(.subset2(panel_loc, \"b\"))]\n panel_xend <- cumsum(plot_widths)\n panel_y <- switch(link,\n hand1 = 1 - sum(t_border),\n hand2 = sum(b_border)\n )\n panel_coord <- data_frame0(\n x = (panel_xend - plot_widths)[panel_index],\n xend = panel_xend[panel_index],\n y = panel_y, yend = panel_y\n )\n }\n hand <- switch(link,\n hand1 = switch_direction(direction, \"left\", \"top\"),\n hand2 = switch_direction(direction, \"right\", \"bottom\")\n )\n nms <- names(link_index)\n link_panels <- vec_rep_each(names(full_breaks), list_sizes(full_breaks))\n coords[[link]] <- lapply(seq_along(link_index), function(i) {\n l_index <- .subset2(link_index, i)\n if (is.null(l_index)) return(NULL) # styler: off\n d_index <- .subset2(data_index, i)\n link <- vec_slice(link_coord, l_index)\n link$link_id <- nms[i]\n link$link_panel <- reorder(\n vec_slice(link_panels, l_index), l_index,\n order = FALSE\n )\n link$link_index <- l_index\n link$.hand <- hand\n link$.index <- d_index\n panel <- vec_slice(panel_coord, i)\n list(panel = panel, link = link)\n })\n }\n coords <- vec_interleave(\n .subset2(coords, \"hand1\"),\n .subset2(coords, \"hand2\")\n )\n coords <- list_drop_empty(coords)\n draw <- .subset2(data, \"draw\")\n if (is.gList(grob <- draw(coords))) {\n grob <- gTree(children = grob)\n }\n\n if (is.grob(grob)) {\n layout <- .subset2(x, \"layout\")\n panels <- layout[\n grepl(\"^panel\", .subset2(layout, \"name\")), ,\n drop = FALSE\n ]\n x <- gtable_add_grob(\n x,\n grobs = grob,\n t = 1L, l = 1L, b = -1L, r = -1L,\n # always draw with panel area\n z = min(panels$z)\n )\n }\n NextMethod()\n}\n"], ["/ggalign/R/layout-quad-.R", "#' Arrange plots in the quad-side of a main plot\n#'\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' This function arranges plots around the quad-sides of a main plot, aligning\n#' both horizontal and vertical axes, and can handle either discrete or\n#' continuous variables.\n#'\n#' - If `xlim` is provided, a continuous variable will be required and aligned\n#' in the vertical direction. Otherwise, a discrete variable will be required\n#' and aligned.\n#' - If `ylim` is provided, a continuous variable will be required and aligned\n#' in the horizontal direction. Otherwise, a discrete variable will be\n#' required and aligned.\n#'\n#' The `quad_discrete` is a special case where both `xlim` and `ylim` are not\n#' provided.\n#'\n#' The `quad_continuous` is a special case where both `xlim` and `ylim` are\n#' provided.\n#'\n#' For historical reasons, the following aliases are available:\n#' - `quad_alignh`: Align discrete variables in the horizontal direction and\n#' continuous variables in vertical direction.\n#' - `quad_alignv`: Align discrete variables in the vertical direction and\n#' continuous variables in horizontal direction.\n#' - `quad_alignb` is an alias for `quad_discrete`.\n#' - `quad_free` is an alias for `quad_continuous`.\n#'\n#' @param data `r rd_layout_data()`. By default, this will attempt\n#' to inherit from the parent layout.\n#'\n#' If both `xlim` and `ylim` are provided, a `data frame` is required, and\n#' [`fortify_data_frame()`] will be used to convert the data to a data frame.\n#' When inherited by an annotation stack, no transposition will be applied.\n#'\n#' Otherwise, a `matrix` is required, and [`fortify_matrix()`] will be used to\n#' convert the data to a matrix. When inherited by the column annotation\n#' stack, the data will be transposed.\n#' @param mapping Default list of aesthetic mappings to use for main plot in the\n#' layout. If not specified, must be supplied in each layer added to the main\n#' plot.\n#' @param xlim,ylim A [`continuous_limits()`] object specifying the left/lower\n#' limit and the right/upper limit of the scale. Used to align the continuous\n#' axis.\n#' @param width,height The relative width/height of the main plot, can be a\n#' [`unit`][grid::unit] object.\n#' @inheritParams stack_layout\n#' @inheritParams align\n#' @return A `QuadLayout` object.\n#' @section ggplot2 specification:\n#' If either `xlim` or `ylim` is not provided, the data input will be converted\n#' to a matrix using [`fortify_matrix()`], and the data in the underlying main\n#' plot will contain the following columns:\n#'\n#' - `.panel_x` and `.panel_y`: the column and row panel groups.\n#'\n#' - `.x` and `.y`: an integer index of `x` and `y` coordinates\n#'\n#' - `.discrete_x` and `.discrete_y`: a factor of the data labels (only\n#' applicable when `.row_names` and `.column_names` exists).\n#'\n#' - `.row_names` and `.column_names`: A character of the row and column names\n#' of the original matrix (only applicable when names exist).\n#'\n#' - `.row_index` and `.column_index`: the row and column index of the original\n#' matrix.\n#'\n#' - `value`: the actual matrix value.\n#'\n#' Otherwise, the data input will be used for the main plot.\n#'\n#' @export\nquad_layout <- function(data = waiver(), mapping = aes(),\n xlim = waiver(), ylim = waiver(),\n ...,\n theme = NULL, active = NULL,\n width = NA, height = NA) {\n if (is.waive(xlim) && is.waive(ylim)) {\n quad_discrete(\n data = data, mapping = mapping,\n ..., active = active, theme = theme,\n width = width, height = height\n )\n } else if (!is.waive(xlim) && !is.waive(ylim)) {\n quad_continuous(\n data = data, mapping = mapping, xlim = xlim, ylim = ylim,\n ..., active = active, theme = theme,\n width = width, height = height\n )\n } else {\n data <- fortify_matrix(data = data, ...)\n new_quad_layout(\n name = \"quad_layout\",\n data = data, ylim = ylim, xlim = xlim,\n mapping = mapping, active = active, theme = theme,\n width = width, height = height\n )\n }\n}\n\n#' @export\n#' @rdname quad_layout\nquad_alignh <- function(..., ylim = waiver()) {\n quad_layout(..., xlim = NULL, ylim = ylim)\n}\n\n#' @export\n#' @rdname quad_layout\nquad_alignv <- function(..., xlim = waiver()) {\n quad_layout(..., xlim = xlim, ylim = NULL)\n}\n\n##########################################################\n#' @export\n#' @rdname quad_layout\nquad_discrete <- function(data = waiver(), mapping = aes(),\n ...,\n theme = NULL, active = NULL,\n width = NA, height = NA) {\n UseMethod(\"quad_discrete\")\n}\n\n#' @export\n#' @rdname quad_layout\n#' @usage NULL\nquad_alignb <- quad_discrete\n\n#' @export\nquad_discrete.default <- function(data = waiver(), mapping = aes(),\n ...,\n theme = NULL, active = NULL,\n width = NA, height = NA) {\n data <- fortify_matrix(data = data, ...)\n new_quad_layout(\n name = \"quad_discrete\", data = data, xlim = waiver(), ylim = waiver(),\n mapping = mapping, active = active, theme = theme,\n width = width, height = height\n )\n}\n\n#' @export\nquad_discrete.uneval <- function(data, ...) {\n cli_abort(c(\n \"{.arg data} cannot be {.obj_type_friendly {data}}\",\n \"i\" = \"Have you misspelled the {.arg data} argument in {.fn quad_discrete}\"\n ))\n}\n\n#############################################################\n#' @export\n#' @rdname quad_layout\nquad_continuous <- function(data = waiver(), mapping = aes(),\n xlim = NULL, ylim = NULL,\n ...,\n theme = NULL, active = NULL,\n width = NA, height = NA) {\n UseMethod(\"quad_continuous\")\n}\n\n#' @usage NULL\n#' @export\n#' @rdname quad_layout\nggside <- quad_continuous\n\n#' @usage NULL\n#' @export\n#' @rdname quad_layout\nquad_free <- quad_continuous\n\n#' @export\nquad_continuous.default <- function(data = waiver(), mapping = aes(),\n xlim = NULL, ylim = NULL,\n ...,\n theme = NULL, active = NULL,\n width = NA, height = NA) {\n xlim <- xlim %|w|% NULL\n ylim <- ylim %|w|% NULL\n data <- fortify_data_frame(data = data, ...)\n new_quad_layout(\n name = \"quad_continuous\",\n data = data, xlim = xlim, ylim = ylim,\n mapping = mapping, active = active, theme = theme,\n width = width, height = height\n )\n}\n\n#' @export\nquad_continuous.uneval <- function(data, ...) {\n cli_abort(c(\n \"{.arg data} cannot be {.obj_type_friendly {data}}\",\n \"i\" = \"Have you misspelled the {.arg data} argument in {.fn quad_free}\"\n ))\n}\n\n#####################################################\n#' @importFrom ggplot2 ggplot\n#' @importFrom methods new\nnew_quad_layout <- function(name, data, xlim = waiver(), ylim = waiver(),\n mapping = aes(), theme = NULL, active = NULL,\n width = NA, height = NA,\n class = \"QuadLayout\",\n call = caller_call()) {\n if (!is.waive(xlim)) assert_limits(xlim, call = call)\n if (!is.waive(ylim)) assert_limits(ylim, call = call)\n if (is.waive(xlim) || is.waive(ylim)) {\n # If we need align discrete variables, data cannot be `NULL` and\n # must be provided, here, we convert it to waiver() to indicate\n # inherit from the parent layout\n data <- data %||% waiver()\n if (!is.waive(data) && !is.function(data)) {\n nrows <- NROW(data)\n ncols <- ncol(data)\n\n # for data has dimention but one dimention is 0\n # as.matrix(data.frame(row.names = letters))\n if (nrows == 0L || ncols == 0L) {\n cli_abort(\"empty data is no allowed\")\n }\n } else {\n nrows <- NULL\n ncols <- NULL\n }\n }\n horizontal <- ylim %|w|% discrete_design(nobs = nrows)\n vertical <- xlim %|w|% discrete_design(nobs = ncols)\n\n # always remove default axis titles\n # https://stackoverflow.com/questions/72402570/why-doesnt-gplot2labs-overwrite-update-the-name-argument-of-scales-function\n # There are multiple ways to set labels in a plot, which take different\n # priorities. Here are the priorities from highest to lowest.\n # 1. The guide title.\n # 2. The scale name.\n # 3. The `labs()` function.\n # 4. The captured expression in aes().\n plot <- ggplot(mapping = mapping) +\n ggplot2::labs(x = NULL, y = NULL)\n\n if (!is.null(theme)) assert_s3_class(theme, \"theme\", call = call)\n # for `QuadLayout`, we use `NULL` to inherit data from parent layout\n # since `QuadLayout` must have data, and won't be waiver()\n # if inherit from the parent layout data, we'll inherit\n # the action data function\n schemes <- default_schemes(\n if (is.null(data)) waiver() else NULL,\n th = theme_no_strip()\n )\n\n # check arguments -----------------------------------\n width <- check_size(width, call = call)\n height <- check_size(height, call = call)\n assert_active(active, call = call)\n\n # Here we use S4 object to override the double dispatch of `+.gg` method\n new(\n class,\n # used by the layout\n data = data, theme = theme,\n schemes = schemes,\n plot_active = update_active(active, new_active(use = TRUE)),\n name = name,\n # used by the main body\n body_schemes = default_schemes(waiver()),\n # following parameters can be controlled by `quad_switch`\n width = width, height = height,\n # following parameters are used internally\n plot = plot, horizontal = horizontal, vertical = vertical\n )\n}\n\n# Used to create the QuadLayout\n#' @include layout-.R\nmethods::setClass(\n \"QuadLayout\",\n contains = \"LayoutProto\",\n list(\n data = \"ANY\", plot = \"ANY\", body_schemes = \"list\", name = \"character\",\n # parameters for main body\n width = \"ANY\", height = \"ANY\",\n # Used to align axis\n horizontal = \"ANY\", vertical = \"ANY\",\n # top, left, bottom, right must be a StackLayout object.\n top = \"ANY\", left = \"ANY\", bottom = \"ANY\", right = \"ANY\",\n # If we regard `QuadLayout` as a plot, and put it into the stack\n # layout, we need following arguments to control it's behavour\n plot_active = \"ANY\"\n ),\n prototype = list(\n # used by QuadLayout\n top = NULL, left = NULL, bottom = NULL, right = NULL\n )\n)\n\n#' @export\nis_layout_discrete.QuadLayout <- function(x, direction, ...) {\n is_discrete_design(slot(x, direction))\n}\n\n#' @export\nis_layout_continuous.QuadLayout <- function(x, direction, ...) {\n is_continuous_design(slot(x, direction))\n}\n"], ["/ggalign/R/ggplot-helper.R", "# Exported function for ggplot2\n# Usually a quick shortcuts to define something\n#\n#' Remove axis elements\n#'\n#' @param axes Which axes elements should be removed? A string containing\n#' one or more of `r oxford_and(c(.tlbr, \"x\", \"y\"))`.\n#' @param text If `TRUE`, will remove the axis labels.\n#' @param ticks If `TRUE`, will remove the axis ticks.\n#' @param title If `TRUE`, will remove the axis title.\n#' @param line If `TRUE`, will remove the axis line.\n#' @return A [`theme()`][ggplot2::theme] object.\n#' @examples\n#' p <- ggplot() +\n#' geom_point(aes(x = wt, y = qsec), data = mtcars)\n#' p + theme_no_axes()\n#' p + theme_no_axes(\"b\")\n#' p + theme_no_axes(\"l\")\n#' @importFrom rlang inject\n#' @importFrom ggplot2 theme element_blank\n#' @export\ntheme_no_axes <- function(axes = \"xy\", text = TRUE, ticks = TRUE,\n title = TRUE, line = FALSE) {\n assert_string(axes, empty_ok = FALSE)\n if (grepl(\"[^tlbrxy]\", axes)) {\n cli_abort(sprintf(\n \"{.arg axes} can only contain the %s characters\",\n oxford_and(c(.tlbr, \"x\", \"y\"))\n ))\n }\n axes <- split_position(axes)\n el <- list(text = text, ticks = ticks, title = title, line = line)\n el <- names(el)[vapply(el, isTRUE, logical(1L), USE.NAMES = FALSE)]\n el_axis <- el_pos <- NULL\n if (length(positions <- vec_set_intersect(axes, .tlbr))) {\n positions <- .subset(\n c(t = \"top\", l = \"left\", b = \"bottom\", r = \"right\"),\n positions\n )\n el_pos <- vec_expand_grid(pos = positions, el = el)\n el_pos <- paste(\"axis\",\n .subset2(el_pos, \"el\"),\n if_else(.subset2(el_pos, \"pos\") %in% c(\"top\", \"bottom\"), \"x\", \"y\"),\n .subset2(el_pos, \"pos\"),\n sep = \".\"\n )\n }\n if (length(axes <- vec_set_intersect(axes, c(\"x\", \"y\")))) {\n el_axis <- vec_expand_grid(axes = axes, el = el)\n el_axis <- paste(\"axis\",\n .subset2(el_axis, \"el\"), .subset2(el_axis, \"axes\"),\n sep = \".\"\n )\n }\n el <- c(el_axis, el_pos)\n el <- vec_set_names(vec_rep(list(element_blank()), length(el)), el)\n inject(theme(!!!el, validate = FALSE))\n}\n\n##########################################################################\n#' Theme Polygon elements\n#'\n#' Draw polygon.\n#'\n#' @inheritParams ggplot2::element_rect\n#' @inheritParams geom_rect3d\n#' @inheritParams ggplot2::fill_alpha\n#' @param linewidth Line size in `mm`.\n#' @param linetype Line type for lines. An integer (0:8), a name (blank, solid,\n#' dashed, dotted, dotdash, longdash, twodash), or a string with an even number\n#' (up to eight) of hexadecimal digits which give the lengths in consecutive\n#' positions in the string.\n#' @seealso [`element_rect`][ggplot2::element_rect]\n#' @return A `element_polygon` object\n#' @export\nelement_polygon <- function(fill = NULL, colour = NULL, linewidth = NULL,\n linetype = NULL, alpha = NULL, lineend = NULL,\n linejoin = NULL, linemitre = NULL, color = NULL,\n inherit.blank = FALSE) {\n if (!is.null(color)) colour <- color\n structure(\n list(\n fill = fill, colour = colour, alpha = alpha,\n linewidth = linewidth, linetype = linetype,\n lineend = lineend, linejoin = linejoin, linemitre = linemitre,\n inherit.blank = inherit.blank\n ),\n class = c(\"ggalign_element_polygon\", \"element_polygon\", \"element\")\n )\n}\n\n#' @importFrom utils packageVersion\n#' @importFrom grid gpar\n#' @importFrom ggplot2 element_grob fill_alpha\n#' @export\nelement_grob.ggalign_element_polygon <- function(element,\n x = c(0, 0.5, 1, 0.5),\n y = c(0.5, 1, 0.5, 0),\n fill = NULL,\n colour = NULL,\n linewidth = NULL,\n linetype = NULL, ...) {\n if (packageVersion(\"ggplot2\") > \"3.5.2\") {\n gp <- ggfun(\"gg_par\")(\n lwd = linewidth, col = colour, fill = fill, lty = linetype\n )\n element_gp <- ggfun(\"gg_par\")(\n lwd = element$linewidth,\n col = element$colour,\n fill = fill_alpha(element$fill, element$alpha %||% NA),\n lty = element$linetype,\n lineend = element$lineend,\n linejoin = element$linejoin,\n linemitre = element$linemitre\n )\n } else {\n gp <- gpar(\n lwd = ggfun(\"len0_null\")(linewidth * .pt),\n col = colour,\n fill = fill,\n lty = linetype\n )\n element_gp <- gpar(\n lwd = ggfun(\"len0_null\")(element$linewidth * .pt),\n col = element$colour,\n fill = fill_alpha(element$fill, element$alpha %||% NA),\n lty = element$linetype,\n lineend = element$lineend,\n linejoin = element$linejoin,\n linemitre = element$linemitre\n )\n }\n grid::polygonGrob(\n x = x, y = y,\n gp = ggfun(\"modify_list\")(element_gp, gp), ...\n )\n}\n\n#' Theme curve elements\n#'\n#' Draw curve.\n#'\n#' @inheritParams element_polygon\n#' @inheritParams grid::curveGrob\n#' @param arrow.fill Fill colour for arrows.\n#' @return A `element_curve` object\n#' @export\nelement_curve <- function(colour = NULL, linewidth = NULL, linetype = NULL,\n lineend = NULL, color = NULL, curvature = NULL,\n angle = NULL, ncp = NULL, shape = NULL,\n arrow = NULL, arrow.fill = NULL,\n inherit.blank = FALSE) {\n colour <- color %||% colour\n arrow.fill <- arrow.fill %||% colour\n arrow <- arrow %||% FALSE\n structure(\n list(\n colour = colour, linewidth = linewidth, linetype = linetype,\n lineend = lineend, curvature = curvature, angle = angle,\n ncp = ncp, shape = shape, arrow = arrow, arrow.fill = arrow.fill,\n inherit.blank = inherit.blank\n ),\n class = c(\"ggalign_element_curve\", \"element_curve\", \"element\")\n )\n}\n\n#' @importFrom grid gpar gTree gList\n#' @importFrom ggplot2 element_grob\n#' @export\nelement_grob.ggalign_element_curve <- function(element, x = 0:1, y = 0:1,\n colour = NULL, linewidth = NULL, linetype = NULL, lineend = NULL,\n arrow.fill = NULL,\n default.units = \"npc\",\n id = NULL,\n id.lengths = NULL, ...) {\n arrow <- if (is.logical(element$arrow) && !element$arrow) {\n NULL\n } else {\n element$arrow\n }\n if (is.null(arrow)) {\n arrow.fill <- colour\n element$arrow.fill <- element$colour\n }\n # The gp settings can override element_gp\n gp <- gpar(\n col = colour,\n fill = arrow.fill %||% colour,\n lwd = ggfun(\"len0_null\")(linewidth * .pt),\n lty = linetype,\n lineend = lineend\n )\n element_gp <- gpar(\n col = element$colour,\n fill = element$arrow.fill %||% element$colour,\n lwd = ggfun(\"len0_null\")(element$linewidth * .pt),\n lty = element$linetype,\n lineend = element$lineend\n )\n gp <- ggfun(\"modify_list\")(element_gp, gp)\n if (is.null(id)) {\n if (is.null(id.lengths)) {\n id <- vec_rep(1L, length(x))\n } else {\n id <- vec_rep_each(seq_along(id.lengths), id.lengths)\n }\n }\n index_list <- .subset2(vec_split(seq_along(x), id), \"val\")\n ans <- lapply(index_list, function(index) {\n grid::curveGrob(\n vec_slice(x, index),\n vec_slice(y, index),\n default.units = default.units,\n gp = gp[index],\n curvature = element$curvature,\n angle = element$angle,\n ncp = element$ncp,\n shape = element$shape,\n arrow = arrow,\n square = FALSE, squareShape = 1,\n inflect = FALSE, open = TRUE,\n ...\n )\n })\n gTree(children = inject(gList(!!!ans)))\n}\n\n##########################################################################\nelement_lengths <- function(.el, .fn, ...) {\n fields <- element_vec_fields(.el)\n if (is.null(fields)) 0L\n lengths(.el[fields])\n}\n\n#' Apply a function to the fields of an element object\n#'\n#' @description\n#' For an [`element`][ggplot2::element_blank] object, some fields are\n#' vectorized, while others are not. This function allows you to apply a\n#' function to the vectorized fields.\n#'\n#' The following helper functions are available:\n#'\n#' - `element_rep`: Applies [`rep()`].\n#' - `element_rep_len`: Applies [`rep_len()`].\n#' - `element_vec_recycle`: Applies [`vec_recycle()`][vctrs::vec_recycle].\n#' - `element_vec_rep`: Applies [`vec_rep()`][vctrs::vec_rep].\n#' - `element_vec_rep_each`: Applies [`vec_rep_each()`][vctrs::vec_rep_each].\n#' - `element_vec_slice`: Applies [`vec_slice()`][vctrs::vec_slice].\n#'\n#' @param .el An [`element`][ggplot2::element_blank] object.\n#' @param .fn The function to be applied to the vectorized fields of the element\n#' object.\n#' @param ... Additional arguments passed on to `fn`.\n#' @export\nelement_vec <- function(.el, .fn, ...) {\n fields <- element_vec_fields(.el)\n if (is.null(fields)) {\n return(.el)\n }\n .el[fields] <- lapply(.el[fields], function(value) {\n if (!is.null(value)) value <- .fn(value, ...)\n value\n })\n .el\n}\n\n#' @export\n#' @rdname element_vec\nelement_rep <- function(.el, ...) element_vec(.el, rep, ...)\n\n#' @param length.out Non-negative integer. The desired length of the output\n#' vector. Other inputs will be coerced to a double vector and the first element\n#' taken. Ignored if `NA` or invalid.\n#' @export\n#' @rdname element_vec\nelement_rep_len <- function(.el, length.out, ...) {\n element_vec(.el, rep_len, ..., length.out = length.out)\n}\n\n#' @inheritParams vctrs::vec_recycle\n#' @export\n#' @rdname element_vec\nelement_vec_recycle <- function(.el, size, ...) {\n element_vec(.el, vec_recycle, size = size, ...)\n}\n\n#' @inheritParams vctrs::vec_rep\n#' @export\n#' @rdname element_vec\nelement_vec_rep <- function(.el, times, ...) {\n element_vec(.el, vec_rep, times = times, ...)\n}\n\n#' @export\n#' @rdname element_vec\nelement_vec_rep_each <- function(.el, times, ...) {\n element_vec(.el, vec_rep_each, times = times, ...)\n}\n\n#' @inheritParams vctrs::vec_slice\n#' @importFrom grid is.unit\n#' @export\n#' @rdname element_vec\nelement_vec_slice <- function(.el, i, ...) {\n element_vec(.el, function(x) {\n if (is.unit(x)) x[i, ...] else vec_slice(x, i, ...)\n })\n}\n\nelement_vec_fields <- function(el) UseMethod(\"element_vec_fields\")\n\n#' @export\nelement_vec_fields.ggalign_element_polygon <- function(el) {\n c(\n \"fill\", \"colour\", \"linewidth\", \"linetype\",\n \"lineend\", \"linejoin\", \"linemitre\", \"alpha\"\n )\n}\n\n#' @export\nelement_vec_fields.element_blank <- function(el) NULL\n\n#' @export\nelement_vec_fields.element_polygon <- function(el) {\n c(\"fill\", \"colour\", \"linewidth\", \"linetype\")\n}\n\n#' @export\nelement_vec_fields.element_point <- function(el) {\n c(\"colour\", \"shape\", \"size\", \"fill\", \"stroke\")\n}\n\n#' @export\nelement_vec_fields.element_rect <- function(el) {\n c(\"fill\", \"colour\", \"linewidth\", \"linetype\")\n}\n\n#' @export\nelement_vec_fields.element_line <- function(el) {\n c(\"colour\", \"linewidth\", \"linetype\", \"lineend\")\n}\n\n#' @export\nelement_vec_fields.element_text <- function(el) {\n c(\n \"family\", \"face\", \"colour\", \"size\", \"hjust\", \"vjust\",\n \"angle\", \"lineheight\"\n )\n}\n\n#' @export\nelement_vec_fields.default <- function(el) stop_input_type(el, \"an element\")\n\n######################################################\n#' Remove scale expansion\n#'\n#' @param borders Which border should be removed? A string containing\n#' one or more of `r oxford_and(c(.tlbr, \"x\", \"y\"))`.\n#' @return An object which can be added to ggplot.\n#' @export\nno_expansion <- function(borders = \"tlbr\") {\n assert_string(borders, empty_ok = FALSE)\n if (grepl(\"[^tlbrxy]\", borders)) {\n cli_abort(sprintf(\n \"{.arg borders} can only contain the %s characters\",\n oxford_and(c(.tlbr, \"x\", \"y\"))\n ))\n }\n borders <- .subset(list(\n t = \"top\", l = \"left\", b = \"bottom\", r = \"right\",\n x = c(\"left\", \"right\"), y = c(\"bottom\", \"top\")\n ), split_position(borders))\n borders <- vec_unique(unlist(borders, recursive = FALSE, use.names = FALSE))\n # expansion in x-axis\n structure(list(borders = borders), class = c(\"ggalign_no_expansion\"))\n}\n\n#' @importFrom ggplot2 ggplot_add ggproto ggproto_parent\n#' @export\nggplot_add.ggalign_no_expansion <- function(object, plot, object_name, ...) {\n borders <- .subset2(object, \"borders\")\n ParentLayout <- plot$layout\n\n # tricks to ensure remove `coord` won't remove `no_expansion()`\n plot$layout <- ggproto(NULL, ParentLayout,\n setup_panel_params = function(self) {\n ParentCoord <- self$coord\n self$coord <- ggproto(NULL, ParentCoord,\n setup_panel_params = function(self, scale_x, scale_y,\n params = list()) {\n if (!is.null(scale_x)) {\n expansion <- scale_x$expand %|w|%\n if (packageVersion(\"ggplot2\") > \"3.5.2\") {\n ggfun(\"default_expansion\")(\n scale_y,\n # for ggplot2 > 3.5.2, expand was passed by\n # params\n expand = params$expand[c(4, 2)]\n )\n } else {\n ggfun(\"default_expansion\")(\n scale_y,\n # for ggplot2 > 3.5.2, expand was passed by\n # params\n expand = self$expand\n )\n }\n if (any(borders == \"left\")) {\n expansion[1:2] <- 0\n }\n if (any(borders == \"right\")) {\n expansion[3:4] <- 0\n }\n scale_x$expand <- expansion\n }\n if (!is.null(scale_y)) {\n expansion <- scale_y$expand %|w|%\n if (packageVersion(\"ggplot2\") > \"3.5.2\") {\n ggfun(\"default_expansion\")(\n scale_y,\n # for ggplot2 > 3.5.2, expand was passed by\n # params\n expand = params$expand[c(3, 1)]\n )\n } else {\n ggfun(\"default_expansion\")(\n scale_y,\n # for ggplot2 > 3.5.2, expand was passed by\n # params\n expand = self$expand\n )\n }\n if (any(borders == \"bottom\")) {\n expansion[1:2] <- 0\n }\n if (any(borders == \"top\")) {\n expansion[3:4] <- 0\n }\n scale_y$expand <- expansion\n }\n ggproto_parent(ParentCoord, self)$setup_panel_params(\n scale_x = scale_x, scale_y = scale_y, params = params\n )\n }\n )\n ggproto_parent(ParentLayout, self)$setup_panel_params()\n }\n )\n plot\n}\n"], ["/ggalign/R/craft-align-order2.R", "#' Reorders layout observations based on specific statistics.\n#'\n#' @details\n#' `r lifecycle::badge('experimental')`\n#'\n#' The `align_order2()` function differs from `align_order()` in that the\n#' `weights` argument in `align_order()` must return atomic weights for each\n#' observation. In contrast, the `stat` argument in `align_order2()` can\n#' return more complex structures, such as [hclust][stats::hclust] or\n#' [dendrogram][stats::as.dendrogram], among others.\n#'\n#' Typically, you can achieve the functionality of `align_order2()` using\n#' `align_order()` by manually extracting the ordering information from\n#' the statistic.\n#'\n#' @param stat A statistical function which accepts a data and returns the\n#' statistic, which we'll call [`order2()`] to extract the ordering information.\n#' @param ... <[dyn-dots][rlang::dyn-dots]> Additional arguments passed to\n#' function provided in `stat` argument.\n#' @param data A `matrix`, `data frame`, or atomic vector used as the input for\n#' the `stat` function. Alternatively, you can specify a `function` (including\n#' purrr-like lambda syntax) that will be applied to the layout matrix,\n#' transforming it as necessary for statistic calculations. By default, it will\n#' inherit from the layout matrix.\n#' @inheritParams align_order\n#' @inheritSection align Discrete Axis Alignment\n#' @examples\n#' ggheatmap(matrix(rnorm(81), nrow = 9)) +\n#' anno_left() +\n#' align_order2(hclust2)\n#' @seealso [order2()]\n#' @importFrom ggplot2 waiver\n#' @importFrom rlang list2\n#' @export\nalign_order2 <- function(stat, ..., reverse = FALSE,\n strict = TRUE, data = NULL,\n active = NULL) {\n stat <- rlang::as_function(stat)\n assert_bool(strict)\n assert_bool(reverse)\n assert_active(active)\n active <- update_active(active, new_active(use = FALSE))\n align(\n align = AlignOrder2,\n stat = stat,\n params = list2(...),\n reverse = reverse,\n strict = strict,\n active = active,\n data = data\n )\n}\n\n#' @importFrom ggplot2 ggproto\n#' @importFrom rlang inject\nAlignOrder2 <- ggproto(\"AlignOrder2\", CraftAlign,\n interact_layout = function(self, layout) {\n layout <- ggproto_parent(CraftAlign, self)$interact_layout(layout)\n layout_data <- layout@data\n if (is.null(input_data <- self$input_data) ||\n is.waive(input_data)) { # inherit from the layout\n if (is.null(data <- layout_data)) {\n cli_abort(c(\n sprintf(\n \"you must provide {.arg data} in %s\",\n object_name(self)\n ),\n i = sprintf(\"no data was found in %s\", self$layout_name)\n ))\n }\n } else if (is.function(input_data)) {\n if (is.null(layout_data)) {\n cli_abort(c(\n sprintf(\n \"{.arg data} in %s cannot be a function\",\n object_name(self)\n ),\n i = sprintf(\"no data was found in %s\", self$layout_name)\n ))\n }\n data <- input_data(layout_data)\n } else {\n data <- input_data\n }\n\n design <- layout@design\n layout_nobs <- .subset2(design, \"nobs\")\n\n # we always regard rows as the observations\n if (is.null(layout_nobs)) {\n layout_nobs <- vec_size(data)\n if (layout_nobs == 0L) {\n cli_abort(\"{.arg data} cannot be empty\", call = self$call)\n }\n design[\"nobs\"] <- list(layout_nobs)\n layout@design <- design\n } else if (vec_size(data) != layout_nobs) {\n cli_abort(sprintf(\n \"%s (nobs: %d) is not compatible with the %s (nobs: %d)\",\n object_name, vec_size(data), layout_name, layout_nobs\n ))\n }\n\n # save the labels\n self$labels <- vec_names(data) %||% vec_names(layout_data)\n self$data <- ggalign_data_restore(data, layout_data)\n layout\n },\n compute = function(self, panel, index) {\n inject(self$stat(self$data, !!!self$params))\n },\n align = function(self, panel, index) {\n index <- vec_cast(\n order2(self$statistics), integer(),\n x_arg = \"stat\", call = self$call\n )\n assert_mismatch_nobs(\n self, vec_size(self$data), vec_size(index),\n arg = \"stat\"\n )\n if (self$reverse) index <- rev(index)\n assert_reorder(self, panel, index, self$strict)\n list(panel, index)\n },\n summary_align = function(self) c(TRUE, FALSE)\n)\n\n#' Ordering Permutation\n#'\n#' `order2` returns a permutation which rearranges its first argument into\n#' ascending order.\n#' @param x Any objects can be extracting ordering.\n#' @return An integer vector unless any of the inputs has `2^31` or more\n#' elements, when it is a double vector.\n#' @examples\n#' order2(hclust2(matrix(rnorm(100L), nrow = 10L)))\n#' @export\norder2 <- function(x) UseMethod(\"order2\")\n\n#' @export\n#' @rdname order2\norder2.hclust <- function(x) x$order\n\n#' @importFrom stats order.dendrogram\n#' @export\n#' @rdname order2\norder2.dendrogram <- function(x) order.dendrogram(x)\n\n#' @export\n#' @rdname order2\norder2.ser_permutation_vector <- function(x) {\n rlang::check_installed(\n \"seriation\", \"to extract order from `ser_permutation_vector`\"\n )\n getExportedValue(\"seriation\", \"get_order\")(x)\n}\n\n#' @export\n#' @rdname order2\norder2.ser_permutation <- function(x) {\n rlang::check_installed(\n \"seriation\", \"to extract order from `ser_permutation`\"\n )\n getExportedValue(\"seriation\", \"get_order\")(x)\n}\n\n#' @export\n#' @rdname order2\norder2.phylo <- function(x) {\n second <- x$edge[, 2L, drop = TRUE]\n second[second <= length(x$tip.label)]\n}\n"], ["/ggalign/R/craftbox-.R", "# Use S4 to override the double dispatch problem of ggplot2\n# And it's easy to convert a S4 Class to a S7 Class\nmethods::setClass(\n \"CraftBox\",\n list(\n plot = \"ANY\", # To avoid modify in place, we put plot in a slot\n active = \"ANY\",\n size = \"ANY\",\n schemes = \"ANY\",\n craftsman = \"ANY\" # `Craftsman` object\n )\n)\n\n#' Show `CraftBox` information\n#' @param object A `CraftBox` object.\n#' @return The input invisiblely.\n#' @keywords internal\nmethods::setMethod(\"show\", \"CraftBox\", function(object) {\n print(object)\n})\n\n#' @importFrom methods new\nnew_craftbox <- function(craftsman = NULL, ...,\n plot = NULL, active = NULL, size = NULL,\n schemes = NULL, call = caller_call()) {\n assert_active(active, allow_null = FALSE, call = call)\n if (is.null(size)) {\n size <- unit(NA, \"null\")\n } else {\n size <- check_size(size, call = call)\n }\n new(\n \"CraftBox\",\n # `call`: used to provide error message\n craftsman = ggproto(NULL, craftsman %||% Craftsman, ..., call = call),\n schemes = schemes %||% default_schemes(),\n plot = plot, active = active, size = size\n )\n}\n\n#' @export\nprint.CraftBox <- function(x, ...) {\n cat(x@craftsman$summary(x@plot), sep = \"\\n\")\n invisible(x)\n}\n\n#' @export\nplot.CraftBox <- function(x, ...) {\n cli_abort(sprintf(\"Cannot plot %s object directly\", object_name(x)))\n}\n\n#' @importFrom grid grid.draw\n#' @exportS3Method\ngrid.draw.CraftBox <- plot.CraftBox\n\n#' Add custom objects to ggalign plot\n#' @keywords internal\nmethods::setMethod(\"+\", c(\"CraftBox\", \"ANY\"), function(e1, e2) {\n if (missing(e2)) {\n cli_abort(c(\n \"Cannot use {.code {.Generic}} with a single argument.\",\n \"i\" = \"Did you accidentally put {.code {.Generic}} on a new line?\"\n ))\n }\n\n if (is.null(e2)) return(e1) # styler: off\n\n # Get the name of what was passed in as e2, and pass along so that it\n # can be displayed in error messages\n e2name <- paste(deparse(substitute(e2)), collapse = \" \")\n switch(.Generic, # nolint\n `+` = craftbox_add(e2, e1, e2name),\n stop_incompatible_op(.Generic, e1, e2)\n )\n})\n\n#' @importFrom methods is\nis_craftbox <- function(x) is(x, \"CraftBox\")\n\nis_cross_plot <- function(x) is_craftbox(x) && is_cross(x@craftsman)\n\nis_cross <- function(x) inherits(x, \"CraftCross\")\n\n#######################################################\n#' @importFrom ggplot2 ggproto\nCraftsman <- ggproto(\"Craftsman\",\n call = NULL,\n\n # following fields will be added when added to the layout\n in_linear = NULL,\n layout_name = NULL,\n direction = NULL,\n position = NULL, # for stack_layout() in quad_layout()\n labels = NULL,\n\n # A single boolean value indicates whether we should set facet and coord\n free_facet = FALSE,\n free_coord = FALSE,\n free_limits = FALSE,\n\n # we always prevent user from modifying the object in `$build_plot()` and\n # `$finish_plot()` methods\n locked = TRUE,\n lock = function(self) {\n assign(\"locked\", value = TRUE, envir = self)\n },\n unlock = function(self) {\n assign(\"locked\", value = FALSE, envir = self)\n },\n\n ############################################################\n # when added to the `Layout` object, will call following methods\n\n # we usually, define the `nobs` in `interact_layout`, since we can\n # act with the layout data in `interact_layout` method\n interact_layout = function(self, layout) layout,\n\n # we define the `panel` and `index` method in `setup_design` method\n setup_design = function(self, design) design,\n setup_plot = function(self, plot) plot,\n\n ##############################################################\n # Don't change the facet and coord in following methods\n build_plot = function(self, plot, design, extra_design = NULL,\n previous_design = NULL) {\n plot\n },\n finish_plot = function(self, plot, schemes, theme) {\n plot <- plot_add_schemes(plot, schemes)\n ggremove_margin(plot, self$direction) + theme_recycle()\n },\n\n # utils method to print the object, should return a character vector\n summary = function(self, plot) {\n cls <- class(self)\n cls <- cls[seq_len(which(cls == \"Craftsman\"))]\n sprintf(\"\", paste(cls, collapse = \" \"))\n }\n)\n\n# Used to lock the `Craftsman` object\n#' @export\n`$<-.Craftsman` <- function(x, name, value) {\n if (x$locked) {\n cli_abort(c(\n sprintf(\"Cannot modify %s\", object_name(x)),\n i = sprintf(\"%s is locked\", object_name(x))\n ), call = x$call)\n }\n NextMethod()\n}\n\n#################################################################\ncraftbox_add <- function(object, craftbox, object_name) {\n if (is.null(craftbox@plot)) {\n cli_abort(c(\n sprintf(\n \"Cannot add {.var {object_name}} to %s\",\n object_name(craftbox)\n ),\n i = sprintf(\"no plot found for %s\", object_name(craftbox))\n ))\n }\n UseMethod(\"craftbox_add\")\n}\n\n#' @importFrom ggplot2 ggplot_add\n#' @export\ncraftbox_add.default <- function(object, craftbox, object_name) {\n craftbox@plot <- ggplot_add(\n object,\n ggfun(\"plot_clone\")(craftbox@plot),\n object_name\n )\n craftbox\n}\n\n#' @export\ncraftbox_add.ggalign_scheme <- function(object, craftbox, object_name) {\n name <- ggalign_scheme_name(object)\n craftbox@schemes[name] <- list(update_scheme(\n object, .subset2(craftbox@schemes, name), object_name\n ))\n craftbox\n}\n\n######################################################################\nplot_build <- function(align, ..., schemes, theme) {\n plot <- align$build_plot(plot@plot, ...)\n align$finish_plot(plot, schemes, theme)\n}\n"], ["/ggalign/R/craft-align-hclust.R", "#' Reorder or Group observations based on hierarchical clustering\n#'\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' This function aligns observations within the layout according to a\n#' hierarchical clustering tree, enabling reordering or grouping of elements\n#' based on clustering results.\n#'\n#' @param data A matrix-like object. By default, it inherits from the layout\n#' `matrix`.\n#' @inheritParams align\n#' @inheritParams hclust2\n#' @param reorder_dendrogram A single boolean value indicating whether to\n#' reorder the dendrogram based on the means. Alternatively, you can provide a\n#' custom function that accepts an [`hclust`][stats::hclust] object and the data\n#' used to generate the tree, returning either an [`hclust`][stats::hclust] or\n#' [`dendrogram`][stats::as.dendrogram] object. Default is `FALSE`.\n#' @param reorder_group A single boolean value, indicates whether we should do\n#' Hierarchical Clustering between groups, only used when previous groups have\n#' been established. Default: `FALSE`.\n#' @param k An integer scalar indicates the desired number of groups.\n#' @param h A numeric scalar indicates heights where the tree should be cut.\n#' @param cutree A function used to cut the [`hclust`][stats::hclust] tree. It\n#' should accept four arguments: the [`hclust`][stats::hclust] tree object,\n#' `distance` (only applicable when `method` is a string or a function for\n#' performing hierarchical clustering), `k` (the number of clusters), and `h`\n#' (the height at which to cut the tree). By default,\n#' [`cutree()`][stats::cutree()] is used.\n#' @inheritSection align Discrete Axis Alignment\n#' @seealso [`hclust2()`]\n#' @examples\n#' # align_hclust won't add a dendrogram\n#' ggheatmap(matrix(rnorm(81), nrow = 9)) +\n#' anno_top() +\n#' align_hclust(k = 3L)\n#' @export\nalign_hclust <- function(distance = \"euclidean\",\n method = \"complete\",\n use_missing = \"pairwise.complete.obs\",\n reorder_dendrogram = FALSE,\n reorder_group = FALSE,\n k = NULL, h = NULL, cutree = NULL,\n data = NULL, active = NULL) {\n assert_active(active)\n active <- update_active(active, new_active(use = FALSE))\n .align_hclust(\n align = AlignHclust,\n distance = distance,\n method = method,\n use_missing = use_missing,\n reorder_dendrogram = reorder_dendrogram,\n reorder_group = reorder_group,\n k = k, h = h, cutree = cutree, data = data, active = active\n )\n}\n\n.align_hclust <- function(align, ..., plot = NULL,\n distance = \"euclidean\",\n method = \"complete\",\n use_missing = \"pairwise.complete.obs\",\n reorder_dendrogram = FALSE,\n reorder_group = FALSE,\n k = NULL, h = NULL, cutree = NULL,\n data = NULL, schemes = NULL, active = NULL,\n call = caller_call()) {\n reorder_dendrogram <- allow_lambda(reorder_dendrogram)\n if (!rlang::is_bool(reorder_dendrogram) &&\n !is.null(reorder_dendrogram) &&\n !is.function(reorder_dendrogram)) {\n cli_abort(\n \"{.arg reorder_dendrogram} must be a single boolean value or a function\",\n call = call\n )\n }\n assert_number_whole(k, allow_null = TRUE, call = call)\n assert_number_decimal(h, allow_null = TRUE, call = call)\n assert_bool(reorder_group, call = call)\n cutree <- allow_lambda(cutree)\n assert_(cutree, is.function, \"a function\", allow_null = TRUE, call = call)\n if (inherits(method, \"hclust\")) {\n if (vec_size(.subset2(method, \"order\")) == 0L) {\n cli_abort(\"{.cls hclust} defined in {.arg method} cannot be empty\",\n call = call\n )\n }\n } else if (inherits(method, \"dendrogram\")) {\n if (stats::nobs(method) == 0L) {\n cli_abort(\n \"{.cls dendrogram} defined in {.arg method} cannot be empty\",\n call = call\n )\n }\n }\n\n if (isTRUE(reorder_dendrogram)) {\n reorder_dendrogram <- function(tree, data) {\n if (!inherits(tree, \"dendrogram\")) {\n tree <- stats::as.dendrogram(tree)\n }\n reorder(x = tree, wts = rowMeans(data), agglo.FUN = mean)\n }\n } else if (is.function(reorder_dendrogram)) {\n user_reorder <- reorder_dendrogram\n reorder_dendrogram <- function(tree, data) {\n # we ensure, what we input for user is a `hclust` object.\n if (!inherits(tree, \"hclust\")) tree <- stats::as.hclust(tree)\n ans <- user_reorder(tree, data)\n if (!inherits(ans, \"hclust\") &&\n !inherits(ans, \"dendrogram\")) {\n cli_abort(\n \"{.fn reorder_dendrogram} must return a {.cls hclust} or {.cls dendrogram} object\",\n call = call\n )\n }\n ans\n }\n }\n\n align(\n align = align,\n distance = distance, method = method,\n use_missing = use_missing,\n reorder_dendrogram = reorder_dendrogram,\n reorder_group = reorder_group,\n k = k, h = h, cutree = cutree,\n active = active,\n ..., # additional fields to be added, used by align_dendro\n schemes = schemes %||% default_schemes(),\n data = data,\n plot = plot,\n call = call\n )\n}\n\n#' @importFrom ggplot2 ggproto aes\nAlignHclust <- ggproto(\"AlignHclust\", CraftAlign,\n interact_layout = function(self, layout) {\n if (inherits(self$method, \"hclust\") ||\n inherits(self$method, \"dendrogram\")) {\n layout <- ggproto_parent(CraftAlign, self)$interact_layout(layout)\n if (inherits(self$method, \"hclust\")) {\n nobs <- vec_size(.subset2(self$method, \"order\"))\n } else {\n nobs <- stats::nobs(self$method)\n }\n\n if (is.null(layout_nobs <- .subset2(layout@design, \"nobs\"))) {\n layout@design[\"nobs\"] <- list(nobs)\n } else {\n assert_mismatch_nobs(self, layout_nobs, nobs, arg = \"method\")\n }\n } else {\n layout <- ggproto_parent(AlignOrder2, self)$interact_layout(layout)\n }\n\n # initialize the internal parameters\n self$multiple_tree <- FALSE\n self$height <- NULL\n self$panel <- NULL\n layout\n },\n compute = function(self, panel, index) {\n if (!is.null(self$data) && vec_size(self$data) < 2L) {\n cli_abort(c(\n \"Cannot do Hierarchical Clustering\",\n i = \"must have >= 2 observations to cluster\"\n ), call = self$call)\n }\n\n # if the old panel exist, we do sub-clustering\n if (!is.null(panel) && is.null(self$k) && is.null(self$h) &&\n is.null(self$cutree)) {\n # in this way, we prevent sub-clustering\n if (inherits(self$method, \"hclust\") ||\n inherits(self$method, \"dendrogram\")) {\n cli_abort(\n \"{.arg method} cannot be a {.cls hclust} or {.cls dendrogram} when previous layout panel groups exist\",\n call = self$call\n )\n }\n children <- vector(\"list\", nlevels(panel))\n names(children) <- levels(panel)\n labels <- vec_names(self$data)\n\n # we do clustering within each group ---------------\n for (g in levels(panel)) {\n idx <- which(panel == g)\n gdata <- vec_slice(self$data, idx)\n if (vec_size(gdata) == 1L) {\n children[[g]] <- tree_one_node(idx, .subset(labels, idx))\n } else {\n child <- stats::as.dendrogram(hclust2(\n gdata,\n distance = self$distance,\n method = self$method,\n use_missing = self$use_missing\n ))\n # we restore the actual index of the original matrix\n child <- stats::dendrapply(child, function(x) {\n if (stats::is.leaf(x)) {\n ans <- .subset(idx, x)\n attributes(ans) <- attributes(x)\n ans\n } else {\n x\n }\n })\n if (is.function(self$reorder_dendrogram)) {\n child <- self$reorder_dendrogram(child, gdata)\n }\n children[[g]] <- child\n }\n }\n return(children) # can be a list of `dendrogram` or `hclust` or mix\n }\n hclust2(self$data, self$distance, self$method, self$use_missing)\n },\n #' @importFrom stats order.dendrogram\n align = function(self, panel, index) {\n statistics <- self$statistics\n if (!is.null(panel) && is.null(self$k) && is.null(self$h) &&\n is.null(self$cutree)) {\n # reordering the dendrogram ------------------------\n if (nlevels(panel) > 1L && self$reorder_group) {\n parent_levels <- levels(panel)\n parent_data <- t(sapply(parent_levels, function(g) {\n colMeans(vec_slice(self$data, panel == g), na.rm = TRUE)\n }))\n rownames(parent_data) <- parent_levels\n parent <- hclust2(\n parent_data,\n distance = self$distance,\n method = self$method,\n use_missing = self$use_missing\n )\n # reorder parent based on the parent tree\n if (is.function(self$reorder_dendrogram)) {\n parent <- self$reorder_dendrogram(parent, parent_data)\n }\n # we always ensure the parent is a dendrogram\n # since we'll call `merge_dendrogram()` which requires a\n # dendrogram\n parent <- stats::as.dendrogram(parent)\n panel <- factor(panel, parent_levels[order.dendrogram(parent)])\n # we don't cutree, so we won't draw the height line\n # self$draw_params$height <- attr(ans, \"cutoff_height\")\n } else {\n parent <- NULL\n }\n\n # merge children tree ------------------------------\n if (nlevels(panel) == 1L) {\n statistics <- .subset2(statistics, 1L)\n } else if (isTRUE(self$merge_dendro)) {\n # we have a function named merge_dendrogram(), so we use\n # `merge_dendro` as the argument name\n # `merge_dendrogram` will follow the order of the parent\n statistics <- lapply(statistics, stats::as.dendrogram)\n statistics <- merge_dendrogram(parent, statistics)\n } else {\n # if no parent tree, and we havn't merged the tree\n # we must manually reorder the dendrogram\n if (!is.null(parent)) {\n statistics <- .subset(statistics, levels(panel))\n }\n self$multiple_tree <- TRUE\n }\n } else {\n # hclust2() will attach the distance used\n distance <- attr(statistics, \"distance\")\n if (is.function(self$reorder_dendrogram)) {\n statistics <- self$reorder_dendrogram(statistics, self$data)\n }\n if (!is.null(self$k) || !is.null(self$h) || !is.null(self$cutree)) {\n if (is.null(cutree <- self$cutree)) {\n cutree <- function(tree, dist, k, h) {\n if (!is.null(k)) {\n stats::cutree(tree, k = k)\n } else {\n stats::cutree(tree, h = h)\n }\n }\n }\n # we need `hclust` object to cutree\n statistics <- stats::as.hclust(statistics)\n panel <- cutree(statistics, distance, self$k, self$h)\n # For `cutree`, we always respect the height user specified\n # For user defined function, we always calculate\n # height from the number of `panels`\n if (isTRUE(self$plot_cut_height)) {\n self$height <- self$h %||% cutree_k_to_h(\n statistics, vec_unique_count(panel)\n )\n }\n }\n }\n # save the modified `statistics`\n self$statistics <- statistics\n if (self$multiple_tree) {\n index <- unlist(lapply(statistics, order2), FALSE, FALSE)\n } else {\n index <- order2(statistics)\n }\n # reorder panel factor levels to following the dendrogram order\n if (!is.null(panel)) {\n panel <- factor(panel, unique(panel[index]))\n # save panel information, in case of user change it\n self$panel <- panel\n }\n list(panel, index)\n },\n summary_align = function(self, ...) {\n c(TRUE, !is.null(self$k) || !is.null(self$h) || !is.null(self$cutree))\n }\n)\n\n#' Generate Tree Structures with Hierarchical Clustering\n#'\n#' @param matrix A numeric matrix, or data frame.\n#' @param distance A string of distance measure to be used. This must be one of\n#' `\"euclidean\"`, `\"maximum\"`, `\"manhattan\"`, `\"canberra\"`, `\"binary\"` or\n#' `\"minkowski\"`. Correlation coefficient can be also used, including\n#' `\"pearson\"`, `\"spearman\"` or `\"kendall\"`. In this way, `1 - cor` will be used\n#' as the distance. In addition, you can also provide a [`dist`][stats::dist]\n#' object directly or a function return a [`dist`][stats::dist] object. Use\n#' `NULL`, if you don't want to calculate the distance.\n#' @param method A string of the agglomeration method to be used. This should be\n#' (an unambiguous abbreviation of) one of `\"ward.D\"`, `\"ward.D2\"`, `\"single\"`,\n#' `\"complete\"`, `\"average\"` (= UPGMA), `\"mcquitty\"` (= WPGMA), `\"median\"` (=\n#' WPGMC) or `\"centroid\"` (= UPGMC). You can also provide a function which\n#' accepts the calculated distance (or the input matrix if `distance` is `NULL`)\n#' and returns a [`hclust`][stats::hclust] object. Alternative, you can supply\n#' an object which can be coerced to [`hclust`][stats::hclust].\n#' @param use_missing An optional character string giving a method for computing\n#' covariances in the presence of missing values. This must be (an abbreviation\n#' of) one of the strings `\"everything\"`, `\"all.obs\"`, `\"complete.obs\"`,\n#' `\"na.or.complete\"`, or `\"pairwise.complete.obs\"`. Only used when `distance`\n#' is a correlation coefficient string.\n#' @seealso\n#' - [cor()][stats::cor]\n#' - [dist()][stats::dist]\n#' - [hclust()][stats::hclust]\n#' @examples\n#' hclust2(dist(USArrests), method = \"ward.D\")\n#' @return A [hclust][stats::hclust] object.\n#' @importFrom rlang is_string try_fetch\n#' @export\nhclust2 <- function(matrix, distance = \"euclidean\", method = \"complete\",\n use_missing = \"pairwise.complete.obs\") {\n method <- allow_lambda(method)\n if (!is_string(method) && !is.function(method)) {\n ans <- try_fetch(\n stats::as.hclust(method),\n error = function(cnd) {\n cli_abort(paste(\n \"{.arg method} can only be a {.cls string},\",\n \"{.cls function} or an object which can be coerced to\",\n \"{.cls hclust}.\"\n ), parent = cnd)\n }\n )\n return(ans)\n }\n if (is.null(distance)) {\n d <- matrix\n } else {\n d <- make_dist(matrix, distance, use_missing)\n }\n if (is_string(method)) {\n ans <- stats::hclust(d, method = method)\n } else if (is.function(method)) {\n ans <- method(d)\n ans <- try_fetch(\n stats::as.hclust(ans),\n error = function(cnd) {\n cli_abort(paste(\n \"{.arg method} must return an object which\",\n \"can be coerced to {.cls hclust}\"\n ), parent = cnd)\n }\n )\n }\n if (!is.null(distance)) attr(ans, \"distance\") <- d\n ans\n}\n\n#' @importFrom rlang arg_match0\nmake_dist <- function(matrix, distance, use_missing,\n arg = caller_arg(distance), call = caller_call()) {\n distance <- allow_lambda(distance)\n if (is_string(distance)) {\n distance <- arg_match0(distance, c(\n \"euclidean\", \"maximum\", \"manhattan\", \"canberra\",\n \"binary\", \"minkowski\", \"pearson\", \"spearman\", \"kendall\"\n ), arg_nm = arg, error_call = call)\n d <- switch(distance,\n euclidean = ,\n maximum = ,\n manhattan = ,\n canberra = ,\n binary = ,\n minkowski = stats::dist(matrix, method = distance),\n pearson = ,\n spearman = ,\n kendall = stats::as.dist(\n 1 - stats::cor(t(matrix), use = use_missing, method = distance)\n ),\n cli_abort(\"Unsupported {.arg {arg}} specified\", call = call)\n )\n } else if (is.function(distance)) {\n if (!inherits(d <- distance(matrix), \"dist\")) {\n cli_abort(\n \"{.arg {arg}} must return a {.cls dist} object\",\n call = call\n )\n }\n } else if (inherits(distance, \"dist\")) {\n d <- distance\n } else {\n cli_abort(paste(\n \"{.arg {arg}} can only be a {.cls string}, {.cls dist}\",\n \"object, or a {.cls function} return {.cls dist}\"\n ), call = call)\n }\n d\n}\n\ncutree_k_to_h <- function(tree, k) {\n if (is.null(n1 <- nrow(tree$merge)) || n1 < 1) {\n cli_abort(\"invalid {.arg tree} ({.field merge} component)\")\n }\n n <- n1 + 1\n if (is.unsorted(tree$height)) {\n cli_abort(\n \"the 'height' component of 'tree' is not sorted (increasingly)\"\n )\n }\n mean(tree$height[c(n - k, n - k + 1L)])\n}\n"], ["/ggalign/R/layout-quad-upset.R", "#' Create an UpSet plot\n#'\n#' @description\n#' `r lifecycle::badge('experimental')`\n#'\n#' `ggupset` is a specialized version of [`quad_discrete()`], which simplifies\n#' the creation of Upset plot.\n#'\n#' @param data Data used to create the UpSet plot. [`fortify_matrix()`] will be\n#' used to convert the data to a matrix. Currently, only\n#' [`fortify_matrix.list_upset`] and [`fortify_matrix.matrix_upset`] are\n#' suitable for creating an UpSet plot.\n#' @param ... Additional arguments passed to [`fortify_matrix()`].\n#' @inheritParams quad_layout\n#' @param direction A string indicating the direction of the UpSet plot,\n#' `\"h\"`(`horizontal`) or `\"v\"`(`vertical`). In a vertical UpSet plot, the\n#' columns of the matrix correspond to the sets, and the rows correspond to the\n#' intersections. By default, the horizontal UpSet plot is used, where the rows\n#' of the matrix correspond to the sets and the columns correspond to the\n#' intersections.\n#' @param point A list of parameters passed to\n#' [`geom_point()`][ggplot2::geom_point()].\n#' @param line A list of parameters passed to\n#' [`geom_line()`][ggplot2::geom_line()].\n#' @param rect A list of parameters passed to\n#' [`geom_rect()`][ggplot2::geom_rect()].\n#'\n#' @inheritSection heatmap_layout ggplot2 specification\n#' @examples\n#' set.seed(123)\n#' lt <- list(\n#' a = sample(letters, 5),\n#' b = sample(letters, 10),\n#' c = sample(letters, 15)\n#' )\n#' ggupset(tune(lt)) +\n#' scale_fill_manual(values = c(\"#F0F0F0\", \"white\"), guide = \"none\") +\n#' scale_color_manual(values = c(\"grey\", \"black\"), guide = \"none\") +\n#' anno_top() +\n#' ggalign(data = function(d) ggalign_attr(d, \"intersection_sizes\")) +\n#' ggplot2::geom_bar(aes(y = .data$value), stat = \"identity\") +\n#' anno_right() +\n#' ggalign(data = function(d) ggalign_attr(d, \"set_sizes\")) +\n#' ggplot2::geom_bar(aes(x = .data$value),\n#' stat = \"identity\",\n#' orientation = \"y\"\n#' )\n#' @importFrom ggplot2 aes\n#' @export\nggupset <- function(data = NULL, mapping = aes(),\n ...,\n direction = \"h\",\n point = NULL, line = NULL, rect = NULL,\n width = NA, height = NA,\n theme = NULL, active = NULL) {\n UseMethod(\"ggupset\")\n}\n\n# Don't allow inherit from the parent layout, since data for upset plot is\n# usually different with others\n#' @export\nggupset.NULL <- function(data, ...) {\n cli_abort(\"{.arg data} must be provided to create upset plot\")\n}\n\n#' @export\nggupset.waiver <- ggupset.NULL\n\n#' @importFrom ggplot2 aes\n#' @export\nggupset.default <- function(data = NULL, mapping = aes(),\n ...,\n direction = \"h\",\n point = NULL, line = NULL, rect = NULL,\n width = NA, height = NA,\n theme = NULL, active = NULL) {\n direction <- check_direction(direction)\n # we need a matrix to melted into long formated data frame\n data <- fortify_matrix(data = data, ...)\n if (is_vertical(direction)) data <- ggalign_data_restore(t(data), data)\n ans <- new_quad_layout(\n name = \"ggupset\",\n data = data,\n mapping = mapping,\n theme = theme,\n active = active\n )\n ans@plot <- ggadd_default(ans@plot, mapping = aes(.data$.x, .data$.y)) +\n ggplot2::labs(x = NULL, y = NULL) +\n upset_rect(direction, rect) +\n upset_point(point) +\n upset_line(direction, line)\n ans\n}\n\nmerge_mapping <- function(x, y) {\n if (is.null(x)) {\n return(y)\n }\n for (i in names(y)) {\n x[[i]] <- .subset2(y, i)\n }\n x\n}\n\nmerge_data_fn <- function(plot_data, user_data) {\n if (is.null(user_data) || is.waive(user_data)) {\n plot_data\n } else if (is.function(user_data <- allow_lambda(user_data))) {\n force(plot_data)\n function(data) user_data(plot_data(data))\n } else {\n user_data\n }\n}\n\nupset_rect <- function(direction, rect) {\n if (is_horizontal(direction)) {\n rect$mapping <- merge_mapping(rect$mapping, aes(\n ymin = .data$.ymin, ymax = .data$.ymax, fill = .data$rect_group\n ))\n rect$data <- merge_data_fn(function(data) {\n column <- c(\n \".y\", \".panel_x\", \".panel_y\",\n \".row_index\", \".row_names\", \".discrete_y\"\n )\n o <- vec_unique(data[vec_set_intersect(column, names(data))])\n o$rect_group <- (.subset2(o, \".y\") %% 2L) == 0L\n o$.ymin <- o$.y - 0.5\n o$.ymax <- o$.y + 0.5\n o\n }, rect$data)\n inject(ggplot2::geom_rect(!!!rect,\n xmin = -Inf, xmax = Inf, inherit.aes = FALSE\n ))\n } else {\n rect$mapping <- merge_mapping(rect$mapping, aes(\n xmin = .data$.xmin, xmax = .data$.xmax,\n fill = .data$rect_group\n ))\n rect$data <- merge_data_fn(function(data) {\n column <- c(\n \".x\", \".panel_x\", \".panel_y\",\n \".column_index\", \".column_names\", \".discrete_x\"\n )\n o <- vec_unique(data[vec_set_intersect(column, names(data))])\n o$rect_group <- (.subset2(o, \".x\") %% 2L) == 0L\n o$.xmin <- o$.x - 0.5\n o$.xmax <- o$.x + 0.5\n o\n }, rect$data)\n inject(ggplot2::geom_rect(!!!rect,\n ymin = -Inf, ymax = Inf, inherit.aes = FALSE\n ))\n }\n}\n\nupset_point <- function(point) {\n point$mapping <- merge_mapping(point$mapping, aes(\n x = .data$.x, y = .data$.y, color = .data$point_group\n ))\n point$data <- merge_data_fn(function(data) {\n data$point_group <- .subset2(data, \"value\")\n data\n }, point$data)\n inject(ggplot2::geom_point(!!!point, inherit.aes = FALSE))\n}\n\nupset_line <- function(direction, line) {\n line$mapping <- merge_mapping(line$mapping, switch_direction(\n direction,\n aes(.data$.x, .data$.y, group = paste(.data$.panel_x, .data$.x)),\n aes(.data$.x, .data$.y, group = paste(.data$.panel_y, .data$.y))\n ))\n line$data <- merge_data_fn(function(data) {\n if (is_horizontal(direction)) {\n dlist <- vec_split(data, data[c(\".panel_x\", \".x\")])\n dlist <- lapply(.subset2(dlist, \"val\"), function(d) {\n o <- vec_slice(d, .subset2(d, \"value\"))\n if (vec_size(o) < 2L) {\n return(NULL)\n }\n vec_slice(o, c(\n which.min(.subset2(o, \".y\")),\n which.max(.subset2(o, \".y\"))\n ))\n })\n vec_rbind(!!!dlist)\n } else {\n dlist <- vec_split(data, data[c(\".panel_y\", \".y\")])\n dlist <- lapply(.subset2(dlist, \"val\"), function(d) {\n o <- vec_slice(d, .subset2(d, \"value\"))\n if (vec_size(o) < 2L) {\n return(NULL)\n }\n vec_slice(o, c(\n which.min(.subset2(o, \".x\")),\n which.max(.subset2(o, \".x\"))\n ))\n })\n vec_rbind(!!!dlist)\n }\n }, line$data)\n inject(ggplot2::geom_line(!!!line, inherit.aes = FALSE))\n}\n"], ["/ggalign/R/link.R", "#' Define the links to connect a pair of observations\n#'\n#' @description\n#' This function allows users to define links between a pair of observations,\n#' facilitating the visualization of connections between related data points.\n#'\n#' @param .draw A function used to draw the links. The function must return a\n#' [`grob()`][grid::grob] object. If the function does not return a valid\n#' `grob`, no drawing will occur. The input data for the function should\n#' include a data frame with the coordinates of the pair of observations to\n#' be linked.\n#' @inheritParams .link_draw\n#' @seealso\n#' - [`link_line()`]\n#' - [`.link_draw()`]\n#' @importFrom rlang is_empty inject\n#' @importFrom grid gTree gList\n#' @export\nlink_draw <- function(.draw, ...) {\n if (!is.function(draw <- allow_lambda(.draw))) {\n cli_abort(\"{.arg .draw} must be a function\")\n }\n new_draw <- function(data) {\n ans <- lapply(data, draw)\n ans <- ans[vapply(ans, is.grob, logical(1L), USE.NAMES = FALSE)]\n if (!is_empty(ans)) inject(gList(!!!ans))\n }\n .link_draw(new_draw, ...)\n}\n\n#' @inherit link_draw title\n#'\n#' @description\n#' A base version of [`link_draw()`], optimized for performance. This function\n#' serves as the foundation for building other `link_*` functions that manage\n#' the drawing of links between pairs of observations.\n#'\n#' @param .draw A function used to draw the links. The function must return a\n#' [`grob()`][grid::grob] object. If the function does not return a valid\n#' `grob`, no drawing will occur. The input data for the function should be\n#' a list, where each item is a data frame containing the coordinates of\n#' the pair of observations.\n#' @inheritParams pair_links\n#' @seealso [`link_draw()`]\n#' @export\n.link_draw <- function(.draw, ...) {\n if (override_call(call <- caller_call())) {\n call <- current_call()\n }\n if (!is.function(draw <- allow_lambda(.draw))) {\n cli_abort(\"{.arg .draw} must be a function\", call = call)\n }\n links <- pair_links(...)\n structure(list(draw = draw, links = links), class = \"ggalign_link_draw\")\n}\n\n#' @export\nprint.ggalign_link_draw <- function(x, ...) {\n header <- sprintf(\"<%s>\", vec_ptype_full(x))\n cat(header, sep = \"\\n\")\n obj_print_data(.subset2(x, \"links\"))\n invisible(x)\n}\n\n#' Link the paired observations with a line\n#'\n#' @inheritParams .link_draw\n#' @param .element A [`element_line()`][ggplot2::element_line] object.\n#' Vectorized fields will be recycled to match the total number of groups, or\n#' you can wrap the element with [`I()`] to recycle to match the drawing\n#' groups. The drawing groups typically correspond to the product of the\n#' number of observations from both sides, as each pair of observations will\n#' be linked with a single line.\n#' @importFrom ggplot2 element_line\n#' @export\nlink_line <- function(..., .element = NULL) {\n assert_s3_class(.element, \"element_line\", allow_null = TRUE)\n default <- calc_element(\"ggalign.line\", complete_theme(theme_get()))\n if (is.null(.element)) {\n .element <- default\n } else {\n .element <- ggplot2::merge_element(.element, default)\n }\n ans <- .link_draw(.draw = function(data) {\n data <- lapply(data, function(d) {\n # if the link is only in one side, we do nothing\n if (vec_unique_count(.subset2(d, \".hand\")) < 2L) {\n return(NULL)\n }\n both <- .subset2(vec_split(d, .subset2(d, \".hand\")), \"val\")\n data <- cross_join(.subset2(both, 1L), .subset2(both, 2L))\n data_frame0(\n x = vec_interleave(\n (data$x.x + data$xend.x) / 2L,\n (data$x.y + data$xend.y) / 2L\n ),\n y = vec_interleave(\n (data$y.x + data$yend.x) / 2L,\n (data$y.y + data$yend.y) / 2L\n )\n )\n })\n if (inherits(.element, \"AsIs\")) {\n .element <- element_rep_len(.element,\n length.out = sum(list_sizes(data)) / 2L\n )\n } else {\n .element <- element_rep_len(.element, length.out = length(data))\n .element <- element_vec_rep_each(.element,\n times = list_sizes(data) / 2L\n )\n }\n data <- vec_rbind(!!!data)\n if (vec_size(data)) {\n element_grob(\n .element,\n x = data$x, y = data$y,\n id.lengths = vec_rep(2L, vec_size(data) / 2L),\n default.units = \"native\"\n )\n }\n }, ...)\n add_class(ans, \"ggalign_link_line\")\n}\n\n#' Link the paired observations with a quadrilateral\n#'\n#' @inheritParams .link_draw\n#' @inheritParams mark_tetragon\n#' @export\nlink_tetragon <- function(..., .element = NULL) {\n assert_s3_class(.element, \"element_polygon\", allow_null = TRUE)\n default <- calc_element(\"ggalign.polygon\", complete_theme(theme_get()))\n if (is.null(.element)) {\n .element <- default\n } else {\n .element <- ggplot2::merge_element(.element, default)\n }\n .link_draw(.draw = function(data) {\n data <- lapply(data, function(d) {\n # if the link is only in one side, we do nothing\n if (vec_unique_count(.subset2(d, \".hand\")) < 2L) {\n return(NULL)\n }\n both <- .subset2(vec_split(d, .subset2(d, \".hand\")), \"val\")\n both <- lapply(both, function(link) {\n # find the consecutive groups\n index <- .subset2(link, \"link_index\")\n oindex <- order(index)\n group <- cumsum(c(0L, diff(index[oindex])) != 1L)\n\n # restore the order\n group <- group[order(oindex)]\n\n # split link into groups\n .subset2(vec_split(link, group), \"val\")\n })\n both <- vec_expand_grid(\n hand1 = .subset2(both, 1L),\n hand2 = .subset2(both, 2L)\n )\n ans <- .mapply(function(hand1, hand2) {\n data_frame0(\n x = vec_c(\n min(hand1$x), max(hand1$xend),\n max(hand2$xend), min(hand2$x)\n ),\n y = vec_c(\n min(hand1$y), max(hand1$yend),\n max(hand2$yend), min(hand2$y)\n )\n )\n }, both, NULL)\n vec_rbind(!!!ans)\n })\n if (inherits(.element, \"AsIs\")) {\n .element <- element_rep_len(.element,\n length.out = sum(list_sizes(data)) / 4L\n )\n } else {\n .element <- element_rep_len(.element, length.out = length(data))\n .element <- element_vec_rep_each(.element,\n times = list_sizes(data) / 4L\n )\n }\n data <- vec_rbind(!!!data)\n if (vec_size(data)) {\n element_grob(\n .element,\n x = data$x, y = data$y,\n id.lengths = vec_rep(4L, vec_size(data) / 4L),\n default.units = \"native\"\n )\n }\n }, ...)\n}\n\n# preDraw:\n# - makeContext\n# - pushvpgp\n# - preDrawDetails: by default, do noting\n# makeContent:\n# drawDetails:\n# postDraw:\n# - postDrawDetails: by default, do noting\n# - popgrobvp\n#' @importFrom grid makeContent convertHeight convertWidth gList setChildren\n#' @export\nmakeContent.ggalignLinkTree <- function(x) {\n # Grab viewport information\n width <- convertWidth(unit(1, \"npc\"), \"mm\", valueOnly = TRUE)\n height <- convertHeight(unit(1, \"npc\"), \"mm\", valueOnly = TRUE)\n\n # Grab grob metadata\n full_data1 <- .subset2(x, \"full_data1\")\n full_data2 <- .subset2(x, \"full_data2\")\n direction <- .subset2(x, \"direction\")\n link_index_list <- .subset2(x, \"link_index\")\n data_index_list <- .subset2(x, \"data_index\")\n obs_size <- .subset2(x, \"obs_size\")\n\n # prepare output for current for loop\n coords <- vector(\"list\", 2L)\n names(coords) <- c(\"hand1\", \"hand2\")\n for (link in names(coords)) {\n link_index <- lapply(link_index_list, .subset2, link)\n data_index <- lapply(data_index_list, .subset2, link)\n # early exit and step into next cycle if no link\n if (all(vapply(link_index, is.null, logical(1L), USE.NAMES = FALSE))) {\n coords[link] <- list(link_index)\n next\n }\n full_breaks <- switch(link,\n hand1 = full_data1,\n hand2 = full_data2\n )\n\n spacing <- .subset2(x, switch(link,\n hand1 = \"spacing1\",\n hand2 = \"spacing2\"\n ))\n\n # each value represent an `observation`, for panel space, we use `NA`\n # obs arranged from left to top, and from bottom to top\n points <- unlist(vec_interleave(full_breaks, list(NA)), FALSE, FALSE)\n # remove the last panel space, shouldn't exist\n points <- points[-length(points)]\n sizes <- numeric(length(points))\n n_spacing <- length(full_breaks) - 1L\n\n # then, we define the link grobs\n if (is_horizontal(direction)) { # the link should be in left or right\n spacing <- convertHeight(spacing, \"mm\", valueOnly = TRUE)\n spacing <- scales::rescale(spacing, c(0, 1), from = c(0, height))\n sizes[is.na(points)] <- spacing\n obs_height <- (1 - spacing * n_spacing) / sum(!is.na(points))\n sizes[!is.na(points)] <- obs_height # nobs\n yend <- cumsum(sizes)\n link_x <- switch(link,\n hand1 = 0,\n hand2 = 1\n )\n # by default, the height for each observation is `1`,\n # if we define obs size, we just re-scale it\n removed <- (1 - obs_size) * obs_height\n link_coord <- data_frame0(\n x = link_x, xend = link_x,\n y = yend - sizes + removed / 2L,\n yend = yend - removed / 2L\n )\n link_coord <- vec_slice(link_coord, !is.na(points))\n } else { # the link should be in top or bottom\n spacing <- convertWidth(spacing, \"mm\", valueOnly = TRUE)\n spacing <- scales::rescale(spacing, c(0, 1), from = c(0, width))\n sizes[is.na(points)] <- spacing\n obs_width <- (1 - spacing * n_spacing) / sum(!is.na(points))\n sizes[!is.na(points)] <- obs_width\n xend <- cumsum(sizes)\n link_y <- switch(link,\n hand1 = 1,\n hand2 = 0\n )\n # by default, the width for each observation is `1`,\n # if we define obs size, we just re-scale it\n removed <- (1 - obs_size) * obs_width\n link_coord <- data_frame0(\n x = xend - sizes + removed / 2L,\n xend = xend - removed / 2L,\n y = link_y, yend = link_y\n )\n link_coord <- vec_slice(link_coord, !is.na(points))\n }\n hand <- switch(link,\n hand1 = switch_direction(direction, \"left\", \"top\"),\n hand2 = switch_direction(direction, \"right\", \"bottom\")\n )\n nms <- names(link_index)\n link_panels <- vec_rep_each(names(full_breaks), list_sizes(full_breaks))\n coords[[link]] <- lapply(seq_along(link_index), function(i) {\n l_index <- .subset2(link_index, i)\n if (is.null(l_index)) return(NULL) # styler: off\n d_index <- .subset2(data_index, i)\n link <- vec_slice(link_coord, l_index)\n link$link_id <- nms[i]\n link$link_panel <- reorder(\n vec_slice(link_panels, l_index), l_index,\n order = FALSE\n )\n link$link_index <- l_index\n link$.hand <- hand\n link$.index <- d_index\n link\n })\n }\n\n # hand1 - hand2\n data <- .mapply(vec_rbind, coords, NULL)\n draw <- .subset2(x, \"draw\")\n if (is.grob(grob <- draw(data))) { # wrap single grob to a gList\n grob <- gList(grob)\n }\n if (is.gList(grob)) {\n setChildren(x, grob)\n } else {\n x\n }\n}\n"], ["/ggalign/R/layout-chain-stack-build.R", "#' @export\nggalign_build.StackLayout <- function(x) {\n x <- default_layout(x)\n (stack_build(x) %||% align_plots(theme = x@theme)) +\n layout_title(\n title = .subset2(x@titles, \"title\"),\n subtitle = .subset2(x@titles, \"subtitle\"),\n caption = .subset2(x@titles, \"caption\")\n )\n}\n\n#' @param schemes,theme Parameters from parent layout\n#' @param extra_design layout parameters of the axis vertically with the stack.\n#' @noRd\nstack_build <- function(stack, schemes = NULL, theme = NULL,\n extra_design = NULL) {\n if (is_empty(stack@plot_list)) {\n return(NULL)\n }\n direction <- stack@direction\n position <- .subset2(stack@heatmap, \"position\")\n schemes <- inherit_parent_layout_schemes(stack, schemes)\n\n if (is_horizontal(direction)) {\n spacing <- \"y\"\n # for horizontal stack, we by default remove top and bottom spaces\n # if (!is.null(position)) {\n # schemes$scheme_align[\"free_spaces\"] <- list(\n # .subset2(schemes$scheme_align, \"free_spaces\") %|w|% \"tb\"\n # )\n # }\n } else {\n spacing <- \"x\"\n # for vertical stack, we by default remove left and right spaces\n # if (!is.null(position)) {\n # schemes$scheme_align[\"free_spaces\"] <- list(\n # .subset2(schemes$scheme_align, \"free_spaces\") %|w|% \"lr\"\n # )\n # }\n }\n theme <- inherit_parent_layout_theme(stack, theme, spacing = spacing)\n composer <- resolve_stack_layout(stack, schemes, theme, extra_design)\n if (is_empty(plots <- .subset2(composer, \"plots\"))) {\n return(NULL)\n }\n\n # arrange plots\n if (is.null(position)) { # for stack layout\n # sizes should be of length 3\n sizes <- stack@sizes\n # recycle the sizes when necessary\n if (length(sizes) == 1L) sizes <- rep(sizes, length.out = 3L)\n sizes <- sizes[\n c(\n .subset2(composer, \"left_or_top\"),\n TRUE,\n .subset2(composer, \"right_or_bottom\")\n )\n ]\n } else { # for the heatmap annotation\n sizes <- NA\n }\n plot <- align_plots(\n !!!plots,\n design = area(\n .subset2(composer, \"t\"),\n .subset2(composer, \"l\"),\n .subset2(composer, \"b\"),\n .subset2(composer, \"r\")\n ),\n widths = switch_direction(\n direction,\n do.call(unit.c, .subset2(composer, \"sizes\")),\n sizes\n ),\n heights = switch_direction(\n direction,\n sizes,\n do.call(unit.c, .subset2(composer, \"sizes\"))\n ),\n guides = .subset2(.subset2(schemes, \"scheme_align\"), \"guides\"),\n theme = stack@theme\n )\n\n # for annotation, we should always make it next to the main body\n if (is.null(position)) {\n return(plot)\n }\n plot <- free_vp(\n plot,\n x = switch(position,\n left = 1L,\n right = 0L,\n 0.5\n ),\n y = switch(position,\n top = 0L,\n bottom = 1L,\n 0.5\n ),\n just = switch(position,\n top = \"bottom\",\n left = \"right\",\n bottom = \"top\",\n right = \"left\"\n )\n )\n\n # whether we should override the `guides` collection for the whole\n # annotation stack\n free_guides <- .subset2(stack@heatmap, \"free_guides\")\n if (!is.waive(free_guides)) plot <- free_guide(plot, free_guides)\n # we also apply the `free_spaces` for the whole annotation stack\n free_spaces <- .subset2(\n .subset2(schemes, \"scheme_align\"), \"free_spaces\"\n ) %|w|% NULL\n if (!is.null(free_spaces)) {\n plot <- free_space(free_border(plot, free_spaces), free_spaces)\n }\n plot\n}\n\n#' @param schemes,theme Parameters for current stack, which have inherited\n#' parameters from the parent.\n#' @noRd\nresolve_stack_layout <- function(stack, schemes, theme, extra_design) {\n UseMethod(\"resolve_stack_layout\")\n}\n\n#' @export\nresolve_stack_layout.StackLayout <- function(stack, schemes, theme,\n extra_design) {\n plot_list <- stack@plot_list\n direction <- stack@direction\n position <- .subset2(stack@heatmap, \"position\")\n\n # we remove the plot without actual plot area\n keep <- vapply(plot_list, function(plot) {\n # we remove objects without plot area\n # Now, only `CraftBox` will contain `NULL`\n !is_craftbox(plot) || !is.null(plot@plot)\n }, logical(1L), USE.NAMES = FALSE)\n plot_list <- .subset(plot_list, keep)\n if (is_empty(plot_list)) return(NULL) # styler: off\n\n # we reorder the plots based on the `order` slot\n plot_order <- vapply(plot_list, function(plot) {\n if (is_layout(plot)) {\n .subset2(plot@plot_active, \"order\")\n } else {\n .subset2(plot@active, \"order\")\n }\n }, integer(1L), USE.NAMES = FALSE)\n plot_list <- .subset(plot_list, make_order(plot_order))\n\n # build the stack\n composer <- stack_composer(direction)\n\n # for `free_spaces`, if we have applied it in the whole stack layout\n # we shouln't use it for a single plot. Otherwise, the guide legends\n # collected by the layout will overlap with the axis of the plot in the\n # layout.\n #\n # this occurs in the annotation stack (`position` is not `NULL`).\n #\n # here is the example:\n # p1 <- ggplot(mtcars) +\n # geom_point(aes(mpg, disp))\n # p2 <- ggplot(mtcars) +\n # geom_boxplot(aes(gear, disp, group = gear, fill = gear))\n # p3 <- ggplot(mtcars) +\n # geom_bar(aes(gear)) +\n # facet_wrap(~cyl)\n # align_plots(\n # free_space(free_border(\n # align_plots(\n # # we shouldn't add free_space for the internal plot\n # free_space(\n # free_border(\n # p1 + scale_y_continuous(\n # expand = expansion(),\n # labels = ~ paste(\"very very long labels\", .x)\n # ),\n # \"l\"\n # ),\n # \"l\"\n # ),\n # p2 + theme(legend.position = \"left\"),\n # guides = \"l\"\n # ),\n # \"l\"\n # ), \"l\"),\n # p3 + theme(plot.margin = margin(l = 5, unit = \"cm\")),\n # ncol = 1\n # )\n stack_spaces <- .subset2(.subset2(schemes, \"scheme_align\"), \"free_spaces\")\n if (is_string(stack_spaces) && !is.null(position)) {\n released_spaces <- stack_spaces\n } else {\n released_spaces <- NULL\n }\n\n design <- setup_design(stack@design)\n stack_composer_add(\n plot_list,\n stack = stack,\n composer,\n schemes = schemes,\n theme = theme,\n design = design,\n extra_design = extra_design,\n direction = direction,\n position = position,\n released_spaces = released_spaces,\n previous_design = NULL\n )\n}\n\nmake_order <- function(order) {\n l <- length(order)\n index <- seq_len(l)\n\n # for order not set by user, we use heuristic algorithm to define the order\n need_action <- is.na(order)\n if (all(need_action)) { # shorthand for the usual way, we don't set any\n return(index)\n } else if (all(!need_action)) { # we won't need do something special\n return(order(order))\n }\n\n # 1. for outliers, we always put them in the two tail\n # 2. for order has been set and is not the outliers,\n # we always follow the order\n # 3. non-outliers were always regarded as the integer index\n used <- as.integer(order[!need_action & order >= 1L & order <= l])\n\n # we flatten user index to continuous integer sequence\n sequence <- vec_unrep(used) # key is the sequence start\n start <- .subset2(sequence, \"key\")\n end <- pmin(\n start + .subset2(sequence, \"times\") - 1L,\n vec_c(start[-1L] - 1L, l) # the next start - 1L\n )\n used <- .mapply(function(s, e) s:e, list(s = start, e = end), NULL)\n\n # following index can be used\n unused <- vec_set_difference(index, unlist(used, FALSE, FALSE))\n\n # we assign the candidate index to the order user not set.\n order[need_action] <- unused[seq_len(sum(need_action))]\n\n # make_order(c(NA, 1, NA)): c(2, 1, 3)\n # make_order(c(NA, 1, 3)): c(2, 1, 3)\n # make_order(c(NA, 1, 3, 1)): c(2, 4, 3, 1)\n order(order)\n}\n"], ["/ggalign/R/fortify-data-frame-dendrogram.R", "#' @inherit fortify_data_frame.default title description\n#'\n#' @param data A [`hclust`][stats::hclust] or a\n#' [`dendrogram`][stats::as.dendrogram] object.\n#' @param center A boolean value. if `TRUE`, nodes are plotted centered with\n#' respect to all leaves/tips in the branch. Otherwise (default), plot them in\n#' the middle of the direct child nodes.\n#' @param type A string indicates the plot type, `\"rectangle\"` or `\"triangle\"`.\n#' @param leaf_pos The x-coordinates of the leaf node. Must be the same length\n#' of the number of observations in `tree`.\n#' @param leaf_braches Branches of the leaf node. Must be the same length of the\n#' number of observations in `tree`. Usually come from [cutree][stats::cutree].\n#' @param reorder_branches A single boolean value, indicates whether reorder the\n#' provided `leaf_braches` based on the actual index.\n#' @param branch_gap A single numeric value indicates the gap between different\n#' branches.\n#' @param root A length one string or numeric indicates the root branch.\n#' @param priority A string of \"left\" or \"right\". if we draw from `right` to\n#' `left`, the left will override the right, so we take the `\"left\"` as the\n#' priority. If we draw from `left` to `right`, the right will override the\n#' left, so we take the `\"right\"` as priority. This is used by\n#' [`align_dendro()`] to provide support of facet operation in ggplot2.\n#' @param double A single logical value indicating whether horizontal lines\n#' should be doubled when segments span multiple branches. If `TRUE`, the\n#' horizontal lines will be repeated for each branch that the segment spans. If\n#' `FALSE`, only one horizontal line will be drawn. This is used by\n#' [`align_dendro()`] to provide support of facet operation in ggplot2.\n#' @inheritParams fortify_data_frame\n#' @return A `data frame` with the node coordinates:\n#' - `.panel`: Similar with `panel` column, but always give the correct\n#' branch for usage of the ggplot facet.\n#' - `.index`: the original index in the tree for the the node\n#' - `label`: node label text\n#' - `x` and `y`: x-axis and y-axis coordinates for the node\n#' - `branch`: which branch the node is. You can use this column to color\n#' different groups.\n#' - `panel`: which panel the node is, if we split the plot into panel\n#' using [facet_grid][ggplot2::facet_grid], this column will show\n#' which panel the node is from. Note: some nodes may\n#' fall outside panel (between two panels), so there are possible\n#' `NA` values in this column.\n#' - `leaf`: A logical value indicates whether the node is a leaf.\n#' @section ggalign attributes:\n#' `edge`: A `data frame` for edge coordinates:\n#' - `.panel`: Similar with `panel` column, but always give the correct\n#' branch for usage of the ggplot facet.\n#' - `x` and `y`: x-axis and y-axis coordinates for the start node of the edge.\n#' - `xend` and `yend`: the x-axis and y-axis coordinates of the terminal node\n#' for edge.\n#' - `branch`: which branch the edge is. You can use this column to color\n#' different groups.\n#' - `panel1` and `panel2`: The panel1 and panel2 columns have the same\n#' functionality as `panel`, but they are specifically for the `edge` data\n#' and correspond to both nodes of each edge.\n#' @examples\n#' fortify_data_frame(hclust(dist(USArrests), \"ave\"))\n#' @importFrom grid is.unit\n#' @importFrom stats order.dendrogram\n#' @importFrom rlang arg_match0\n#' @family fortify_data_frame\n#' @export\nfortify_data_frame.dendrogram <- function(data, ...,\n priority = \"right\",\n center = FALSE,\n type = \"rectangle\",\n leaf_pos = NULL,\n leaf_braches = NULL,\n reorder_branches = TRUE,\n branch_gap = NULL,\n root = NULL,\n double = TRUE,\n data_arg = NULL, call = NULL) {\n call <- call %||% current_call()\n data_arg <- data_arg %||% \"data\"\n rlang::check_dots_empty(call = call)\n assert_bool(center, call = call)\n assert_bool(reorder_branches, call = call)\n type <- arg_match0(type, c(\"rectangle\", \"triangle\"), error_call = call)\n priority <- arg_match0(priority, c(\"left\", \"right\"), error_call = call)\n N <- stats::nobs(data)\n rectangle <- type == \"rectangle\"\n if (is.null(leaf_pos)) {\n leaf_pos <- seq_len(N)\n } else if (length(leaf_pos) != N) {\n cli_abort(\n \"{.arg leaf_pos} must be of the same length of {.arg tree}\",\n call = call\n )\n }\n\n # if no branches provided, all branch will be regarded as the `root`\n if (is.null(leaf_braches)) {\n root <- root %||% \"root\"\n } else if (anyNA(leaf_braches)) {\n cli_abort(\"`NA` is not allowed in {.arg leaf_braches}\",\n call = call\n )\n } else if (length(leaf_braches) != N) {\n cli_abort(\n \"{.arg leaf_braches} must be of the same length of {.arg tree}\",\n call = call\n )\n } else if (is.character(leaf_braches)) {\n root <- root %||% \"root\"\n } else if (is.factor(leaf_braches)) {\n leaf_braches <- as.character(leaf_braches)\n root <- root %||% \"root\"\n } else if (is.numeric(leaf_braches)) {\n root <- root %||% (min(leaf_braches) - 1L)\n } else {\n cli_abort(\"{.arg leaf_braches} must be a character or numeric\",\n call = call\n )\n }\n\n if (!is.null(leaf_braches) && reorder_branches) {\n leaf_braches <- .subset(leaf_braches, order.dendrogram(data))\n }\n\n # check `branch_gap`\n if (is.numeric(branch_gap)) {\n if (!is_scalar(branch_gap)) {\n cli_abort(\"{.arg branch_gap} must be of length 1\",\n call = call\n )\n }\n } else if (is.null(branch_gap)) {\n branch_gap <- 0\n } else {\n cli_abort(\"{.arg branch_gap} must be numeric value.\",\n call = call\n )\n }\n\n # the root value shouldn't be the same of leaf branches.\n if (!is_scalar(root)) {\n cli_abort(\"{.arg root} must be of length 1\", call = call)\n } else if (anyNA(root)) {\n cli_abort(\"{.arg root} cannot be `NA`\", call = call)\n } else if (any(root == leaf_braches)) {\n cli_abort(\n \"{.arg root} cannot contain value in {.arg leaf_braches}\",\n call = call\n )\n }\n\n # initialize values\n i <- 0L # leaf index\n branch_levels <- NULL\n last_branch <- root\n total_gap <- 0\n dendrogram_data <- function(dend, from_root = TRUE) {\n if (stats::is.leaf(dend)) { # base version\n index <- as.integer(dend) # the column index of the original data\n y <- attr(dend, \"height\") %||% 0\n label <- attr(dend, \"label\") %||% NA\n i <<- i + 1L\n if (is.null(leaf_braches)) {\n branch <- root\n } else {\n branch <- .subset(leaf_braches, i)\n }\n\n x <- .subset(leaf_pos, i) + total_gap\n # for every new branch, we saved the branch for later use, in order\n # to order the branch levels, and we add a gap between two branch\n if (branch != last_branch) {\n branch_levels <<- c(branch_levels, branch)\n x <- x + branch_gap\n total_gap <<- total_gap + branch_gap\n }\n last_branch <<- branch\n\n node <- data_frame0(\n index = index, label = label,\n x = x, y = y, branch = branch,\n leaf = TRUE, panel = branch,\n ggpanel = branch\n )\n list(\n # current node\n node = node, edge = NULL,\n # current node information\n x = x, y = y,\n branch = branch,\n panel = branch,\n ggpanel = branch\n )\n } else if (inherits(dend, \"dendrogram\")) { # recursive version\n # the parent height -------------------------------------\n y <- attr(dend, \"height\")\n\n # for the children nodes ---------------------------------\n data <- list_transpose(\n lapply(dend, dendrogram_data, from_root = FALSE)\n )\n\n # node should be the direct children\n node <- vec_rbind(!!!.subset2(data, \"node\"))\n edge <- vec_rbind(!!!.subset2(data, \"edge\"))\n\n # all coordinate for direct children nodes -------------\n # following should be length 2\n direct_leaves_x <- unlist(\n .subset2(data, \"x\"),\n recursive = FALSE, use.names = FALSE\n )\n direct_leaves_y <- unlist(\n .subset2(data, \"y\"),\n recursive = FALSE, use.names = FALSE\n )\n direct_leaves_branch <- unlist(\n .subset2(data, \"branch\"),\n recursive = FALSE, use.names = FALSE\n )\n direct_leaves_panel <- unlist(\n .subset2(data, \"panel\"),\n recursive = FALSE, use.names = FALSE\n )\n direct_leaves_ggpanel <- unlist(\n .subset2(data, \"ggpanel\"),\n recursive = FALSE, use.names = FALSE\n )\n\n # prepare node data ------------------------------------\n\n # all x coordinate for children nodes --------------------\n # used if center is `TRUE`, we'll calculate the center position\n # among all children nodes\n leaves <- vec_slice(node, .subset2(node, \"leaf\")) # all leaves\n\n # we assign the `panel` for current branch node\n ranges <- split(\n .subset2(leaves, \"x\"),\n .subset2(leaves, \"panel\")\n )\n ranges <- ranges[\n order(vapply(ranges, min, numeric(1L), USE.NAMES = FALSE))\n ]\n full_panel <- names(ranges)\n\n # x coordinate for current branch: the midpoint\n if (center) {\n x <- sum(range(.subset2(leaves, \"x\"))) / 2L\n } else {\n x <- sum(direct_leaves_x) / 2L\n }\n if (is.null(leaf_braches)) { # no branches\n ggpanel <- panel <- branch <- root\n } else {\n # we assign the branch for current branch node\n branch <- unique(direct_leaves_branch)\n # if two children leaves are different, this branch should be\n # `root`, this is often used to color the segments\n if (length(branch) > 1L) branch <- root\n\n # we assign the `panel` for current branch node\n panel <- NA\n for (i in seq_along(ranges)) {\n if (x < min(.subset2(ranges, i))) {\n panel <- NA\n break\n } else if (x <= max(.subset2(ranges, i))) {\n panel <- .subset2(full_panel, i)\n break\n }\n }\n # if the node is between two panels, no panel\n # we choose the priority\n if (is.na(ggpanel <- panel)) {\n # it's not possible for an branch node live outside the\n # all panels - the left or right most. So `i` won't be 1 or\n # length(ranges). we don't need to check the argument\n ggpanel <- switch(priority,\n left = .subset(full_panel, i - 1L),\n right = .subset(full_panel, i)\n )\n }\n }\n\n # there is no node data in dendrogram root\n if (!from_root) {\n node <- vec_rbind(node, data_frame0(\n index = NA, label = NA,\n x = x, y = y, branch = branch, leaf = FALSE,\n panel = panel, ggpanel = ggpanel\n ))\n }\n\n # if it's the `rectangle`\n if (rectangle) {\n # 2 vertical lines\n vertical_lines <- data_frame0(\n x = direct_leaves_x,\n xend = direct_leaves_x,\n y = direct_leaves_y,\n yend = rep_len(y, 2L),\n branch = direct_leaves_branch,\n panel1 = direct_leaves_panel,\n panel2 = direct_leaves_panel,\n ggpanel = direct_leaves_ggpanel\n )\n # 2 horizontal lines\n # if the horizontal lines spanned multiple panels\n # we double the left line and the right line\n added_edge <- vec_rbind(\n vertical_lines,\n # left horizontal line\n make_horizontal(\n c(direct_leaves_x[1L], x),\n panels = c(direct_leaves_panel[1L], panel),\n ggpanels = c(direct_leaves_ggpanel[1L], ggpanel),\n y = y,\n branch = direct_leaves_branch[1L],\n ranges = ranges,\n full_panel = full_panel,\n double = double\n ),\n # right horizontal line\n make_horizontal(\n c(x, direct_leaves_x[2L]),\n panels = c(panel, direct_leaves_panel[2L]),\n ggpanels = c(ggpanel, direct_leaves_ggpanel[2L]),\n y = y,\n branch = direct_leaves_branch[2L],\n ranges = ranges,\n full_panel = full_panel,\n double = double\n )\n )\n } else {\n added_edge <- data_frame0(\n x = rep_len(x, 2L),\n xend = direct_leaves_x,\n y = rep_len(y, 2L),\n yend = direct_leaves_y,\n branch = direct_leaves_branch,\n panel1 = rep_len(panel, 2L),\n panel2 = direct_leaves_panel,\n ggpanel = rep_len(ggpanel, 2L)\n )\n }\n if (is.null(edge)) {\n edge <- added_edge\n } else {\n edge <- vec_rbind(edge, added_edge)\n }\n list(\n node = node, edge = edge,\n x = x, y = y, branch = branch,\n panel = panel, ggpanel = ggpanel\n )\n } else {\n cli_abort(\"Invalid {.cls dendrogram} provided in {.arg {data_arg}}\",\n call = call\n )\n }\n }\n ans <- dendrogram_data(data)\n node <- .subset2(ans, \"node\")\n edge <- .subset2(ans, \"edge\")\n\n # set factor levels for branch and panel ---------------\n panel_levels <- branch_levels\n branch_levels <- c(branch_levels, root)\n node$panel <- factor(.subset2(node, \"panel\"), panel_levels)\n node$branch <- factor(.subset2(node, \"branch\"), branch_levels)\n node$ggpanel <- factor(.subset2(node, \"ggpanel\"), panel_levels)\n if (!is.null(edge)) {\n edge$panel1 <- factor(.subset2(edge, \"panel1\"), panel_levels)\n edge$panel2 <- factor(.subset2(edge, \"panel2\"), panel_levels)\n edge$branch <- factor(.subset2(edge, \"branch\"), branch_levels)\n edge$ggpanel <- factor(.subset2(edge, \"ggpanel\"), panel_levels)\n }\n node <- rename(node, c(ggpanel = \".panel\", index = \".index\"))\n edge <- rename(edge, c(ggpanel = \".panel\"))\n ggalign_data_set(node, edge = edge)\n}\n\n#' @param ... Additional arguments passed to `dendrogram` method.\n#' @export\n#' @rdname fortify_data_frame.dendrogram\nfortify_data_frame.hclust <- function(data, ...) {\n fortify_data_frame.dendrogram(stats::as.dendrogram(data), ...)\n}\n\n#' @param ggpanels Won't be `NA`\n#' @noRd\nmake_horizontal <- function(x, panels, ggpanels, y, branch,\n ranges, full_panel = names(ranges),\n double = TRUE) {\n if (!isTRUE(double) || identical(ggpanels[1L], ggpanels[2L])) {\n # in the same panel\n data_frame0(\n x = x[1L],\n xend = x[2L],\n y = y,\n yend = y,\n branch = branch,\n panel1 = panels[1L],\n panel2 = panels[2L],\n ggpanel = ggpanels[1L]\n )\n } else {\n index <- match(ggpanels, full_panel)\n ending <- index[2L] # right index\n panel0 <- panels[1L]\n ggpanel0 <- ggpanels[1L]\n point0 <- x[1L] # the left point coordinate x\n out <- vector(\"list\", diff(index))\n right_index <- (index[1L] + 1L):ending\n for (i in seq_along(right_index)) {\n i1 <- .subset(right_index, i) # right index\n if (i1 == ending) {\n point1 <- x[2L]\n panel1 <- panels[2L]\n ggpanel1 <- ggpanels[2L]\n } else {\n point1 <- mean(range(.subset2(ranges, i1)))\n ggpanel1 <- panel1 <- .subset(full_panel, i1)\n }\n out[[i]] <- data_frame0(\n x = c(point0, point1),\n xend = c(point1, point0),\n y = y,\n yend = y,\n branch = branch,\n panel1 = c(panel0, panel1),\n panel2 = c(panel1, panel0),\n ggpanel = c(ggpanel0, ggpanel1)\n )\n point0 <- point1\n panel0 <- panel1\n ggpanel0 <- ggpanel1\n }\n vec_rbind(!!!out)\n }\n}\n"], ["/ggalign/R/layout-quad-add.R", "#' @keywords internal\nquad_layout_add <- function(object, quad, object_name) {\n UseMethod(\"quad_layout_add\")\n}\n\n#############################################################\n#' @export\nquad_layout_add.layout_title <- function(object, quad, object_name) {\n quad@titles <- update_non_waive(quad@titles, object)\n quad\n}\n\n##############################################################\n# Preventing from adding following elements\n#' @export\nquad_layout_add.matrix <- function(object, quad, object_name) {\n cli_abort(sprintf(\"Can't change data of %s\", object_name(quad)))\n}\n\n#' @export\nquad_layout_add.data.frame <- quad_layout_add.matrix\n\n#############################################################\n# Add elements for the main body or the annotation\n#' @importFrom methods slot slot<-\n#' @export\nquad_layout_add.default <- function(object, quad, object_name) {\n if (is.null(position <- quad@active)) {\n quad <- quad_body_add(object, quad, object_name)\n } else if (is.null(stack <- slot(quad, position))) {\n cli_abort(c(\n sprintf(\"Cannot add {.var {object_name}} to %s\", object_name(quad)),\n i = \"the {.field {position}} annotation stack is not initialized\",\n i = \"Try to use {.code quad_anno(initialize = TRUE)} or you can add a {.code stack_layout()} manually\"\n ))\n } else {\n slot(quad, position) <- chain_layout_add(object, stack, object_name)\n }\n quad\n}\n\n#' @export\nquad_layout_add.list <- function(object, quad, object_name) {\n for (o in object) quad <- quad_layout_add(o, quad, object_name)\n quad\n}\n\n#' @export\nquad_layout_add.NULL <- function(object, quad, object_name) {\n quad\n}\n\n#' @export\nquad_layout_add.ggalign_with_quad <- function(object, quad, object_name) {\n old <- quad@active\n contexts <- quad_operated_context(object, old, \"+\") %||%\n list(NULL) # we wrap `NULL` to a list for `for loop`.\n object <- .subset2(object, \"object\")\n object_name <- .subset2(object, \"object_name\")\n for (active in contexts) {\n quad@active <- active\n quad <- quad_layout_add(object, quad, object_name)\n }\n quad@active <- old\n quad\n}\n\n##################################################################\n#' @export\nquad_layout_add.quad_active <- function(object, quad, object_name) {\n if (!is.null(width <- .subset2(object, \"width\"))) {\n quad@width <- width\n }\n if (!is.null(height <- .subset2(object, \"height\"))) {\n quad@height <- height\n }\n quad@active <- NULL\n quad\n}\n\n#' @importFrom methods slot\n#' @export\nquad_layout_add.quad_anno <- function(object, quad, object_name) {\n position <- .subset2(object, \"position\")\n initialize <- .subset2(object, \"initialize\")\n stack <- slot(quad, position)\n if (is.null(stack) && !isFALSE(initialize)) {\n # try to initialize the annotation stack with the layout data\n direction <- to_direction(position)\n layout_design <- slot(quad, direction)\n # for the annotation stack, we try to take the data from the\n # quad layout\n quad_data <- quad@data\n data <- waiver() # use waiver() to indicate data is not initialized\n quad_matrix <- FALSE # the default value for `quad_matrix` in the stack\n if (is_continuous_design(layout_design)) { # the stack need a data frame\n if (!is.data.frame(quad_data)) {\n if (is.null(initialize)) {\n cli_warn(paste(\n \"`data` in {.fn {quad@name}} is\",\n \"{.obj_type_friendly {quad_data}}, but the\",\n \"{.field {position}} annotation stack need a\",\n \"{.cls data.frame}, won't initialize\",\n \"the {.field {position}} annotation stack\"\n ))\n } else {\n data <- NULL\n }\n } else {\n data <- quad_data\n }\n } else if (is.matrix(quad_data)) { # the stack need a matrix\n if (is_horizontal(direction)) {\n data <- quad_data\n } else {\n data <- ggalign_data_restore(t(quad_data), quad_data)\n }\n quad_matrix <- TRUE\n } else {\n if (is.null(initialize)) {\n cli_warn(paste(\n \"`data` in {.fn {quad@name}} is\",\n \"{.obj_type_friendly {quad_data}}, but the\",\n \"{.field {position}} annotation stack need a\",\n \"{.cls data.frame}, won't initialize\",\n \"the {.field {position}} annotation stack\"\n ))\n } else {\n data <- NULL\n }\n }\n if (!is.waive(data)) { # initialize the annotation stack\n stack <- new_stack_layout(\n data = data,\n direction = direction,\n # the layout parameters should be the same with `quad_layout()`\n design = layout_design,\n # we'll inherit the action data function when\n schemes = default_schemes(if (is.null(data)) NULL else waiver())\n )\n stack@heatmap$position <- position\n stack@heatmap$quad_matrix <- quad_matrix\n }\n } else if (!is.null(stack) && isTRUE(initialize)) {\n cli_abort(c(\n \"Cannot initialize the {position} annotation stack\",\n i = \"{position} annotation stack has already been initialized\"\n ))\n }\n\n if (!is.null(stack)) {\n # update parameters\n if (!is.null(size <- .subset2(object, \"size\"))) {\n stack@sizes <- size\n }\n if (!is.waive(free_guides <- .subset2(object, \"free_guides\"))) {\n stack@heatmap[\"free_guides\"] <- list(free_guides)\n }\n stack <- switch_chain_plot(\n stack, .subset2(object, \"what\"), quote(quad_anno())\n )\n slot(quad, position) <- stack\n }\n quad@active <- position\n quad\n}\n\n#' @export\nquad_layout_add.QuadLayout <- function(object, quad, object_name) {\n cli_abort(c(\n sprintf(\"Cannot add {.var {object_name}} to %s\", object_name(quad)),\n i = \"Did you mean to place multiple {.fn quad_layout} elements inside a {.fn stack_layout}?\"\n ))\n}\n\n#' @export\nquad_layout_add.StackLayout <- function(object, quad, object_name) {\n # we check if there is an active annotation\n if (is.null(position <- quad@active)) {\n cli_abort(c(\n sprintf(\"Cannot add {.var {object_name}} to %s\", object_name(quad)),\n i = \"no active annotation stack\",\n i = \"try to activate an annotation stack with {.fn anno_*}\"\n ))\n }\n # check the annotation stack is not initialized\n if (!is.null(slot(quad, position))) {\n cli_abort(c(\n sprintf(\"Cannot add {.var {object_name}} to %s\", object_name(quad)),\n i = \"{position} annotation stack already exists\"\n ))\n }\n # cannot contain nested layout\n if (!all(vapply(object@plot_list, is_craftbox, logical(1L),\n USE.NAMES = FALSE))) { # styler: off\n cli_abort(c(\n sprintf(\"Cannot add {.var {object_name}} to %s\", object_name(quad)),\n i = \"annotation stack cannot contain nested layout\"\n ))\n }\n # check quad layout is compatible with stack layout\n if (!identical(direction <- to_direction(position), object@direction)) {\n cli_abort(c(\n sprintf(\"Cannot add {.var {object_name}} to %s\", object_name(quad)),\n i = \"only {.field {direction}} stack is allowed in {position} annotation\"\n ))\n }\n if (length(object@sizes) > 1L) {\n cli_abort(c(\n sprintf(\"Cannot add {.var {object_name}} to %s\", object_name(quad)),\n i = \"{.arg sizes} must be of length one to use the stack as an annotation\"\n ))\n }\n quad_design <- slot(quad, direction)\n if (is_cross_layout(object) &&\n any(position == c(\"bottom\", \"right\")) &&\n !is_empty(object@cross_points)) {\n # if there are cross points in bottom or right annotation,\n # use the first design\n stack_design <- .subset2(object@odesign, 1L)\n } else {\n stack_design <- object@design\n }\n # check if we can align in this direction\n # `stack_layout()` is free from aligning obervations in this axis\n if (is_continuous_design(stack_design)) {\n if (!is_continuous_design(quad_design)) {\n cli_abort(c(\n sprintf(\n \"Cannot add {.var {object_name}} to %s\",\n object_name(quad)\n ),\n i = sprintf(\n \"%s cannot align continuous variable in {.field {direction}} direction\",\n object_name(quad)\n )\n ))\n }\n layout_design <- stack_design\n } else if (is_discrete_design(quad_design)) {\n layout_design <- melt_discrete_design(\n quad_design, stack_design,\n old_name = object_name(quad),\n new_name = object_name\n )\n } else {\n cli_abort(c(\n sprintf(\"Cannot add {.var {object_name}} to %s\", object_name(quad)),\n i = sprintf(\n \"%s cannot align discrete variable in {.field {direction}} direction\",\n object_name(quad)\n )\n ))\n }\n object@heatmap$position <- position\n slot(quad, position) <- object\n update_design(quad,\n direction = direction,\n design = layout_design,\n object_name = object_name\n )\n}\n\n#' @importFrom methods slot slot<-\n#' @export\nquad_layout_add.CraftBox <- function(object, quad, object_name) {\n if (is.null(position <- quad@active)) {\n cli_abort(c(\n sprintf(\"Cannot add {.var {object_name}} to %s\", object_name(quad)),\n i = \"no active annotation stack\",\n i = \"try to activate an annotation stack with {.fn anno_*}\"\n ))\n }\n if (is.null(stack <- slot(quad, position))) {\n cli_abort(c(\n sprintf(\"Cannot add {.var {object_name}} to %s\", object_name(quad)),\n i = \"the {.field {position}} annotation stack is not initialized\",\n i = \"Try to use {.code quad_anno(initialize = TRUE)} or you can add a {.code stack_layout()} manually\"\n ))\n }\n\n # add annotation -----------------------------\n stack <- chain_layout_add(object, stack, object_name)\n slot(quad, position) <- stack\n\n # if there are cross points in bottom or right annotation, we use\n # the first design\n if (is_cross_layout(stack) &&\n any(position == c(\"bottom\", \"right\")) &&\n !is_empty(stack@cross_points)) {\n new_design <- .subset2(stack@odesign, 1L)\n } else {\n new_design <- stack@design\n }\n\n update_design(\n quad,\n direction = to_direction(position),\n design = new_design,\n object_name = object_name\n )\n}\n\n#######################################################\n# used to add elements for main body\n#' @keywords internal\nquad_body_add <- function(object, quad, object_name) {\n UseMethod(\"quad_body_add\")\n}\n\n#' @importFrom ggplot2 ggplot_add\n#' @export\nquad_body_add.default <- function(object, quad, object_name) {\n quad@plot <- ggplot_add(object, ggfun(\"plot_clone\")(quad@plot), object_name)\n quad\n}\n\n#' @export\nquad_body_add.Coord <- function(object, quad, object_name) {\n if (!inherits(object, \"CoordCartesian\")) {\n cli_warn(c(\n \"only {.field cartesian coordinate} is supported\",\n i = \"will discard {.var {object_name}} directly\"\n ))\n return(quad)\n }\n NextMethod() # call default method\n}\n\n#' @export\nquad_body_add.layout_theme <- function(object, quad, object_name) {\n quad@theme <- update_layout_theme(quad@theme, object)\n quad\n}\n\n#' @export\nquad_body_add.ggalign_scheme <- function(object, quad, object_name) {\n name <- ggalign_scheme_name(object)\n quad@body_schemes[name] <- list(update_scheme(\n object, .subset2(quad@body_schemes, name), object_name\n ))\n quad\n}\n"], ["/ggalign/R/layout-heatmap-.R", "#' Create a heatmap\n#'\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' `heatmap_layout` is a specialized version of [`quad_discrete()`], which\n#' simplifies the creation of heatmap plots by integrating essential elements\n#' for a standard heatmap layout, ensuring that the appropriate data mapping and\n#' visualization layers are automatically applied. `ggheatmap` is an alias for\n#' `heatmap_layout`.\n#'\n#' @param data `r rd_layout_data()`. By default, it will try to inherit from\n#' parent layout. [`fortify_matrix()`] will be used to convert data to a\n#' matrix.\n#' @param ... Additional arguments passed to [`fortify_matrix()`].\n#' @inheritParams quad_layout\n#' @param filling A single string of `r oxford_or(c(\"raster\", \"tile\"))` to\n#' indicate the filling style. By default, `waiver()` is used, which means that\n#' if the input matrix has more than 20,000 cells (`nrow * ncol > 20000`),\n#' [`geom_raster()`][ggplot2::geom_raster] will be used for performance\n#' efficiency; for smaller matrices, [`geom_tile()`][ggplot2::geom_tile] will be\n#' used. To customize the filling style, set this to `NULL`.\n#'\n#' For backward compatibility, a single boolean value is acceptable: `TRUE`\n#' means `waiver()`, and `FALSE` means `NULL`.\n#'\n#' By default, the classic heatmap color scheme\n#' [`scale_fill_gradient2(low = \"blue\", high = \"red\")`][ggplot2::scale_fill_gradient2]\n#' is utilized for continuous values.\n#'\n#' You can use the options\n#' `r code_quote(sprintf(\"%s.heatmap_continuous_fill\", pkg_nm()))` or\n#' `r code_quote(sprintf(\"%s.heatmap_discrete_fill\", pkg_nm()))` to modify the\n#' default heatmap body filling color scale. See\n#' [`scale_fill_continuous()`][ggplot2::scale_fill_continuous] or\n#' [`scale_fill_discrete()`][ggplot2::scale_fill_discrete] for details on\n#' option settings.\n#'\n#' @section ggplot2 specification:\n#' The data input will be converted to a matrix using [`fortify_matrix()`], and\n#' the data in the underlying main plot will contain the following columns:\n#'\n#' - `.panel_x` and `.panel_y`: the column and row panel groups.\n#'\n#' - `.x` and `.y`: an integer index of `x` and `y` coordinates\n#'\n#' - `.discrete_x` and `.discrete_y`: a factor of the data labels (only\n#' applicable when `.row_names` and `.column_names` exists).\n#'\n#' - `.row_names` and `.column_names`: A character of the row and column names\n#' of the original matrix (only applicable when names exist).\n#'\n#' - `.row_index` and `.column_index`: the row and column index of the original\n#' matrix.\n#'\n#' - `value`: the actual matrix value.\n#'\n#' @return A `HeatmapLayout` object.\n#' @examples\n#' ggheatmap(1:10)\n#' ggheatmap(letters)\n#' ggheatmap(matrix(rnorm(81), nrow = 9L))\n#' @importFrom ggplot2 aes\n#' @export\nheatmap_layout <- function(data = NULL, mapping = aes(),\n ...,\n width = NA, height = NA, filling = waiver(),\n theme = NULL, active = NULL) {\n UseMethod(\"heatmap_layout\")\n}\n\n#' @usage NULL\n#' @export\n#' @rdname heatmap_layout\nggheatmap <- heatmap_layout\n\n#' @importFrom ggplot2 aes\n#' @importFrom rlang arg_match0\n#' @export\nheatmap_layout.default <- function(data = NULL, mapping = aes(),\n ...,\n width = NA, height = NA, filling = waiver(),\n theme = NULL, active = NULL) {\n # A single boolean value for compatible with `version <= 0.0.4`\n if (isTRUE(filling)) {\n filling <- waiver()\n } else if (isFALSE(filling)) {\n filling <- NULL\n } else if (!is.waive(filling) && !is.null(filling)) {\n filling <- arg_match0(filling, c(\"tile\", \"raster\"))\n }\n data <- data %|w|% NULL\n # we need a matrix to melted into long formated data frame\n data <- fortify_matrix(data = data, ...)\n ans <- new_quad_layout(\n name = \"ggheatmap\",\n data = data,\n mapping = mapping,\n theme = theme, active = active,\n width = width, height = height,\n class = \"HeatmapLayout\"\n )\n # add default mapping\n ans@plot <- ggadd_default(ans@plot, mapping = aes(.data$.x, .data$.y)) +\n ggplot2::labs(x = NULL, y = NULL)\n ans@filling <- filling\n ans\n}\n\n# used to create the heatmap layout\n#' @keywords internal\n#' @include layout-quad-.R\nmethods::setClass(\n \"HeatmapLayout\",\n contains = \"QuadLayout\",\n list(filling = \"ANY\") # parameters for heatmap body\n)\n"], ["/ggalign/R/layout-chain-stack-composer.R", "#' @keywords internal\nstack_composer <- function(direction) {\n structure(\n list(\n t = integer(), l = integer(),\n b = integer(), r = integer(),\n plots = list(), sizes = list(),\n direction = direction,\n align = 1L,\n # attributes used by `stack_layout()`\n left_or_top = FALSE, right_or_bottom = FALSE\n ),\n class = \"stack_composer\"\n )\n}\n\nstack_composer_add_plot <- function(composer, plot, t, l, b = t, r = l) {\n composer$t <- c(.subset2(composer, \"t\"), t)\n composer$l <- c(.subset2(composer, \"l\"), l)\n composer$b <- c(.subset2(composer, \"b\"), b)\n composer$r <- c(.subset2(composer, \"r\"), r)\n composer$plots <- c(.subset2(composer, \"plots\"), list(plot))\n composer\n}\n\n#' @importFrom rlang is_empty\nstack_composer_align_plot <- function(composer, plot, size) {\n if (is.null(plot)) {\n return(composer)\n }\n if (is_horizontal(.subset2(composer, \"direction\"))) {\n r_border <- .subset2(composer, \"r\")\n if (is_empty(r_border)) {\n l <- 1L\n } else {\n l <- max(r_border) + 1L\n }\n t <- .subset2(composer, \"align\")\n } else {\n b_border <- .subset2(composer, \"b\")\n if (is_empty(b_border)) {\n t <- 1L\n } else {\n t <- max(b_border) + 1L\n }\n l <- .subset2(composer, \"align\")\n }\n composer$sizes <- c(.subset2(composer, \"sizes\"), list(size))\n stack_composer_add_plot(composer, plot, t, l)\n}\n\nstack_composer_add <- function(plot, stack, composer, ...) {\n UseMethod(\"stack_composer_add\")\n}\n\n#' @importFrom utils packageVersion\n#' @export\nstack_composer_add.CraftBox <- function(plot, stack, composer, design, ...,\n schemes, theme,\n released_spaces,\n direction, position) {\n size <- plot@size\n\n # for `released_spaces`, release the `free_spaces` in a single plot\n plot_schemes <- inherit_schemes(plot@schemes, schemes)\n if (!is.null(released_spaces)) {\n plot_spaces <- .subset2(\n .subset2(plot_schemes, \"scheme_align\"), \"free_spaces\"\n )\n if (is_string(plot_spaces)) {\n plot_spaces <- setdiff_position(plot_spaces, released_spaces)\n if (!nzchar(plot_spaces)) plot_spaces <- NULL\n plot_schemes$scheme_align[\"free_spaces\"] <- list(plot_spaces)\n }\n }\n\n # let `Align` to determine how to build the plot\n craftsman <- plot@craftsman # `Craftsman` object\n plot <- plot@plot\n if (!craftsman$free_facet && is_discrete_design(design)) {\n if (nlevels(.subset2(design, \"panel\")) > 1L) {\n if (is_horizontal(direction)) {\n facet <- ggplot2::facet_grid(\n rows = ggplot2::vars(.data$.panel),\n scales = \"free_y\", space = \"free\",\n drop = FALSE, as.table = FALSE\n )\n free_row <- FALSE\n free_column <- TRUE\n } else {\n facet <- ggplot2::facet_grid(\n cols = ggplot2::vars(.data$.panel),\n scales = \"free_x\", space = \"free\",\n drop = FALSE, as.table = FALSE\n )\n free_row <- TRUE\n free_column <- FALSE\n }\n } else {\n facet <- facet_stack(direction, craftsman$layout_name)\n }\n plot <- ggmelt_facet(plot, facet,\n free_row = free_row, free_column = free_column\n )\n }\n if (!craftsman$free_coord) {\n plot <- gguse_linear_coord(plot, layout_name = craftsman$layout_name)\n }\n\n # set limits and default scales\n if (!craftsman$free_limits) {\n if (is_horizontal(direction)) {\n plot <- plot + ggalign_design(\n y = design,\n ylabels = .subset(craftsman$labels, .subset2(design, \"index\"))\n )\n } else {\n plot <- plot + ggalign_design(\n x = design,\n xlabels = .subset(craftsman$labels, .subset2(design, \"index\"))\n )\n }\n }\n\n # let `Craftsman` add other components\n plot <- craftsman$build_plot(plot, design = design, ...)\n plot <- craftsman$finish_plot(plot, plot_schemes, theme)\n\n # Let layout finally modify the plot\n plot <- chain_decorate(stack, plot)\n\n # add the plot to the composer\n stack_composer_align_plot(composer, plot, size)\n}\n\n#' @importFrom grid unit.c unit\nstack_composer_add.QuadLayout <- function(plot, stack, composer, schemes, theme,\n direction, ...) {\n patches <- quad_build(plot, schemes, theme, direction)\n plots <- .subset2(patches, \"plots\")\n sizes <- .subset2(patches, \"sizes\")\n\n if (is_horizontal(.subset2(composer, \"direction\"))) {\n composer$left_or_top <- .subset2(composer, \"left_or_top\") ||\n !is.null(.subset2(plots, \"top\"))\n composer$right_or_bottom <- .subset2(composer, \"right_or_bottom\") ||\n !is.null(.subset2(plots, \"bottom\"))\n composer <- stack_composer_align_plot(\n composer,\n .subset2(plots, \"left\"),\n .subset2(sizes, \"left\")\n )\n composer <- stack_composer_align_plot(\n composer,\n .subset2(plots, \"main\"),\n .subset2(.subset2(sizes, \"main\"), \"width\")\n )\n l <- max(.subset2(composer, \"r\"))\n if (!is.null(top <- .subset2(plots, \"top\"))) {\n if (.subset2(composer, \"align\") == 1L) {\n composer$t <- .subset2(composer, \"t\") + 1L\n composer$b <- .subset2(composer, \"b\") + 1L\n composer$align <- .subset2(composer, \"align\") + 1L\n }\n if (!is_null_unit(size <- .subset2(sizes, \"top\"))) {\n attr(top, \"vp\")$height <- size\n }\n composer <- stack_composer_add_plot(composer, top, t = 1L, l = l)\n }\n if (!is.null(bottom <- .subset2(plots, \"bottom\"))) {\n if (!is_null_unit(size <- .subset2(sizes, \"bottom\"))) {\n attr(bottom, \"vp\")$height <- size\n }\n composer <- stack_composer_add_plot(composer, bottom,\n t = .subset2(composer, \"align\") + 1L, l = l\n )\n }\n composer <- stack_composer_align_plot(\n composer,\n .subset2(plots, \"right\"),\n .subset2(sizes, \"right\")\n )\n } else {\n composer$left_or_top <- .subset2(composer, \"left_or_top\") ||\n !is.null(.subset2(plots, \"left\"))\n composer$right_or_bottom <- .subset2(composer, \"right_or_bottom\") ||\n !is.null(.subset2(plots, \"right\"))\n composer <- stack_composer_align_plot(\n composer,\n .subset2(plots, \"top\"),\n .subset2(sizes, \"top\")\n )\n composer <- stack_composer_align_plot(\n composer,\n .subset2(plots, \"main\"),\n .subset2(.subset2(sizes, \"main\"), \"height\")\n )\n t <- max(.subset2(composer, \"b\"))\n if (!is.null(left <- .subset2(plots, \"left\"))) {\n if (.subset2(composer, \"align\") == 1L) {\n composer$l <- .subset2(composer, \"l\") + 1L\n composer$r <- .subset2(composer, \"r\") + 1L\n composer$align <- .subset2(composer, \"align\") + 1L\n }\n if (!is_null_unit(size <- .subset2(sizes, \"left\"))) {\n attr(left, \"vp\")$width <- size\n }\n composer <- stack_composer_add_plot(composer, left, t = t, l = 1L)\n }\n if (!is.null(right <- .subset2(plots, \"right\"))) {\n if (!is_null_unit(size <- .subset2(sizes, \"right\"))) {\n attr(right, \"vp\")$width <- size\n }\n composer <- stack_composer_add_plot(composer, right,\n t = t, l = .subset2(composer, \"align\") + 1L\n )\n }\n composer <- stack_composer_align_plot(\n composer,\n .subset2(plots, \"bottom\"),\n .subset2(sizes, \"bottom\")\n )\n }\n composer\n}\n\n#' @export\nstack_composer_add.list <- function(plot, stack, composer, ...) {\n for (p in plot) {\n composer <- stack_composer_add(\n plot = p, stack = stack, composer = composer, ...\n )\n }\n composer\n}\n"], ["/ggalign/R/craft-align-order.R", "#' Order observations based on weights\n#'\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' Ordering observations based on summary weights or a specified ordering\n#' character or integer index.\n#'\n#' @param weights A summary function which accepts a data and returns the\n#' weights for each observations. Alternatively, you can provide an ordering\n#' index as either an integer or a character. Since characters have been\n#' designated as character indices, if you wish to specify a function name as a\n#' string, you must enclose it with [`I()`].\n#' @param ... <[dyn-dots][rlang::dyn-dots]> Additional arguments passed to\n#' function provided in `weights` argument.\n#' @param reverse A boolean value. Should the sort order be in reverse?\n#' @param strict A boolean value indicates whether the order should be strict.\n#' If previous groups has been established, and strict is `FALSE`, this will\n#' reorder the observations in each group.\n#' @param data A `matrix`, `data frame`, or atomic vector used as the input for\n#' the `weights` function. Alternatively, you can specify a `function`\n#' (including purrr-like lambda syntax) that will be applied to the layout\n#' matrix, transforming it as necessary for weight calculations. By default, it\n#' will inherit from the layout matrix.\n#' @inheritParams align\n#' @inheritSection align Discrete Axis Alignment\n#' @examples\n#' ggheatmap(matrix(rnorm(81), nrow = 9)) +\n#' anno_left() +\n#' align_order(I(\"rowMeans\"))\n#' @importFrom ggplot2 waiver\n#' @importFrom rlang list2\n#' @export\nalign_order <- function(weights = rowMeans, ...,\n reverse = FALSE, strict = TRUE, data = NULL,\n active = NULL) {\n if (is.numeric(weights) ||\n (is.character(weights) && !inherits(weights, \"AsIs\"))) {\n # vec_duplicate_any is slight faster than `anyDuplicated`\n if (vec_any_missing(weights) || vec_duplicate_any(weights)) {\n cli_abort(paste(\n \"{.arg weights} must be an ordering numeric or character\",\n \"without missing value or ties\"\n ))\n } else if (is.numeric(weights)) {\n weights <- vec_cast(weights, integer())\n }\n if (vec_size(weights) == 0L) {\n cli_abort(\"{.arg weights} cannot be empty\")\n }\n if (!is.null(data)) {\n cli_warn(c(\n \"{.arg data} won't be used\",\n i = \"{.arg weights} is not a {.cls function}\"\n ))\n }\n } else {\n weights <- rlang::as_function(weights)\n data <- data %||% waiver()\n }\n assert_bool(strict)\n assert_bool(reverse)\n assert_active(active)\n active <- update_active(active, new_active(use = FALSE))\n align(\n align = AlignOrder,\n weights = weights,\n params = list2(...),\n reverse = reverse,\n strict = strict,\n active = active,\n data = data\n )\n}\n\n#' @importFrom ggplot2 ggproto\n#' @importFrom rlang inject is_atomic\nAlignOrder <- ggproto(\"AlignOrder\", CraftAlign,\n interact_layout = function(self, layout) {\n if (is.function(self$weights)) {\n layout <- ggproto_parent(AlignOrder2, self)$interact_layout(layout)\n } else {\n layout <- ggproto_parent(CraftAlign, self)$interact_layout(layout)\n if (is.null(layout_nobs <- .subset2(layout@design, \"nobs\"))) {\n layout@design[\"nobs\"] <- list(vec_size(self$weights))\n } else {\n assert_mismatch_nobs(\n self, layout_nobs, vec_size(self$weights),\n arg = \"weights\"\n )\n }\n self$labels <- vec_names(layout@data)\n }\n layout\n },\n compute = function(self, panel, index) {\n if (is.function(self$weights)) {\n ans <- inject(self$weights(self$data, !!!self$params))\n if (!is_atomic(ans)) {\n cli_abort(\n \"{.arg weights} must return an atomic weights\",\n call = self$call\n )\n }\n assert_mismatch_nobs(\n self, vec_size(ans), vec_size(ans),\n arg = \"weights\"\n )\n ans\n }\n },\n align = function(self, panel, index) {\n if (is.function(self$weights)) {\n index <- order(self$statistics)\n } else {\n index <- vec_as_location(\n self$weights,\n n = vec_size(self$weights),\n names = self$labels,\n missing = \"error\",\n call = self$call\n )\n }\n if (self$reverse) index <- rev(index)\n assert_reorder(self, panel, index, self$strict)\n list(panel, index)\n },\n summary_align = function(self) c(TRUE, FALSE)\n)\n"], ["/ggalign/R/alignpatch-.R", "# here is copied from patchwork\n# we modified the `patchwork` package for following reasons:\n# 1. collect guides for each side (should be merged into patchwork, not allowed\n# to be merged: https://github.com/thomasp85/patchwork/issues/379).\n# 2. `free_*()` functions: see https://github.com/thomasp85/patchwork/issues/379\n# - `free_align()`: added\n# - `free_border()`: not added\n# - `free_lab()`: added\n# - `free_space()`: added\n# - `free_vp()`: not added\n# 3. Added titles around the plot top, left, bottom, and right\n# (`patch_titles()`)\nTABLE_ROWS <- 18L + 2L\nTABLE_COLS <- 15L + 2L\n\nTOP_BORDER <- 9L + 1L\nLEFT_BORDER <- 7L + 1L\nBOTTOM_BORDER <- 8L + 1L\nRIGHT_BORDER <- 7L + 1L\n\n# top-bottom\n# 1: margin\n# 2: tag\n# 3: title\n# 4: subtitle\n# 5: guide-box-top\n# 6: legend.box.spacing\n# feature: insert patch title\n# 7: xlab-t\n# strip.placement = \"inside\"/\"outside\"\n# 8: axis-t/strip-t\n# 9: strip-t/axis-t\n# 10: panel\n# 11: strip-b\n# 12: axis-b\n# 13: xlab-b\n# feature: insert patch title\n# 14: legend.box.spacing\n# 15: guide-box-bottom\n# 16: caption\n# 17: tag\n# 18: margin\n\n# left-right\n#\n# 1: margin\n# 2: tag\n# 3: guide-box-left\n# 4: legend.box.spacing\n# feature: insert patch title\n# 5: ylab-l\n# 6: axis-l\n# 8: panel\n# 10: axis-r\n# 11: ylab-r\n# feature: insert patch title\n# 12: legend.box.spacing\n# 13: guide-box-right\n# 14: tag\n# 15: margin\n\n.TLBR <- c(\"top\", \"left\", \"bottom\", \"right\")\n.tlbr <- c(\"t\", \"l\", \"b\", \"r\")\n\n# position is a single string contains `.tlbr`\nsetdiff_position <- function(x, y) gsub(sprintf(\"[%s]\", y), \"\", x)\nunion_position <- function(x, y) paste0(x, gsub(sprintf(\"[%s]\", x), \"\", y))\nsplit_position <- function(x) {\n vec_unique(.subset2(strsplit(x, \"\", fixed = TRUE), 1L))\n}\n\n# pos is an atomic character\nsetup_pos <- function(x) unname(complete_pos(split_position(x)))\n\nsetup_guides <- function(x) {\n .subset(\n c(t = \"top\", l = \"left\", b = \"bottom\", r = \"right\", i = \"inside\"),\n split_position(x)\n )\n}\n\ncomplete_pos <- function(x) {\n .subset(c(t = \"top\", l = \"left\", b = \"bottom\", r = \"right\"), x)\n}\n\nopposite_pos <- function(pos) {\n switch(pos,\n top = \"bottom\",\n bottom = \"top\",\n left = \"right\",\n right = \"left\"\n )\n}\n\n#' @importFrom ggplot2 zeroGrob\n#' @importFrom gtable gtable gtable_add_grob\n#' @importFrom grid unit\nmake_patch_table <- function() {\n widths <- unit(rep(0L, TABLE_COLS), \"mm\")\n widths[LEFT_BORDER + 1L] <- unit(1L, \"null\")\n heights <- unit(rep(0L, TABLE_ROWS), \"mm\")\n heights[TOP_BORDER + 1L] <- unit(1L, \"null\")\n ans <- gtable(widths, heights)\n gtable_add_grob(ans,\n list(zeroGrob()), TOP_BORDER + 1L, LEFT_BORDER + 1L,\n z = -Inf, name = \"panel-area\"\n )\n}\n\n#' Generate a plot grob.\n#'\n#' @param x An object to be converted into a [grob][grid::grob].\n#' @return A [`grob()`][grid::grob] object.\n#' @examples\n#' ggalignGrob(ggplot())\n#' @export\nggalignGrob <- function(x) {\n ggalign_gtable(ggalign_build(x))\n}\n\n# Now, we only define `ggalign_gtable` method for `alignpatches` and `ggplot`\n# `ggalign_build` must return these objects\nggalign_build <- function(x) UseMethod(\"ggalign_build\")\n\nggalign_gtable <- function(x) UseMethod(\"ggalign_gtable\")\n\n#' @export\nggalign_gtable.gtable <- function(x) x\n\n#' Prepare plots to be aligned with `align_plots`\n#'\n#' @param x A plot object to be prepared for alignment.\n#' @details\n#' `ggalign` has implement `alignpatch` method for following objects:\n#' - [`ggplot`][ggplot2::ggplot]\n#' - [`alignpatches`][align_plots]\n#' - [`wrapped_plot`][ggwrap]\n#' - [`patch`][patchwork::patchGrob]\n#' - [`wrapped_patch`][patchwork::wrap_elements]\n#' - [`spacer`][patchwork::plot_spacer]\n#'\n#' @return A `Patch` object.\n#' @examples\n#' alignpatch(ggplot())\n#' @seealso [`align_plots()`]\n#' @export\n#' @keywords internal\nalignpatch <- function(x) UseMethod(\"alignpatch\")\n\n#' @export\nalignpatch.default <- function(x) {\n cli_abort(\"Cannot align {.obj_type_friendly {x}}\")\n}\n\n#' @export\nalignpatch.NULL <- function(x) NULL\n\npatch_no_method <- function(plot, method) {\n cli_abort(\"no {.fn {method}} method for {.obj_type_friendly {plot}}\")\n}\n\n#' @importFrom ggplot2 ggproto\n#' @importFrom grid unit.c\nPatch <- ggproto(\n \"Patch\", NULL,\n # following fields will be added by `alignpatch()`\n plot = NULL,\n # following fields will be added in `alignpatches$patch_gtable()`\n # borders = NULL, gt = NULL,\n\n #' @param guides `guides` argument from the parent alignpatches\n #' @return Which side of guide legends should be collected by the parent\n #' `alignpatches` object?\n #' @noRd\n set_guides = function(self, guides) {\n patch_no_method(self$plot, \"set_guides\")\n },\n patch_gtable = function(self, theme, guides, plot = self$plot) {\n patch_no_method(self$plot, \"patch_gtable\")\n },\n collect_guides = function(self, guides, gt = self$gt) {\n if (is.null(guides)) return(list()) # styler: off\n layout <- .subset2(gt, \"layout\")\n grobs <- .subset2(gt, \"grobs\")\n guides_ind <- grep(\"guide-box\", .subset2(layout, \"name\"))\n guides_loc <- vec_slice(layout, guides_ind)\n collected_guides <- vector(\"list\", length(guides))\n names(collected_guides) <- guides\n panel_loc <- find_panel(gt)\n remove_grobs <- NULL\n for (guide_pos in guides) {\n guide_ind <- switch(guide_pos,\n top = .subset2(guides_loc, \"b\") < .subset2(panel_loc, \"t\"),\n left = .subset2(guides_loc, \"r\") < .subset2(panel_loc, \"l\"),\n bottom = .subset2(guides_loc, \"t\") > .subset2(panel_loc, \"b\"),\n right = .subset2(guides_loc, \"l\") > .subset2(panel_loc, \"r\"),\n inside = .subset2(guides_loc, \"t\") >= .subset2(panel_loc, \"t\") &\n .subset2(guides_loc, \"b\") <= .subset2(panel_loc, \"b\") &\n .subset2(guides_loc, \"l\") >= .subset2(panel_loc, \"l\") &\n .subset2(guides_loc, \"r\") <= .subset2(panel_loc, \"r\")\n )\n if (!any(guide_ind)) next\n guide_loc <- vec_slice(guides_loc, guide_ind)\n guide_ind <- .subset(guides_ind, guide_ind)\n remove_grobs <- c(guide_ind, remove_grobs)\n collected_guides[[guide_pos]] <- .subset2(grobs, guide_ind)\n\n # remove the guide spaces from the original gtable\n # for inside guide, no need to remove the spaces\n if (guide_pos == \"inside\") next\n\n space_pos <- switch(guide_pos,\n top = ,\n left = 1L,\n bottom = ,\n right = -1L\n )\n if (guide_pos %in% c(\"right\", \"left\")) {\n gt$widths[c(guide_loc$l, guide_loc$l + space_pos)] <- unit(\n c(0L, 0L), \"mm\"\n )\n } else if (guide_pos %in% c(\"bottom\", \"top\")) {\n gt$heights[c(guide_loc$t, guide_loc$t + space_pos)] <- unit(\n c(0L, 0L), \"mm\"\n )\n }\n }\n if (length(remove_grobs)) {\n gt <- subset_gt(gt, -remove_grobs, trim = FALSE)\n }\n self$gt <- gt\n collected_guides\n },\n respect = function(self, gt = self$gt) isTRUE(.subset2(gt, \"respect\")),\n align_panel_sizes = function(self, panel_width, panel_height,\n gt = self$gt) {\n list(width = panel_width, height = panel_height, respect = FALSE)\n },\n get_sizes = function(self, free = NULL, gt = self$gt) {\n ans <- .subset2(gt, \"heights\")\n if (any(free == \"t\")) {\n top <- unit(rep_len(0, TOP_BORDER), \"mm\")\n } else {\n top <- ans[seq_len(TOP_BORDER)]\n }\n if (any(free == \"b\")) {\n bottom <- unit(rep_len(0, BOTTOM_BORDER), \"mm\")\n } else {\n bottom <- ans[seq(length(ans) - BOTTOM_BORDER + 1L, length(ans))]\n }\n ans <- .subset2(gt, \"widths\")\n if (any(free == \"l\")) {\n left <- unit(rep_len(0, LEFT_BORDER), \"mm\")\n } else {\n left <- ans[seq_len(LEFT_BORDER)]\n }\n if (any(free == \"r\")) {\n right <- unit(rep_len(0, RIGHT_BORDER), \"mm\")\n } else {\n right <- ans[seq(length(ans) - RIGHT_BORDER + 1L, length(ans))]\n }\n list(\n widths = unit.c(left, unit(0, \"mm\"), right),\n heights = unit.c(top, unit(0, \"mm\"), bottom)\n )\n },\n align_border = function(self, t = NULL, l = NULL, b = NULL, r = NULL,\n gt = self$gt) {\n if (!is.null(t)) gt$heights[seq_along(t)] <- t\n if (!is.null(l)) gt$widths[seq_along(l)] <- l\n if (!is.null(b)) {\n n_row <- nrow(gt)\n gt$heights[seq(n_row - length(b) + 1L, n_row)] <- b\n }\n if (!is.null(r)) {\n n_col <- ncol(gt)\n gt$widths[seq(n_col - length(r) + 1L, n_col)] <- r\n }\n gt\n },\n split_gt = function(self, gt = self$gt) {\n isbg <- .subset2(.subset2(gt, \"layout\"), \"name\") == \"background\"\n if (any(isbg)) {\n bg <- .subset(.subset2(gt, \"grobs\"), isbg) # a list of background\n plot <- subset_gt(gt, !isbg, trim = FALSE)\n } else {\n bg <- NULL\n plot <- gt\n }\n list(bg = bg, plot = plot)\n },\n add_plot = function(self, gt, plot, t, l, b, r, name, z = 2L) {\n gtable_add_grob(\n gt,\n grobs = plot,\n t = t, l = l, b = b, r = r,\n name = name, z = z\n )\n },\n add_background = function(self, gt, bg, t, l, b, r, name, z = 1L) {\n gtable_add_grob(\n gt,\n grobs = bg,\n t = t, l = l, b = b, r = r,\n name = name, z = z\n )\n },\n free_border = function(self, borders, gt = self$gt) {\n patch_no_method(self$plot, \"free_border\")\n },\n align_free_border = function(self, borders,\n t = NULL, l = NULL, b = NULL, r = NULL,\n gt = self$gt) {\n patch_no_method(self$plot, \"align_free_border\")\n },\n free_lab = function(self, labs, gt = self$gt) {\n patch_no_method(self$plot, \"free_lab\")\n }\n)\n"], ["/ggalign/R/ggplot-geom-rect3d.R", "#' Add z-aesthetic for geom_tile\n#'\n#' @section new aesthetics:\n#' - `z`: the third dimention (in the z direction), use\n#' [`scale_z_continuous()`] to control the ranges.\n#' - `theta`: Angle between x-axis and z-axis.\n#' @inheritParams ggplot2::layer\n#' @inheritParams ggplot2::geom_polygon\n#' @inheritParams ggplot2::geom_path\n#' @aesthetics GeomRect3d\n#' @examples\n#' set.seed(123)\n#' small_mat <- matrix(rnorm(81), nrow = 9)\n#' rownames(small_mat) <- paste0(\"row\", seq_len(nrow(small_mat)))\n#' colnames(small_mat) <- paste0(\"column\", seq_len(ncol(small_mat)))\n#' ggheatmap(small_mat,\n#' filling = FALSE,\n#' theme = theme(\n#' legend.box.spacing = unit(10, \"mm\"),\n#' plot.margin = margin(t = 15, unit = \"mm\")\n#' )\n#' ) +\n#' geom_tile3d(\n#' aes(fill = value, z = value, width = 0.8, height = 0.8),\n#' color = \"black\"\n#' ) +\n#' scale_fill_viridis_c(\n#' option = \"plasma\",\n#' breaks = scales::breaks_pretty(3L)\n#' ) +\n#' coord_cartesian(clip = \"off\")\n#'\n#' @export\ngeom_rect3d <- function(mapping = NULL, data = NULL, stat = \"identity\",\n position = \"identity\", ...,\n lineend = \"butt\", linejoin = \"round\", linemitre = 10,\n na.rm = FALSE, show.legend = NA, inherit.aes = TRUE) {\n ggplot2::layer(\n data = data,\n mapping = mapping,\n stat = stat,\n geom = GeomRect3d,\n position = position,\n show.legend = show.legend,\n inherit.aes = inherit.aes,\n params = list(\n lineend = lineend,\n linejoin = linejoin,\n linemitre = linemitre,\n na.rm = na.rm, ...\n )\n )\n}\n\n#' @importFrom ggplot2 ggproto fill_alpha\nGeomRect3d <- ggproto(\n \"GeomRect3d\",\n ggplot2::GeomRect,\n required_aes = c(ggplot2::GeomRect$required_aes, \"z\"),\n non_missing_aes = c(ggplot2::GeomRect$non_missing_aes, \"z\", \"theta\"),\n setup_data = function(self, data, params) {\n theta <- data$theta %||% .subset2(params, \"theta\")\n if (!is.null(theta) && any(theta <= 0 || theta >= 90)) {\n cli_abort(\n \"value mapped to {.field theta} aesthetic must > 0 and < 90.\"\n )\n }\n data$theta <- theta %||% 60\n ggproto_parent(ggplot2::GeomRect, self)$setup_data(data, params)\n },\n draw_panel = function(self, data, panel_params, coord, lineend = \"butt\",\n linejoin = \"round\", linemitre = 10) {\n data <- setup_3d_data(data)\n # Transform to viewport coords\n coords <- coord$transform(data, panel_params)\n\n # collapse the gpar value\n data <- .subset2(\n vec_split(\n data[setdiff(names(data), c(\"x\", \"y\", \"width\", \"height\"))],\n .subset2(data, \"polygon_id\")\n ),\n \"val\"\n )\n data <- vec_rbind(!!!lapply(data, vec_unique))\n\n # Draw as grob\n grid::polygonGrob(\n x = coords$x,\n y = coords$y,\n id = coords$polygon_id,\n default.units = \"native\",\n gp = gpar(\n col = data$colour,\n fill = fill_alpha(data$fill, data$alpha),\n lwd = data$linewidth,\n lty = data$linetype,\n lineend = lineend,\n linejoin = linejoin,\n linemitre = linemitre\n )\n )\n }\n)\n\nsetup_3d_data <- function(data) {\n data <- vec_slice(\n data,\n order(\n .subset2(data, \"xmin\"),\n .subset2(data, \"ymin\"),\n decreasing = TRUE\n )\n )\n coords <- .mapply(\n function(xmin, xmax, ymin, ymax, z, theta, ...) {\n if (z == 0L) {\n # fallback to tile\n data_frame0(\n x = vec_c(xmin, xmax, xmax, xmin),\n y = vec_rep_each(c(ymin, ymax), 2L)\n )\n } else {\n offset_x <- z * cos(theta / 180 * pi)\n z_xmin <- xmin + offset_x\n z_xmax <- xmax + offset_x\n offset_y <- z * sin(theta / 180 * pi)\n z_ymin <- ymin + offset_y\n z_ymax <- ymax + offset_y\n data_frame0(\n x = vec_c(\n xmin, z_xmin, z_xmax, xmax, xmin, xmin,\n z_xmin, z_xmin, z_xmin, z_xmax, z_xmax, z_xmin\n ),\n y = vec_c(\n ymin, z_ymin, z_ymin, ymin, ymin, ymax,\n z_ymax, z_ymin, z_ymax, z_ymax, z_ymin, z_ymin\n )\n )\n }\n },\n data,\n MoreArgs = NULL\n )\n vec_cbind(\n vec_rbind(!!!coords),\n vec_rep_each(\n data[\n vec_set_difference(\n names(data),\n c(\"x\", \"xmin\", \"xmax\", \"y\", \"ymin\", \"ymax\", \"z\")\n )\n ],\n list_sizes(coords)\n ),\n polygon_id = vec_rep_each(seq_along(coords), list_sizes(coords))\n )\n}\n\n#' @aesthetics GeomTile3d\n#' @importFrom rlang list2\n#' @export\n#' @rdname geom_rect3d\ngeom_tile3d <- function(mapping = NULL, data = NULL, stat = \"identity\",\n position = \"identity\", ...,\n lineend = \"butt\", linejoin = \"round\", linemitre = 10,\n na.rm = FALSE, show.legend = NA, inherit.aes = TRUE) {\n ggplot2::layer(\n data = data,\n mapping = mapping,\n stat = stat,\n geom = GeomTile3d,\n position = position,\n show.legend = show.legend,\n inherit.aes = inherit.aes,\n params = list(\n lineend = lineend,\n linejoin = linejoin,\n linemitre = linemitre,\n na.rm = na.rm, ...\n )\n )\n}\n\n#' @importFrom ggplot2 ggproto ggproto_parent\nGeomTile3d <- ggproto(\n \"GeomTile3d\",\n ggplot2::GeomTile,\n required_aes = c(ggplot2::GeomTile$required_aes, \"z\"),\n non_missing_aes = c(ggplot2::GeomTile$non_missing_aes, \"z\", \"theta\"),\n setup_data = function(self, data, params) {\n theta <- data$theta %||% .subset2(params, \"theta\")\n if (!is.null(theta) && any(theta <= 0 || theta >= 90)) {\n cli_abort(\n \"value mapped to {.field theta} aesthetic must > 0 and < 90.\"\n )\n }\n data$theta <- theta %||% 60\n ggproto_parent(ggplot2::GeomTile, self)$setup_data(data, params)\n },\n draw_panel = function(self, data, panel_params, coord, lineend = \"butt\",\n linejoin = \"round\", linemitre = 10) {\n ggproto_parent(GeomRect3d, self)$draw_panel(\n data = data, panel_params = panel_params, coord = coord,\n lineend = lineend, linejoin = linejoin, linemitre = linemitre\n )\n }\n)\n\n#' z scales\n#'\n#' @param ... Other arguments passed on to\n#' [`continuous_scale()`][ggplot2::continuous_scale],\n#' [`binned_scale()`][ggplot2::binned_scale], or\n#' [`discrete_scale()`][ggplot2::discrete_scale] as appropriate, to control\n#' name, limits, breaks, labels and so forth.\n#' @param range Output range of z values. Must larger than 0.\n#' @inheritParams ggplot2::continuous_scale\n#' @seealso [`geom_tile3d()`]/[`geom_rect3d()`]\n#' @export\n#' @examples\n#'\n#' set.seed(7)\n#' mat <- matrix(runif(100), 10)\n#' rownames(mat) <- LETTERS[1:10]\n#' colnames(mat) <- letters[1:10]\n#' ggheatmap(mat,\n#' filling = FALSE,\n#' theme = theme(\n#' legend.box.spacing = unit(10, \"mm\"),\n#' plot.margin = margin(t = 15, unit = \"mm\")\n#' )\n#' ) +\n#' geom_tile3d(aes(fill = value, z = value, width = 0.8, height = 0.8)) +\n#' scale_z_continuous(range = c(0.2, 1)) +\n#' coord_cartesian(clip = \"off\")\n#' @export\nscale_z_continuous <- function(name = waiver(), ..., range = c(0.1, 1),\n guide = \"none\") {\n if (min(range) < 0) {\n cli_abort(\"{.arg range} must contain only positive values\")\n }\n ggplot2::continuous_scale(\"z\",\n name = name, palette = scales::pal_rescale(range), ...,\n guide = guide\n )\n}\n\n#' @rdname scale_z_continuous\n#' @export\nscale_z_binned <- function(name = waiver(), ..., range = c(0.1, 1),\n guide = \"none\") {\n if (min(range) < 0) {\n cli_abort(\"{.arg range} must contain only positive values\")\n }\n ggplot2::binned_scale(\"z\",\n name = name, palette = scales::pal_rescale(range), ...,\n guide = guide\n )\n}\n\n#' @rdname scale_z_continuous\n#' @export\nscale_z_discrete <- function(...) {\n cli_warn(\"Using {z} for a discrete variable is not advised.\")\n args <- list2(...)\n args$call <- args$call %||% current_call()\n rlang::exec(scale_z_ordinal, !!!args)\n}\n\n#' @rdname scale_z_continuous\n#' @export\nscale_z_ordinal <- function(name = waiver(), ..., range = c(0.1, 1),\n guide = \"none\") {\n if (min(range) < 0) {\n cli_abort(\"{.arg range} must contain only positive values\")\n }\n ggplot2::discrete_scale(\n \"z\",\n name = name,\n palette = function(n) seq(range[1], range[2], length.out = n),\n ...,\n gudie = guide\n )\n}\n\n#' @rdname scale_z_continuous\n#' @export\n#' @usage NULL\nscale_z_datetime <- function(name = waiver(), ..., range = c(0.1, 1),\n guide = \"none\") {\n if (min(range) < 0) {\n cli_abort(\"{.arg range} must contain only positive values\")\n }\n ggplot2::datetime_scale(\n aesthetics = \"z\", transform = \"time\", name = name,\n palette = scales::pal_rescale(range),\n ..., guide = guide\n )\n}\n\n#' @rdname scale_z_continuous\n#' @export\n#' @usage NULL\nscale_z_date <- function(name = waiver(), ..., range = c(0.1, 1),\n guide = \"none\") {\n if (min(range) < 0) {\n cli_abort(\"{.arg range} must contain only positive values\")\n }\n ggplot2::datetime_scale(\n aesthetics = \"z\", transform = \"date\", name = name,\n palette = scales::pal_rescale(range),\n ..., guide = guide\n )\n}\n"], ["/ggalign/R/alignpatch-align_plots.R", "#' Arrange multiple plots into a grid\n#'\n#' @param ... <[dyn-dots][rlang::dyn-dots]> A list of plots, ususally the\n#' ggplot object. Use `NULL` to indicate an empty spacer.\n#' @param ncol,nrow The dimensions of the grid to create - if both are `NULL` it\n#' will use the same logic as [`facet_wrap()`][ggplot2::facet_wrap] to set the\n#' dimensions\n#' @param byrow If `FALSE` the plots will be filled in in column-major order.\n#' @param widths,heights The relative widths and heights of each column and row\n#' in the grid. Will get repeated to match the dimensions of the grid. The\n#' special value of `NA` will behave as `1null` unit unless a fixed aspect plot\n#' is inserted in which case it will allow the dimension to expand or contract\n#' to match the aspect ratio of the content.\n#' @param area Specification of the location of areas in the layout. Can\n#' either be specified as a text string or by concatenating calls to\n#' [`area()`] together.\n#' @param guides A string with one or more of `r oxford_and(c(.tlbr, \"i\"))`\n#' indicating which side of guide legends should be collected. Defaults to\n#' [`waiver()`][ggplot2::waiver()], which inherits from the parent layout. If\n#' there is no parent layout, or if `NULL` is provided, no guides will be\n#' collected.\n#' @param theme A [`theme()`][ggplot2::theme] object used to customize various\n#' elements of the layout. By default, the theme will inherit from the parent\n#' `layout`.\n#' @param design An alias for `area`, retained for backward compatibility.\n#' @return An `AlignPatches` object.\n#' @seealso\n#' - [layout_design()]\n#' - [layout_title()]\n#' - [layout_theme()]\n#' @examples\n#' # directly copied from patchwork\n#' p1 <- ggplot(mtcars) +\n#' geom_point(aes(mpg, disp))\n#' p2 <- ggplot(mtcars) +\n#' geom_boxplot(aes(gear, disp, group = gear))\n#' p3 <- ggplot(mtcars) +\n#' geom_bar(aes(gear)) +\n#' facet_wrap(~cyl)\n#' p4 <- ggplot(mtcars) +\n#' geom_bar(aes(carb))\n#' p5 <- ggplot(mtcars) +\n#' geom_violin(aes(cyl, mpg, group = cyl))\n#'\n#' # Either add the plots as single arguments\n#' align_plots(p1, p2, p3, p4, p5)\n#'\n#' # Or use bang-bang-bang to add a list\n#' align_plots(!!!list(p1, p2, p3), p4, p5)\n#'\n#' # Match plots to areas by name\n#' area <- \"#BB\n#' AA#\"\n#' align_plots(B = p1, A = p2, area = area)\n#'\n#' # Compare to not using named plot arguments\n#' align_plots(p1, p2, area = area)\n#' @export\nalign_plots <- function(..., ncol = NULL, nrow = NULL, byrow = TRUE,\n widths = NA, heights = NA, area = NULL,\n guides = waiver(), theme = NULL, design = NULL) {\n plots <- rlang::dots_list(..., .ignore_empty = \"all\", .named = NULL)\n nms <- names(plots)\n area <- area %||% design\n if (!is.null(nms) && is.character(area)) {\n area_names <- unique(trimws(.subset2(strsplit(area, \"\"), 1L)))\n area_names <- sort(vec_set_difference(area_names, c(\"\", \"#\")))\n if (all(nms %in% area_names)) {\n plot_list <- vector(\"list\", length(area_names))\n names(plot_list) <- area_names\n plot_list[nms] <- plots\n plots <- plot_list\n }\n }\n\n for (plot in plots) {\n if (!has_method(plot, \"alignpatch\", default = FALSE)) {\n cli_abort(\"Cannot align {.obj_type_friendly {plot}}\")\n }\n }\n\n # setup layout parameters\n layout <- layout_design(\n ncol = ncol, nrow = nrow, byrow = byrow,\n widths = widths, heights = heights, area = area,\n guides = guides\n )\n AlignPatches(plots = plots, layout = layout, theme = theme)\n}\n\n#' @importFrom ggplot2 is_theme\n#' @importFrom S7 new_object S7_object prop prop<-\nAlignPatches <- S7::new_class(\"AlignPatches\",\n properties = list(\n plots = S7::new_property(\n S7::class_list,\n setter = function(self, value) {\n if (!is.null(prop(self, \"plots\"))) {\n cli_abort(\"'@plots' is read-only\")\n }\n prop(self, \"plots\", check = FALSE) <- value\n self\n }\n ),\n layout = S7::new_property(\n S7::class_list,\n setter = function(self, value) {\n if (!inherits(value, \"layout_design\")) {\n cli_abort(\"'@layout' must be a {.fn layout_design} object\")\n }\n old <- prop(self, \"layout\") %||% list(\n ncol = NULL, nrow = NULL, byrow = TRUE,\n widths = NA, heights = NA, area = NULL,\n guides = waiver()\n )\n guides <- .subset2(value, \"guides\")\n value$guides <- NULL # guides need special consideration\n old <- update_non_waive(old, value)\n if (is.null(guides) || is.waive(guides)) {\n old[\"guides\"] <- list(guides)\n } else if (!identical(guides, NA)) {\n old[\"guides\"] <- list(setup_guides(guides))\n }\n prop(self, \"layout\", check = FALSE) <- old\n self\n }\n ),\n titles = S7::new_property(\n S7::class_list,\n setter = function(self, value) {\n if (!inherits(value, \"layout_title\")) {\n cli_abort(\"'@titles' must be a {.fn layout_title} object'\")\n }\n old <- prop(self, \"titles\") %||%\n list(title = NULL, subtitle = NULL, caption = NULL)\n prop(self, \"titles\", check = FALSE) <- update_non_waive(\n old, value\n )\n self\n }\n ),\n theme = S7::new_property(\n S7::class_any,\n setter = function(self, value) {\n if (!is.null(value) && !is_theme(value)) {\n cli_abort(\"'@theme' must be a {.cls theme} object'\")\n }\n if (is.null(prop(self, \"theme\")) || is.null(value)) {\n prop(self, \"theme\", check = FALSE) <- value\n } else {\n prop(self, \"theme\", check = FALSE) <- prop(self, \"theme\") +\n value\n }\n self\n },\n default = NULL\n )\n ),\n constructor = function(plots = list(), layout = NULL,\n titles = NULL, theme = NULL) {\n out <- new_object(\n S7_object(),\n plots = plots,\n layout = layout %||% layout_design(),\n titles = titles %||% layout_title(),\n theme = theme\n )\n # for backward compatibility\n add_class(out, \"alignpatches\")\n }\n)\n\n#' @importFrom rlang caller_env\nlocal(\n S7::method(`+`, list(AlignPatches, S7::class_any)) <-\n function(e1, e2) {\n # Get the name of what was passed in as e2, and pass along so that\n # it can be displayed in error messages\n if (missing(e2)) {\n cli_abort(c(\n \"Cannot use {.code +} with a single argument.\",\n \"i\" = \"Did you accidentally put {.code +} on a new line?\"\n ))\n }\n e2name <- deparse(substitute(e2, env = caller_env(2)))\n alignpatches_add(e2, e1, e2name)\n }\n)\n\n#' @importFrom S7 S7_dispatch\nalignpatches_add <- S7::new_generic(\n \"alignpatches_add\", \"object\",\n function(object, patches, objectname) S7_dispatch()\n)\n\nS7::method(alignpatches_add, S7::class_any) <-\n function(object, patches, objectname) {\n if (is.null(object)) return(patches) # styler: off\n cli_abort(c(\n \"Cannot add {objectname}\",\n \"x\" = \"Only other layout elements or compatible objects can be added.\"\n ))\n }\n\n#############################################################\n#' Define the grid to compose plots in\n#'\n#' To control how different plots are laid out, you need to add a layout design\n#' specification. If you are nesting grids, the layout is scoped to the current\n#' nesting level.\n#' @inheritParams align_plots\n#' @return A `layout_design` object.\n#' @examples\n#' p1 <- ggplot(mtcars) +\n#' geom_point(aes(mpg, disp))\n#' p2 <- ggplot(mtcars) +\n#' geom_boxplot(aes(gear, disp, group = gear))\n#' p3 <- ggplot(mtcars) +\n#' geom_bar(aes(gear)) +\n#' facet_wrap(~cyl)\n#' align_plots(p1, p2, p3) +\n#' layout_design(nrow = 1L)\n#' align_plots(p1, p2, p3) +\n#' layout_design(ncol = 1L)\n#' @importFrom ggplot2 waiver\n#' @export\nlayout_design <- function(ncol = waiver(), nrow = waiver(), byrow = waiver(),\n widths = waiver(), heights = waiver(),\n area = waiver(), guides = NA, design = waiver()) {\n if (!is.waive(ncol)) {\n assert_number_whole(ncol, min = 1, allow_na = TRUE, allow_null = TRUE)\n }\n if (!is.waive(nrow)) {\n assert_number_whole(nrow, min = 1, allow_na = TRUE, allow_null = TRUE)\n }\n if (!is.waive(byrow)) assert_bool(byrow)\n area <- area %|w|% design\n if (!is.waive(area)) area <- as_areas(area)\n if (!identical(guides, NA) && !is.waive(guides) && !is.null(guides)) {\n assert_guides(guides)\n }\n structure(\n list(\n ncol = ncol,\n nrow = nrow,\n byrow = byrow,\n widths = widths,\n heights = heights,\n area = area,\n guides = guides\n ),\n class = c(\"layout_design\", \"plot_layout\")\n )\n}\n\nS3_layout_design <- S7::new_S3_class(\"layout_design\")\n\nS7::method(alignpatches_add, S3_layout_design) <-\n function(object, patches, objectname) {\n patches@layout <- object\n patches\n }\n\nS7::method(alignpatches_add, S7::new_S3_class(\"plot_layout\")) <-\n function(object, patches, objectname) {\n object$area <- object$design # pathwork use `design`\n object <- .subset(object, names(layout_design()))\n if (is.waive(object$guides)) {\n object$guides <- NA\n } else if (identical(object$guides, \"auto\")) {\n object$guides <- waiver()\n } else if (identical(object$guides, \"collect\")) {\n object$guides <- \"tlbr\"\n } else if (identical(object$guides, \"keep\")) {\n object[\"guides\"] <- list(NULL)\n }\n alignpatches_add(add_class(object, \"layout_design\"), patches)\n }\n\n##############################################################\n#' Annotate the whole layout\n#'\n#' @inheritParams ggplot2::labs\n#' @return A `layout_title` object.\n#' @examples\n#' p1 <- ggplot(mtcars) +\n#' geom_point(aes(mpg, disp))\n#' p2 <- ggplot(mtcars) +\n#' geom_boxplot(aes(gear, disp, group = gear))\n#' p3 <- ggplot(mtcars) +\n#' geom_bar(aes(gear)) +\n#' facet_wrap(~cyl)\n#' align_plots(p1, p2, p3) +\n#' layout_title(title = \"I'm title\")\n#' @importFrom ggplot2 waiver\n#' @export\nlayout_title <- function(title = waiver(), subtitle = waiver(),\n caption = waiver()) {\n if (!is.waive(title)) assert_string(title, allow_null = TRUE)\n if (!is.waive(subtitle)) assert_string(subtitle, allow_null = TRUE)\n if (!is.waive(caption)) assert_string(caption, allow_null = TRUE)\n structure(\n list(title = title, subtitle = subtitle, caption = caption),\n class = c(\"layout_title\", \"plot_annotation\")\n )\n}\n\nS3_layout_title <- S7::new_S3_class(\"layout_title\")\n\nS7::method(alignpatches_add, S3_layout_title) <-\n function(object, patches, objectname) {\n patches@titles <- object\n patches\n }\n\n##############################################################\n#' Modify theme of the layout\n#'\n#' @inherit ggplot2::theme\n#' @param ... A [`theme()`][ggplot2::theme] object or additional element\n#' specifications not part of base ggplot2. In general, these should also be\n#' defined in the `element tree` argument. [`Splicing`][rlang::splice] a list\n#' is also supported.\n#'\n#' @details\n#' A [`theme()`][ggplot2::theme] object used to customize various elements of\n#' the layout, including `guides`, `title`, `subtitle`, `caption`, `margins`,\n#' `panel.border`, and `background`. By default, the theme will inherit from the\n#' parent `layout`.\n#'\n#' - `guides`, `panel.border`, and `background` will always be used even for the\n#' nested `alignpatches` object.\n#'\n#' - `title`, `subtitle`, `caption`, and `margins` will be added for the\n#' top-level `alignpatches` object only.\n#'\n#' @examples\n#' p1 <- ggplot(mtcars) +\n#' geom_point(aes(mpg, disp))\n#' p2 <- ggplot(mtcars) +\n#' geom_boxplot(aes(gear, disp, group = gear))\n#' p3 <- ggplot(mtcars) +\n#' geom_bar(aes(gear)) +\n#' facet_wrap(~cyl)\n#' align_plots(\n#' p1 + theme(plot.background = element_blank()),\n#' p2 + theme(plot.background = element_blank()),\n#' p3 + theme(plot.background = element_blank())\n#' ) +\n#' layout_theme(plot.background = element_rect(fill = \"red\"))\n#' @importFrom ggplot2 theme\n#' @export\nlayout_theme <- rlang::new_function(\n # We utilize editor completion by listing all `theme()` arguments here.\n # By placing `...` at the beginning, we can check if the first\n # following argument is a `theme()` object rather than individual theme\n # elements.\n c(\n rlang::exprs(... = ),\n .subset(\n rlang::fn_fmls(theme),\n vec_set_difference(names(rlang::fn_fmls(theme)), \"...\")\n )\n ),\n quote({\n elements <- ggfun(\"find_args\")(..., complete = NULL, validate = NULL)\n ans <- theme(!!!elements)\n th <- NULL\n for (i in seq_len(...length())) {\n if (inherits(t <- ...elt(i), \"theme\")) {\n th <- ggfun(\"add_theme\")(th, t)\n }\n }\n add_class(ggfun(\"add_theme\")(th, ans), \"layout_theme\")\n })\n)\n\nS3_layout_theme <- S7::new_S3_class(\"layout_theme\")\n\nS7::method(alignpatches_add, S3_layout_theme) <-\n function(object, patches, objectname) {\n patches@theme <- object\n patches\n }\n\nS7::method(alignpatches_add, S7::new_S3_class(\"plot_annotation\")) <-\n function(object, patches, objectname) {\n patches@titles <- .subset(object, names(layout_title()))\n patches@theme <- .subset2(object, \"theme\")\n patches\n }\n\nupdate_layout_theme <- function(old, new) {\n if (is.null(old) || is.null(new)) return(new) # styler: off\n old + new\n}\n\n#' Add layout annotation (internal use)\n#'\n#' This function is a placeholder for future extensions.\n#' If you're trying to apply a theme, use [layout_theme()] instead.\n#'\n#' @param ... Currently unused. May accept a theme in the future.\n#' @param theme A theme object. If not `waiver()`, an error will be raised.\n#'\n#' @return None. This function is used for input validation.\n#' @importFrom ggplot2 is_theme\n#' @export\n#' @keywords internal\nlayout_annotation <- function(..., theme = waiver()) {\n if (is_theme(...elt(1)) || !is.waive(theme)) {\n cli_abort(\"Please use {.fn layout_theme} instead; {.fn layout_annotation} is reserved for future extensions.\")\n }\n}\n"], ["/ggalign/R/import-standalone-tibble.R", "# Standalone file: do not edit by hand\n# Source: https://github.com/Yunuuuu/standalone/blob/HEAD/R/standalone-tibble.R\n# Generated by: usethis::use_standalone(\"Yunuuuu/standalone\", \"tibble\")\n# ----------------------------------------------------------------------\n#\n# ---\n# repo: Yunuuuu/standalone\n# file: standalone-tibble.R\n# last-updated: 2024-11-14\n# license: https://unlicense.org\n# imports: [vctrs (>= 0.5.0), rlang]\n# ---\n\n# when developing R package, instead of depending on `dplyr`, `tidyr`, `tibble`.\n# we prefer use the basic function from `vctrs`\n#\n# Note: these functions won't check arguments\n#\n# Since `vctrs` also depends on `rlang` and `cli`, it has no harm to use\n# function from `rlang` and `cli`.\n#\n# Please initialize the package docs and import vctrs\n# 1. run `usethis::use_package_doc()`\n# 2. in package docs, please add #' @import vctrs\n\n# ## Changelog\n# 2025-03-12\n# - Added `case_when()`\n#\n# 2024-11-14\n# - Added `column_to_rownames()`\n#\n# 2024-11-13\n# - fix wrong results in `coalesce()`: we should assign value in the missing\n# index\n#\n# 2024-11-12\n# - Added `rename`\n# - coalesce() now will return value immediately when no missing value exists.\n#\n# 2024-11-11:\n# - Added `inner_join`\n# - Added `left_join`\n# - Added `right_join`\n# - Added `cross_join`\n# - Added `replace_na`\n# - Added `coalesce`\n# - Added `deframe`\n# - Added `enframe`\n# - Added `remove_rownames`\n# - Added `rownames_to_column`\n#\n# 2024-11-10:\n# - Added `full_join`\n# - Added `if_else`\n#\n# nocov start\n\n#' @importFrom rlang set_names\nfull_join <- function(\n x,\n y,\n by = vec_set_intersect(names(x), names(y)),\n by.x = by,\n by.y = by,\n suffix = c(\".x\", \".y\")\n) {\n loc <- vec_locate_matches(x[by.x], set_names(y[by.y], by.x), remaining = NA)\n x_slicer <- .subset2(loc, \"needles\")\n y_slicer <- .subset2(loc, \"haystack\")\n ans <- join_bind(\n vec_slice(x, x_slicer),\n # drop duplicated join column\n vec_slice(y[vec_set_difference(names(y), by.y)], y_slicer),\n suffix = suffix\n )\n new_rows <- which(vec_detect_missing(x_slicer)) # should come from `y`\n if (length(new_rows)) {\n ans[new_rows, by.x] <- vec_slice(y[by.y], y_slicer[new_rows])\n }\n ans\n}\n\n#' @importFrom rlang set_names\ninner_join <- function(\n x,\n y,\n by = vec_set_intersect(names(x), names(y)),\n by.x = by,\n by.y = by,\n suffix = c(\".x\", \".y\")\n) {\n loc <- vec_locate_matches(\n x[by.x],\n set_names(y[by.y], by.x),\n no_match = \"drop\"\n )\n x_slicer <- .subset2(loc, \"needles\")\n y_slicer <- .subset2(loc, \"haystack\")\n join_bind(\n vec_slice(x, x_slicer),\n # drop duplicated join column\n vec_slice(y[vec_set_difference(names(y), by.y)], y_slicer),\n suffix = suffix\n )\n}\n\n#' @importFrom rlang set_names\nleft_join <- function(\n x,\n y,\n by = vec_set_intersect(names(x), names(y)),\n by.x = by,\n by.y = by,\n suffix = c(\".x\", \".y\")\n) {\n loc <- vec_locate_matches(x[by.x], set_names(y[by.y], by.x))\n x_slicer <- .subset2(loc, \"needles\")\n y_slicer <- .subset2(loc, \"haystack\") # can have NA value\n join_bind(\n vec_slice(x, x_slicer),\n # drop duplicated join column\n vec_slice(y[vec_set_difference(names(y), by.y)], y_slicer),\n suffix = suffix\n )\n}\n\n#' @importFrom rlang set_names\nright_join <- function(\n x,\n y,\n by = vec_set_intersect(names(x), names(y)),\n by.x = by,\n by.y = by,\n suffix = c(\".x\", \".y\")\n) {\n loc <- vec_locate_matches(\n x[by.x],\n set_names(y[by.y], by.x),\n no_match = \"drop\",\n remaining = NA\n )\n x_slicer <- .subset2(loc, \"needles\") # can have NA value\n y_slicer <- .subset2(loc, \"haystack\")\n join_bind(\n # drop duplicated join column\n vec_slice(x[vec_set_difference(names(x), by.x)], x_slicer),\n vec_slice(y, y_slicer),\n suffix = suffix\n )\n}\n\ncross_join <- function(x, y, suffix = c(\".x\", \".y\")) {\n x_size <- vec_size(x)\n y_size <- vec_size(y)\n x_out <- vec_rep_each(x, times = y_size)\n y_out <- vec_rep(y, times = x_size)\n join_bind(x_out, y_out, suffix)\n}\n\njoin_bind <- function(x, y, suffix) {\n x_names <- names(x)\n y_names <- names(y)\n common <- vec_set_intersect(x_names, y_names)\n if (length(common)) {\n # add suffix to duplicated names\n index <- vec_match(common, x_names)\n names(x)[index] <- paste0(x_names[index], .subset(suffix, 1L))\n index <- vec_match(common, y_names)\n names(y)[index] <- paste0(y_names[index], .subset(suffix, 2L))\n }\n vec_cbind(x, y, .name_repair = \"check_unique\")\n}\n\n#' Rename elements in a list, data.frame or vector\n#'\n#' This is akin to `dplyr::rename` and `plyr::rename`. It renames elements given\n#' as names in the `replace` vector to the values in the `replace` vector\n#' without touching elements not referenced.\n#'\n#' @param x A data.frame or a named vector or list\n#' @param replace A named character vector. The names identifies the elements in\n#' `x` that should be renamed and the values gives the new names.\n#'\n#' @return `x`, with new names according to `replace`\n#' @noRd\nrename <- function(x, replace) {\n nms <- names(x)\n names(x) <- vec_assign(nms, match(names(replace), nms), replace)\n x\n}\n\nif_else <- function(condition, true, false, na = NULL) {\n # output size from `condition`\n size <- vec_size(condition)\n\n # output type from `true`/`false`/`na`\n ptype <- vec_ptype_common(true = true, false = false, na = na)\n\n args <- vec_recycle_common(\n true = true,\n false = false,\n na = na,\n .size = size\n )\n args <- vec_cast_common(!!!args, .to = ptype)\n\n out <- vec_init(ptype, size)\n\n loc_true <- condition\n loc_false <- !condition\n\n out <- vec_assign(out, loc_true, vec_slice(args$true, loc_true))\n out <- vec_assign(out, loc_false, vec_slice(args$false, loc_false))\n\n if (!is.null(na)) {\n loc_na <- vec_detect_missing(condition)\n out <- vec_assign(out, loc_na, vec_slice(args$na, loc_na))\n }\n\n out\n}\n\ncase_when <- function(.default, ..., .ptype = NULL) {\n if (is.null(.ptype)) {\n .ptype <- vec_ptype(.default)\n } else {\n .default <- vec_cast(.default, .ptype)\n }\n env <- rlang::caller_env()\n dots <- rlang::list2(...)\n unused <- vec_rep(TRUE, times = vec_size(.default))\n for (i in seq_along(dots)) {\n if (!any(unused)) {\n break\n }\n dot <- .subset2(dots, i)\n loc <- unused & rlang::eval_tidy(rlang::f_lhs(dot), env = env)\n value <- rlang::eval_tidy(rlang::f_rhs(dot), env = env)\n value <- vec_cast(value, .ptype, x_arg = sprintf(\"`...` (%d)\", i))\n if (length(value) > 1L) value <- vec_slice(value, loc)\n .default <- vec_assign(\n .default,\n loc,\n value,\n value_arg = sprintf(\"`...` (%d)\", i)\n )\n unused[loc] <- FALSE\n }\n .default\n}\n\n\n#' Replace NAs with specified values\n#' @param value A single value.\n#' @noRd\nreplace_na <- function(x, value) {\n value <- vec_cast(x = value, to = x, x_arg = \"value\", to_arg = \"x\")\n vec_assign(x, vec_detect_missing(x), value)\n}\n\n#' Find the first non-missing element\n#' @param ... A list of atomic vector (You shouldn't input `NULL`).\n#' @noRd\ncoalesce <- function(...) {\n dots <- vec_recycle_common(...)\n out <- .subset2(dots, 1L)\n for (i in 2:length(dots)) {\n if (vec_any_missing(out)) {\n missing <- vec_detect_missing(out)\n out <- vec_assign(\n out,\n missing,\n vec_slice(.subset2(dots, i), missing)\n )\n } else {\n return(out)\n }\n }\n out\n}\n\n#' Convert values to `NA`\n#' @noRd\nna_if <- function(x, y) {\n y <- vec_cast(x = y, to = x, x_arg = \"y\", to_arg = \"x\")\n y <- vec_recycle(y, size = vec_size(x), x_arg = \"y\")\n na <- vec_init(x)\n vec_assign(x, vec_equal(x, y, na_equal = TRUE), na)\n}\n\ndeframe <- function(x) {\n if (ncol(x) == 1L) {\n return(x[[1]])\n }\n vec_set_names(x[[1L]], x[[2]])\n}\n\nenframe <- function(x, name = \"name\", value = \"value\") {\n if (!is.null(names(x))) {\n data <- list(names(x), unname(x))\n } else {\n data <- list(seq_along(x), unname(x))\n }\n new_data_frame(vec_set_names(data, c(name, value)))\n}\n\nremove_rownames <- function(.data) {\n rownames(.data) <- NULL\n .data\n}\n\nrownames_to_column <- function(.data, var = \"rowname\") {\n if (!is.null(var_col <- rownames(.data))) {\n nms <- names(.data)\n .data[[var]] <- var_col\n .data <- .data[c(var, nms)]\n }\n .data\n}\n\ncolumn_to_rownames <- function(.data, var = 1L) {\n rownames(.data) <- .subset2(.data, var)\n .data[[var]] <- NULL\n .data\n}\n\n# nocov end\n"], ["/ggalign/R/layout-.R", "# Will ensure serialisation includes a link to the ggalign namespace\n# Copied from patchwork\nnamespace_link <- function() NULL\n\n# https://stackoverflow.com/questions/65817557/s3-methods-extending-ggplot2-gg-function\n# Here we use S4 object to override the double dispatch of `+.gg` method\n# TO-DO: use S7\n#' A `Layout` object\n#'\n#' A `Layout` object defines how to place the plots.\n#'\n#' @keywords internal\n# add suffix \"Proto\" to avoid conflict with ggplot2\nmethods::setClass(\"LayoutProto\",\n list(\n active = \"ANY\", # current active plot\n schemes = \"list\", # used to provide global parameters for all plots\n # control the layout, `theme` will also be used by `ggsave`\n titles = \"list\",\n annotation = \"list\", # To-Do add `pacth_titles` for layout\n theme = \"ANY\",\n `_namespace` = \"ANY\"\n ),\n prototype = list(\n active = NULL, titles = list(),\n annotation = list(), theme = NULL,\n `_namespace` = namespace_link\n )\n)\n\n#' @export\nprint.LayoutProto <- print.alignpatches\n\n#' @importFrom grid grid.draw\n#' @exportS3Method\ngrid.draw.LayoutProto <- grid.draw.alignpatches\n\n#' @export\nalignpatch.LayoutProto <- function(x) alignpatch(ggalign_build(x))\n\n#' Print Layout object\n#'\n#' @param object A `r rd_layout()`.\n#' @return The input invisiblely.\n#' @importFrom methods show\n#' @export\n#' @keywords internal\nmethods::setMethod(\"show\", \"LayoutProto\", function(object) {\n print(object)\n})\n\n#' Subset a `Layout` object\n#'\n#' Used by [`ggplot_build`][ggplot2::ggplot_build] and\n#' [`ggsave`][ggplot2::ggsave]\n#'\n#' @param x A `Layout` object\n#' @param name A string of slot name in `Layout` object.\n#' @return The slot value.\n#' @importFrom methods slot\n#' @export\n#' @keywords internal\nmethods::setMethod(\"$\", \"LayoutProto\", function(x, name) {\n slot(x, name)\n})\n\n###########################################################\ndefault_layout <- function(layout) { # setup default value for the layout\n layout@theme <- complete_theme(default_theme() + layout@theme)\n\n # we by default, collect all guides\n layout@schemes$scheme_align[\"guides\"] <- list(\n .subset2(.subset2(layout@schemes, \"scheme_align\"), \"guides\") %|w|% \"tlbr\"\n )\n\n # we by default, use `default_theme()`\n layout@schemes$scheme_theme <- update_scheme(\n .subset2(layout@schemes, \"scheme_theme\"),\n new_scheme_theme(complete_theme(default_theme()))\n )\n layout\n}\n\nis_linear <- function(layout) UseMethod(\"is_linear\")\n\n#' @export\nis_linear.StackLayout <- function(layout) TRUE\n\n#' @export\nis_linear.CircleLayout <- function(layout) FALSE\n\n###########################################################\ninherit_parent_layout_schemes <- function(layout, schemes) {\n if (is.null(schemes)) {\n return(layout@schemes)\n }\n inherit_schemes(layout@schemes, schemes)\n}\n\ninherit_parent_layout_theme <- function(layout, theme, spacing = NULL) {\n if (is.null(theme)) return(layout@theme) # styler: off\n # parent theme, set the global panel spacing,\n # so that every panel aligns well\n if (is.null(layout@theme)) return(theme) # styler: off\n ans <- theme + layout@theme\n if (is.null(spacing)) return(ans) # styler: off\n switch(spacing,\n x = ans + theme(\n panel.spacing.x = calc_element(\"panel.spacing.x\", theme)\n ),\n y = ans + theme(\n panel.spacing.y = calc_element(\"panel.spacing.y\", theme)\n )\n )\n}\n\n############################################################\n#' Get the statistics from the layout\n#'\n#' @param x A `r rd_layout()`.\n#' @inheritParams rlang::args_dots_used\n#' @return The statistics\n#' @export\nggalign_stat <- function(x, ...) {\n UseMethod(\"ggalign_stat\")\n}\n\n#' @param position A string of `r oxford_or(.TLBR)`.\n#' @export\n#' @rdname ggalign_stat\nggalign_stat.QuadLayout <- function(x, position, ...) {\n ggalign_stat(x = slot(x, position), ...)\n}\n\n#' @param what A single number or string of the plot elements in the stack\n#' layout.\n#' @export\n#' @rdname ggalign_stat\nggalign_stat.StackLayout <- function(x, what, ...) {\n plot_list <- x@plot_list\n index <- vec_as_location2(\n what,\n n = length(plot_list),\n names = names(plot_list),\n missing = \"error\"\n )\n ggalign_stat(x = .subset2(plot_list, index), ...)\n}\n\n#' @export\nggalign_stat.CraftBox <- function(x, ...) {\n ggalign_stat(x@craftsman, ...)\n}\n\n#' @export\nggalign_stat.CraftAlign <- function(x, ...) {\n rlang::check_dots_empty()\n .subset2(x, \"statistics\")\n}\n\n#' @export\nggalign_stat.default <- function(x, ...) {\n cli_abort(sprintf(\"no statistics found for %s\", object_name(x)))\n}\n\n#############################################################\n#' Reports whether `x` is layout object\n#'\n#' @param x An object to test.\n#' @return A single boolean value.\n#' @examples\n#' is_layout(ggheatmap(1:10))\n#'\n#' @importFrom methods is\n#' @export\nis_layout <- function(x) is(x, \"LayoutProto\")\n\n#' @examples\n#' # for quad_layout()\n#' is_quad_layout(quad_alignb(1:10))\n#' is_quad_layout(quad_alignh(1:10))\n#' is_quad_layout(quad_alignv(1:10))\n#' is_quad_layout(quad_free(mtcars))\n#'\n#' @export\n#' @rdname is_layout\nis_quad_layout <- function(x) is(x, \"QuadLayout\")\n\n#' @examples\n#' # for stack_layout()\n#' is_stack_layout(stack_discrete(\"h\", 1:10))\n#' is_stack_layout(stack_continuous(\"h\", 1:10))\n#'\n#' @export\n#' @rdname is_layout\nis_stack_layout <- function(x) is(x, \"StackLayout\")\n\n#' @export\n#' @rdname is_layout\nis_stack_cross <- function(x) is(x, \"StackCross\")\n\n#' @export\n#' @rdname is_layout\nis_circle_layout <- function(x) is(x, \"CircleLayout\")\n\n#' @examples\n#' # for heatmap_layout()\n#' is_heatmap_layout(ggheatmap(1:10))\n#' @export\n#' @rdname is_layout\nis_heatmap_layout <- function(x) is(x, \"HeatmapLayout\")\n\n#' @examples\n#' is_ggheatmap(ggheatmap(1:10))\n#' @export\n#' @rdname is_layout\nis_ggheatmap <- is_heatmap_layout\n\nis_cross_layout <- function(x) is_stack_cross(x)\n"], ["/ggalign/R/alignpatch-alignpatches.R", "#' @importFrom ggplot2 ggproto\n#' @export\nalignpatch.alignpatches <- function(x) {\n ggproto(NULL, PatchAlignpatches, plot = x)\n}\n\n#' @noRd\nPatchAlignpatches <- ggproto(\"PatchAlignpatches\", Patch,\n set_guides = function(self, guides) guides,\n #' @importFrom gtable gtable gtable_add_grob\n #' @importFrom grid unit\n #' @importFrom ggplot2 wrap_dims calc_element zeroGrob theme_get\n #' @importFrom S7 prop\n patch_gtable = function(self, theme = theme_get(), guides = NULL,\n top_level = FALSE, plot = self$plot) {\n patches <- lapply(prop(plot, \"plots\"), alignpatch)\n layout <- prop(plot, \"layout\")\n\n # get the design areas and dims ------------------\n panel_widths <- .subset2(layout, \"widths\")\n panel_heights <- .subset2(layout, \"heights\")\n if (is.null(area <- .subset2(layout, \"area\"))) {\n if (is.null(layout$ncol) && length(panel_widths) > 1L) {\n layout$ncol <- length(panel_widths)\n }\n if (is.null(layout$nrow) && length(panel_heights) > 1L) {\n layout$nrow <- length(panel_heights)\n }\n dims <- wrap_dims(\n length(patches),\n .subset2(layout, \"nrow\"),\n .subset2(layout, \"ncol\")\n )\n area <- create_area(\n dims[2L], dims[1L],\n .subset2(layout, \"byrow\")\n )\n } else {\n dims <- c(max(field(area, \"b\")), max(field(area, \"r\")))\n }\n\n # filter `plots` based on the design areas --------------------\n if (vec_size(area) < vec_size(patches)) {\n cli_warn(\n \"Too few patch areas to hold all plots. Dropping plots\"\n )\n plots <- vec_slice(patches, vec_seq_along(area))\n } else {\n area <- vec_slice(area, seq_along(patches))\n }\n\n # remove NULL patch -----------------------------------\n keep <- !vapply(patches, is.null, logical(1L), USE.NAMES = FALSE)\n patches <- vec_slice(patches, keep)\n\n # if no plots, we return empty gtable -----------------\n if (is_empty(patches)) return(make_patch_table()) # styler: off\n self$patches <- patches\n\n # add borders to patch --------------------------------\n area <- vec_slice(area, keep)\n for (i in seq_along(patches)) {\n patches[[i]]$borders <- c(\n if (field(area, \"t\")[i] == 1L) \"top\" else NULL,\n if (field(area, \"l\")[i] == 1L) \"left\" else NULL,\n if (field(area, \"b\")[i] == .subset(dims, 1L)) {\n \"bottom\"\n } else {\n NULL\n },\n if (field(area, \"r\")[i] == .subset(dims, 2L)) {\n \"right\"\n } else {\n NULL\n }\n )\n }\n\n # we inherit parameters from the parent --------------------\n # by default, we won't collect any guide legends\n parent_guides <- guides\n guides <- .subset2(layout, \"guides\") %|w|% parent_guides\n\n # by default, we use ggplot2 default theme\n if (!is.null(prop(plot, \"theme\"))) theme <- theme + prop(plot, \"theme\")\n self$theme <- theme\n\n #######################################################\n # 1. patch_gtable: create the gtable for the patch, will set internal\n # `gt`\n # 2. `collect_guides`, can change the internal `gt`\n # 3. set_sizes:\n # - (To-Do) align_panel_spaces: can change the internal `gt`\n # - align_panel_sizes, can change the internal `gt`\n # - get_sizes, the widths and heights for the internal `gt`\n # 4. set_grobs: will call `align_border` and `split_gt`, return the\n # final gtable\n # setup gtable list ----------------------------------\n # Let each patch to determine whether to collect guides\n collected <- lapply(patches, function(patch) patch$set_guides(guides))\n collected_guides <- vector(\"list\", length(patches))\n\n # Always ensure that plots placed in a border collect their guides, if\n # any guides are to be collected in that border. This prevents overlap,\n # unless the guides will be collected by the parent layout.\n border_with_guides <- unique(unlist(collected, FALSE, FALSE))\n border_with_guides <- setdiff(border_with_guides, parent_guides)\n for (i in seq_along(patches)) {\n patch <- .subset2(patches, i)\n g <- union(\n .subset2(collected, i),\n intersect(border_with_guides, patch$borders)\n )\n patch$gt <- patch$patch_gtable(theme = theme, guides = g)\n collected_guides[i] <- list(patch$collect_guides(g))\n }\n\n # collect guides ---------------------------------------\n self$collected_guides <- collect_guides_list(collected_guides)\n\n # prepare the output ----------------------------------\n gt <- gtable(\n unit(rep(0L, TABLE_COLS * dims[2L]), \"null\"),\n unit(rep(0L, TABLE_ROWS * dims[1L]), \"null\")\n )\n\n # setup sizes for each row/column -----------------------\n gt <- self$set_sizes(\n area, dims, panel_widths, panel_heights,\n patches = patches, gt = gt\n )\n\n # add the panel position --------------------------------\n panel_pos <- list(\n t = TOP_BORDER + 1L,\n l = LEFT_BORDER + 1L,\n b = TABLE_ROWS * dims[1L] - BOTTOM_BORDER,\n r = TABLE_COLS * dims[2L] - RIGHT_BORDER\n )\n\n # add guides into the final gtable ----------------------\n if (top_level) {\n gt <- self$attach_guide_list(\n guide_list = self$collected_guides,\n theme = theme,\n panel_pos = panel_pos,\n gt = gt\n )\n }\n\n # setup grobs -------------------------------------------\n # For z in the gtable layout\n # 0L: layout background\n # 1L: background of the plot\n # 2L: plot table\n # 3L: foreground of the panel area\n # 4L: legends\n gt <- self$set_grobs(area, patches = patches, gt = gt)\n\n # add panel area ---------------------------------------\n gt <- gtable_add_grob(\n gt, list(zeroGrob()),\n t = .subset2(panel_pos, \"t\"),\n l = .subset2(panel_pos, \"l\"),\n b = .subset2(panel_pos, \"b\"),\n r = .subset2(panel_pos, \"r\"),\n z = 0L,\n name = \"panel-area\"\n )\n gt <- gtable_add_grob(\n gt,\n # foreground\n list(element_render(theme, \"panel.border\", fill = NA)),\n t = .subset2(panel_pos, \"t\"),\n l = .subset2(panel_pos, \"l\"),\n b = .subset2(panel_pos, \"b\"),\n r = .subset2(panel_pos, \"r\"),\n z = 3L,\n name = \"panel-foreground\"\n )\n\n # add background -----------------------------------\n if (!top_level && inherits(theme$plot.background, \"element\")) {\n gt <- gtable_add_grob(gt,\n element_render(theme, \"plot.background\"),\n t = 1L, l = 1L, b = -1L, r = -1L,\n name = \"background\", z = 0L\n )\n }\n\n # arrange the grobs\n idx <- order(.subset2(.subset2(gt, \"layout\"), \"z\"))\n gt$layout <- vec_slice(.subset2(gt, \"layout\"), idx)\n gt$grobs <- .subset(.subset2(gt, \"grobs\"), idx)\n gt\n },\n align_border = function(self, t = NULL, l = NULL, b = NULL, r = NULL,\n gt = self$gt, patches = self$patches) {\n if (is.null(t) && is.null(l) && is.null(b) && is.null(r)) {\n return(gt)\n }\n gt <- Patch$align_border(t = t, l = l, b = b, r = r, gt = gt)\n self$recurse_lapply(function(patch, grob, t, l, b, r) {\n # For each plot grob, we reuse it's method to set the border\n # sizes we only set the border sizes for plot in the border\n patch$align_border(t = t, l = l, b = b, r = r, gt = grob)\n }, t = t, l = l, b = b, r = r, gt = gt, patches = patches)\n },\n collect_guides = function(self, guides, gt = self$gt) {\n collected_guides <- self$collected_guides\n # for guides not collected by the top-level alignpatches, we attach the\n # guides\n self$gt <- self$attach_guide_list(\n collected_guides[\n vec_set_difference(names(collected_guides), guides)\n ],\n gt = gt\n )\n # return guides to be collected\n .subset(collected_guides, guides)\n },\n #' @importFrom grid is.unit unit\n set_sizes = function(self, area, dims,\n panel_widths, panel_heights,\n patches, gt = self$gt) {\n panel_widths <- rep(panel_widths, length.out = dims[2L])\n panel_heights <- rep(panel_heights, length.out = dims[1L])\n if (!is.unit(panel_widths)) panel_widths <- unit(panel_widths, \"null\")\n if (!is.unit(panel_heights)) {\n panel_heights <- unit(panel_heights, \"null\")\n }\n\n # For gtable with fixed aspect ratio -------------\n # if it cannot be fixed and aligned, the strip, axis and labs will be\n # attached into the panel\n # the plot to be fixed must in only one square of the area\n need_fix <- field(area, \"l\") == field(area, \"r\") &\n field(area, \"t\") == field(area, \"b\") &\n vapply(\n patches,\n function(patch) patch$respect(),\n logical(1L),\n USE.NAMES = FALSE\n )\n\n # here we respect the aspect ratio when necessary -----\n # if the width or height is NA, we will guess the panel widths or\n # heights based on the fixed aspect ratio\n guess_widths <- which(is.na(as.numeric(panel_widths)))\n guess_heights <- which(is.na(as.numeric(panel_heights)))\n cols <- field(area, \"l\")\n rows <- field(area, \"t\")\n patch_index <- order(\n # we first set the widths for the fixed plot with heights set by\n # user\n cols %in% guess_widths & !rows %in% guess_heights,\n # we then set the heights for the fixed plot with widths set by user\n !cols %in% guess_widths & rows %in% guess_heights,\n # we set widths and heights for remaning plots\n # based on the number of plots in each row/column in the descending\n # order\n c(table(rows[need_fix]))[as.character(rows)],\n c(table(cols[need_fix]))[as.character(cols)],\n decreasing = TRUE\n )\n respect_dims <- vector(\"list\", length(patches))\n\n # For plot cannot be fixed, we always attach strips, axes and labels\n # into the panel area\n for (i in patch_index) {\n row <- .subset(rows, i)\n col <- .subset(cols, i)\n # we always build a standard gtable layout from the gtable\n panel_sizes <- .subset2(patches, i)$align_panel_sizes(\n panel_width = panel_widths[col],\n panel_height = panel_heights[row]\n )\n panel_widths[col] <- .subset2(panel_sizes, \"width\")\n panel_heights[row] <- .subset2(panel_sizes, \"height\")\n if (.subset2(panel_sizes, \"respect\")) {\n respect_dims[[i]] <- matrix(c(\n (row - 1L) * TABLE_ROWS + TOP_BORDER + 1L,\n (col - 1L) * TABLE_COLS + LEFT_BORDER + 1L\n ), nrow = 1L)\n }\n }\n if (!is.null(respect_dims <- do.call(base::rbind, respect_dims))) {\n respect <- matrix(\n 0L, TABLE_ROWS * dims[1L],\n TABLE_COLS * dims[2L]\n )\n respect[respect_dims] <- 1L\n gt$respect <- respect\n }\n\n # we set the widths/heights with no fixed plots to be 1 null\n if (any(guess_widths <- is.na(as.numeric(panel_widths)))) {\n panel_widths[guess_widths] <- unit(1L, \"null\")\n }\n if (any(guess_heights <- is.na(as.numeric(panel_heights)))) {\n panel_heights[guess_heights] <- unit(1L, \"null\")\n }\n\n # setup sizes for non-panel rows/columns --------------\n sizes <- table_sizes(\n lapply(patches, function(patch) patch$get_sizes()),\n area, dims[2L], dims[1L]\n )\n widths <- .subset2(sizes, \"widths\")\n heights <- .subset2(sizes, \"heights\")\n\n # restore the panel sizes ----------------------------\n width_ind <- seq(LEFT_BORDER + 1L,\n by = TABLE_COLS, length.out = dims[2L]\n )\n height_ind <- seq(TOP_BORDER + 1L,\n by = TABLE_ROWS, length.out = dims[1L]\n )\n widths[width_ind] <- panel_widths\n heights[height_ind] <- panel_heights\n\n # setup the widths and heights -----------------------\n gt$widths <- widths\n gt$heights <- heights\n gt\n },\n\n #' @importFrom gtable gtable_add_grob\n set_grobs = function(self, area, patches, gt = self$gt) {\n widths <- .subset2(gt, \"widths\")\n heights <- .subset2(gt, \"heights\")\n for (i in seq_along(patches)) {\n loc <- vec_slice(area, i)\n # We must align the borders for the gtable grob with the\n # final plot area sizes\n l <- (field(loc, \"l\") - 1L) * TABLE_COLS + 1L\n l_widths <- widths[seq(l, l + LEFT_BORDER - 1L)]\n r <- field(loc, \"r\") * TABLE_COLS\n r_widths <- widths[seq(r - RIGHT_BORDER + 1L, r)]\n t <- (field(loc, \"t\") - 1L) * TABLE_ROWS + 1L\n t_heights <- heights[seq(t, t + TOP_BORDER - 1L)]\n b <- field(loc, \"b\") * TABLE_ROWS\n b_heights <- heights[seq(b - BOTTOM_BORDER + 1L, b)]\n patch <- .subset2(patches, i)\n\n grobs <- patch$split_gt(patch$align_border(\n t = t_heights, l = l_widths,\n b = b_heights, r = r_widths\n ))\n\n # then we add the plot ---------------------------------\n gt <- patch$add_plot(\n gt, .subset2(grobs, \"plot\"), t, l, b, r,\n name = paste(\"plot\", i, sep = \"-\")\n )\n\n # add background grob ----------------------------------\n if (!is.null(bg <- .subset2(grobs, \"bg\"))) {\n # we always add background in the beginning --------\n gt <- patch$add_background(\n gt, bg, t, l, b, r,\n name = paste(\"plot\", i, \"background\", sep = \"-\")\n )\n }\n\n # remove the grob from the patch, we wont' use it anymore\n patch$gt <- NULL\n }\n gt\n },\n attach_guide_list = function(self, guide_list, theme = self$theme,\n panel_pos = find_panel(gt),\n gt = self$gt) {\n if (length(guide_list)) {\n # https://github.com/tidyverse/ggplot2/blob/57ba97fa04dadc6fd73db1904e39a09d57a4fcbe/R/guides-.R#L512\n theme$legend.spacing <- theme$legend.spacing %||% unit(0.5, \"lines\")\n theme$legend.spacing.y <- calc_element(\"legend.spacing.y\", theme)\n theme$legend.spacing.x <- calc_element(\"legend.spacing.x\", theme)\n theme$legend.box.spacing <- calc_element(\n \"legend.box.spacing\", theme\n ) %||% unit(0.2, \"cm\")\n for (guide_pos in names(guide_list)) {\n gt <- self$attach_guides(\n guide_pos = guide_pos,\n guides = .subset2(guide_list, guide_pos),\n theme = theme, panel_pos = panel_pos,\n clip = \"off\", z = 4L, gt = gt\n )\n }\n }\n gt\n },\n #' @importFrom gtable gtable_width gtable_height\n #' @importFrom grid unit.c grobWidth grobHeight\n #' @importFrom ggplot2 find_panel zeroGrob\n attach_guides = function(self, guide_pos, guides, theme,\n panel_pos = find_panel(gt), ...,\n gt = self$gt) {\n guide_box <- assemble_guides(guides, guide_pos, theme = theme)\n name <- sprintf(\"guide-box-collected-%s\", guide_pos)\n if (guide_pos == \"inside\") {\n gt <- gtable_add_grob(\n x = gt,\n grobs = guide_box,\n t = panel_pos$t,\n l = panel_pos$l,\n b = panel_pos$b,\n r = panel_pos$r,\n name = name,\n ...\n )\n return(gt)\n }\n spacing <- .subset2(theme, \"legend.box.spacing\")\n if (guide_pos == \"left\") {\n if (is.gtable(guide_box)) {\n legend_width <- gtable_width(guide_box)\n widths <- unit.c(spacing, legend_width)\n } else {\n legend_width <- grobWidth(guide_box)\n widths <- unit(c(0, 0), \"mm\")\n }\n gt <- gtable_add_grob(\n x = gt,\n grobs = guide_box,\n t = panel_pos$t,\n l = panel_pos$l - 6L,\n b = panel_pos$b,\n name = name,\n ...\n )\n gt$widths[.subset2(panel_pos, \"l\") - 5:6] <- widths\n } else if (guide_pos == \"right\") {\n if (is.gtable(guide_box)) {\n legend_width <- gtable_width(guide_box)\n widths <- unit.c(spacing, legend_width)\n } else {\n legend_width <- grobWidth(guide_box)\n widths <- unit(c(0, 0), \"mm\")\n }\n gt <- gtable_add_grob(\n x = gt,\n grobs = guide_box,\n t = panel_pos$t,\n l = panel_pos$r + 6L,\n b = panel_pos$b,\n name = name,\n ...\n )\n gt$widths[.subset2(panel_pos, \"r\") + 5:6] <- widths\n } else if (guide_pos == \"bottom\") {\n location <- .subset2(theme, \"legend.location\") %||% \"panel\"\n place <- switch(location,\n panel = panel_pos,\n list(l = 1L, r = ncol(gt))\n )\n if (is.gtable(guide_box)) {\n legend_height <- gtable_height(guide_box)\n heights <- unit.c(spacing, legend_height)\n } else {\n legend_height <- grobHeight(guide_box)\n heights <- unit(c(0, 0), \"mm\")\n }\n gt <- gtable_add_grob(\n x = gt,\n grobs = guide_box,\n t = panel_pos$b + 6L,\n l = place$l,\n r = place$r,\n name = name,\n ...\n )\n gt$heights[.subset2(panel_pos, \"b\") + 5:6] <- heights\n } else if (guide_pos == \"top\") {\n location <- .subset2(theme, \"legend.location\") %||% \"panel\"\n place <- switch(location,\n panel = panel_pos,\n list(l = 1L, r = ncol(gt))\n )\n if (is.gtable(guide_box)) {\n legend_height <- gtable_height(guide_box)\n heights <- unit.c(spacing, legend_height)\n } else {\n legend_height <- grobHeight(guide_box)\n heights <- unit(c(0, 0), \"mm\")\n }\n gt <- gtable_add_grob(\n x = gt,\n grobs = guide_box,\n t = panel_pos$t - 6L,\n l = place$l,\n r = place$r,\n name = name,\n ...\n )\n gt$heights[.subset2(panel_pos, \"t\") - 5:6] <- heights\n }\n gt\n },\n\n #' @importFrom rlang is_empty\n free_border = function(self, borders, gt = self$gt,\n patches = self$patches) {\n gt <- self$recurse_lapply(\n function(patch, grob, t, l, b, r) {\n borders <- intersect(borders, c(t, l, b, r))\n if (is_empty(borders)) return(grob) # styler: off\n patch$free_border(borders = borders, gt = grob)\n },\n t = \"top\", l = \"left\", b = \"bottom\", r = \"right\",\n gt = gt, patches = patches\n )\n # for the collected guides, we should also liberate them\n guide_index <- sprintf(\"guide-box-collected-%s\", borders) %in%\n .subset2(.subset2(gt, \"layout\"), \"name\")\n if (any(guide_index)) {\n gt <- PatchGgplot$free_border(\n borders = borders[guide_index], gt = gt\n )\n }\n gt\n },\n align_free_border = function(self, borders,\n t = NULL, l = NULL, b = NULL, r = NULL,\n gt = self$gt, patches = self$patches) {\n gt <- self$recurse_lapply(\n function(patch, grob, t, l, b, r) {\n patch$align_free_border(\n borders = borders,\n t = t, l = l, b = b, r = r, gt = grob\n )\n },\n t = t, l = l, b = b, r = r,\n gt = gt, patches = patches\n )\n PatchGgplot$align_free_border(\n borders = borders,\n t = t, l = l, b = b, r = r, gt = gt\n )\n },\n\n #' @importFrom rlang is_empty\n free_lab = function(self, labs, gt = self$gt, patches = self$patches) {\n self$recurse_lapply(\n function(patch, grob, t, l, b, r) {\n labs <- intersect(labs, c(t, l, b, r))\n if (is_empty(labs)) return(grob) # styler: off\n patch$free_lab(labs = labs, gt = grob)\n },\n t = \"top\", l = \"left\", b = \"bottom\", r = \"right\",\n gt = gt, patches = patches\n )\n },\n # we apply function in each plot gtable in `gt`.\n #' @importFrom rlang is_empty\n recurse_lapply = function(self, .fn, t, l, b, r,\n gt = self$gt, patches = self$patches) {\n # if no plot provided, we'll do nothing\n if (is_empty(patches)) return(gt) # styler: off\n patch_index <- seq_along(patches)\n grobs <- .subset2(gt, \"grobs\")\n layout_index <- match(\n paste0(\"plot-\", patch_index),\n .subset2(.subset2(gt, \"layout\"), \"name\")\n )\n # For each grob, we reuse the method from the patch\n gt$grobs[layout_index] <- .mapply(function(layout_idx, patch_idx) {\n patch <- .subset2(patches, patch_idx)\n borders <- .subset2(patch, \"borders\")\n .fn(\n patch = patch,\n grob = .subset2(grobs, layout_idx),\n t = if (any(borders == \"top\")) t else NULL,\n l = if (any(borders == \"left\")) l else NULL,\n b = if (any(borders == \"bottom\")) b else NULL,\n r = if (any(borders == \"right\")) r else NULL\n )\n }, list(layout_idx = layout_index, patch_idx = patch_index), NULL)\n gt\n }\n)\n\n#' @importFrom grid convertHeight convertWidth unit\ntable_sizes <- function(sizes, area, ncol, nrow) {\n # `null` unit of the panel area will be converted into 0\n # we'll set the panel width and height afterward\n widths <- lapply(sizes, function(size) {\n convertWidth(.subset2(size, \"widths\"), \"mm\", valueOnly = TRUE)\n })\n widths <- vapply(seq_len(ncol * TABLE_COLS), function(i) {\n area_col <- (i - 1L) %/% TABLE_COLS + 1L\n col_loc <- i %% TABLE_COLS\n if (col_loc == 0L) col_loc <- TABLE_COLS\n area_side <- if (col_loc <= LEFT_BORDER + 1L) \"l\" else \"r\"\n idx <- field(area, area_side) == area_col\n if (any(idx)) {\n max(\n vapply(.subset(widths, idx), .subset, numeric(1L), col_loc),\n 0L\n )\n } else {\n 0L\n }\n }, numeric(1L), USE.NAMES = FALSE)\n heights <- lapply(sizes, function(size) {\n convertHeight(.subset2(size, \"heights\"), \"mm\", valueOnly = TRUE)\n })\n heights <- vapply(seq_len(nrow * TABLE_ROWS), function(i) {\n area_row <- recycle_each(i, TABLE_ROWS)\n row_loc <- recycle_whole(i, TABLE_ROWS)\n area_side <- if (row_loc <= TOP_BORDER + 1L) \"t\" else \"b\"\n idx <- field(area, area_side) == area_row\n if (any(idx)) {\n max(\n vapply(\n .subset(heights, idx), .subset, numeric(1L),\n row_loc,\n USE.NAMES = FALSE\n ),\n 0L\n )\n } else {\n 0L\n }\n }, numeric(1L), USE.NAMES = FALSE)\n list(widths = unit(widths, \"mm\"), heights = unit(heights, \"mm\"))\n}\n"], ["/ggalign/R/layout-chain-stack-.R", "#' Arrange plots horizontally or vertically\n#'\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' If `limits` is provided, a continuous variable will be required and aligned\n#' in the direction specified (`stack_continuous`). Otherwise, a discrete\n#' variable will be required and aligned (`stack_discrete`).\n#'\n#' Several aliases are provided for convenience:\n#' - `stack_vertical`: A special case of `stack_layout` that sets `direction\n#' = \"v\"`.\n#' - `stack_horizontal`: A special case of `stack_layout` that sets `direction\n#' = \"h\"`.\n#' - `stack_discretev`: A special case of `stack_discrete` that sets `direction\n#' = \"v\"`.\n#' - `stack_discreteh`: A special case of `stack_discrete` that sets `direction\n#' = \"h\"`.\n#' - `stack_continuousv()`: A special case of `stack_free` that sets `direction\n#' = \"v\"`.\n#' - `stack_continuoush()`: A special case of `stack_free` that sets `direction\n#' = \"h\"`.\n#'\n#' For historical reasons, the following aliases are available:\n#' - `stack_align` is an alias for `stack_discrete`.\n#' - `stack_alignv` is an alias for `stack_discretev`.\n#' - `stack_alignh` is an alias for `stack_discreteh`.\n#' - `stack_free` is an alias for `stack_continuous`.\n#' - `stack_freev` is an alias for `stack_continuousv`.\n#' - `stack_freeh` is an alias for `stack_continuoush`.\n#'\n#' @param direction A string indicating the direction of the stack layout,\n#' either `\"h\"`(`horizontal`) or `\"v\"`(`vertical`).\n#' @param data `r rd_layout_data()`:\n#' - If `limits` is not provided, [`fortify_matrix()`] will be used to get a\n#' matrix.\n#' - If `limits` is specified, [`fortify_data_frame()`] will be used to get a\n#' data frame.\n#'\n#' @param ... Additional arguments passed to [`fortify_data_frame()`] or\n#' [`fortify_matrix()`].\n#' @param theme A [`theme()`][ggplot2::theme] object used to customize various\n#' elements of the layout, including `guides`, `title`, `subtitle`, `caption`,\n#' `margins`, `panel.border`, and `background`. By default, the theme will\n#' inherit from the parent `layout`. It also controls the panel spacing for all\n#' plots in the layout.\n#'\n#' @param sizes A numeric value or a [`unit`][grid::unit] object. When used for\n#' the [`quad_layout()`] annotation, it must be of length `1`. When used in the\n#' [`stack_layout()`] with a nested [`quad_layout()`], it should be of length\n#' `3`, specifying the relative heights (for `direction = \"h\"`) or widths (for\n#' `direction = \"v\"`) to be applied to the layout.\n#' @param limits A [`continuous_limits()`] object specifying the left/lower\n#' limit and the right/upper limit of the scale. Used to align the continuous\n#' axis.\n#' @return A `StackLayout` object.\n#' @examples\n#' set.seed(123)\n#' small_mat <- matrix(rnorm(56), nrow = 7L)\n#'\n#' stack_horizontal(small_mat) + align_dendro()\n#'\n#' # this is the same with:\n#' stack_discrete(\"h\", small_mat) + align_dendro()\n#'\n#' stack_discreteh(small_mat) + align_dendro()\n#'\n#' # For vertical layout:\n#' stack_vertical(small_mat) + align_dendro()\n#'\n#' @export\nstack_layout <- function(direction, data = NULL, ...,\n theme = NULL, sizes = NA, limits = waiver()) {\n if (is.waive(limits)) {\n stack_discrete(\n data = data, direction = direction, ...,\n theme = theme, sizes = sizes\n )\n } else {\n stack_continuous(\n data = data, direction = direction, ...,\n theme = theme, sizes = sizes, limits = limits\n )\n }\n}\n\n#' @export\n#' @rdname stack_layout\nstack_horizontal <- function(data = NULL, ..., limits = waiver()) {\n stack_layout(data = data, direction = \"h\", limits = limits, ...)\n}\n\n#' @export\n#' @rdname stack_layout\nstack_vertical <- function(data = NULL, ..., limits = waiver()) {\n stack_layout(data = data, direction = \"v\", limits = limits, ...)\n}\n\n###################################################################\n#' @export\n#' @rdname stack_layout\nstack_discrete <- function(direction, data = NULL, ...,\n theme = NULL, sizes = NA) {\n UseMethod(\"stack_discrete\", data)\n}\n\n#' @usage NULL\n#' @export\n#' @rdname stack_layout\nstack_align <- stack_discrete\n\n#' @export\n#' @rdname stack_layout\nstack_discretev <- function(data = NULL, ...) {\n stack_discrete(data = data, direction = \"v\", ...)\n}\n\n#' @usage NULL\n#' @export\n#' @rdname stack_layout\nstack_alignv <- stack_discretev\n\n#' @export\n#' @rdname stack_layout\nstack_discreteh <- function(data = NULL, ...) {\n stack_discrete(data = data, direction = \"h\", ...)\n}\n\n#' @usage NULL\n#' @export\n#' @rdname stack_layout\nstack_alignh <- stack_discreteh\n\n#' @export\nstack_discrete.default <- function(direction, data = NULL, ...,\n theme = NULL, sizes = NA) {\n direction <- check_direction(direction)\n # the observations are rows, we use matrix to easily\n # reshape it into a long formated data frame for ggplot,\n # and we can easily determine the number of observations\n # from matrix\n data <- data %|w|% NULL\n data <- fortify_matrix(data = data, ...)\n schemes <- default_schemes()\n if (!is.null(data) && !is.function(data)) {\n # if we have provided data, we initialize the `nobs`\n nobs <- vec_size(data)\n\n # for data has dimention but one dimention is 0\n # as.matrix(data.frame(row.names = letters))\n if (nobs == 0L) {\n cli_abort(\"empty data is no allowed\")\n }\n } else {\n nobs <- NULL\n }\n new_stack_layout(\n name = \"stack_discrete\",\n data = data, direction = direction,\n design = discrete_design(nobs = nobs),\n schemes = schemes, theme = theme, sizes = sizes\n )\n}\n\n#' @export\nstack_discrete.function <- function(direction, data = NULL, ...) {\n cli_abort(paste0(\n \"{.arg data} must be a {.cls matrix}, \",\n \"or an object coercible by {.fn fortify_matrix}, or a valid \",\n \"{.cls matrix}-like object coercible by {.fn as.matrix}\"\n ))\n}\n\n#' @export\nstack_discrete.formula <- stack_discrete.function\n\n################################################################\n#' @export\n#' @rdname stack_layout\nstack_continuous <- function(direction, data = NULL, ..., limits = NULL,\n theme = NULL, sizes = NA) {\n UseMethod(\"stack_continuous\", data)\n}\n\n#' @usage NULL\n#' @export\n#' @rdname stack_layout\nstack_free <- stack_continuous\n\n#' @export\n#' @rdname stack_layout\nstack_continuousv <- function(data = NULL, ...) {\n stack_continuous(data = data, direction = \"v\", ...)\n}\n\n#' @usage NULL\n#' @export\n#' @rdname stack_layout\nstack_freev <- stack_continuousv\n\n#' @export\n#' @rdname stack_layout\nstack_continuoush <- function(data = NULL, ...) {\n stack_continuous(data = data, direction = \"h\", ...)\n}\n\n#' @usage NULL\n#' @export\n#' @rdname stack_layout\nstack_freeh <- stack_continuoush\n\n#' @export\nstack_continuous.default <- function(direction, data = NULL, ...,\n limits = NULL, theme = NULL, sizes = NA) {\n assert_limits(limits)\n direction <- check_direction(direction)\n data <- data %|w|% NULL\n data <- fortify_data_frame(data = data, ...)\n schemes <- default_schemes()\n new_stack_layout(\n name = \"stack_continuous\",\n data = data, direction = direction, design = limits,\n schemes = schemes, theme = theme, sizes = sizes\n )\n}\n\n#' @export\nstack_continuous.function <- function(direction, data = NULL, ...) {\n cli_abort(paste0(\n \"{.arg data} must be a {.cls data.frame}, \",\n \"or an object coercible by {.fn fortify_data_frame}, or a valid \",\n \"{.cls data.frame}-like object coercible by {.fn as.data.frame}\"\n ))\n}\n\n#' @export\nstack_continuous.formula <- stack_continuous.function\n\n#' @importFrom methods new\nnew_stack_layout <- function(data, direction, design,\n schemes = NULL, theme = NULL, sizes = NA,\n name = NULL, call = caller_call()) {\n sizes <- check_stack_sizes(sizes, call = call)\n if (!is.null(theme)) assert_s3_class(theme, \"theme\", call = call)\n if (is.null(name)) {\n if (is_continuous_design(design)) {\n name <- \"stack_continuous\"\n } else {\n name <- \"stack_discrete\"\n }\n }\n new(\n \"StackLayout\",\n name = name, data = data,\n direction = direction,\n theme = theme, schemes = schemes, # used by the layout\n sizes = sizes, design = design\n )\n}\n\n############################################################\n# Used to place multiple objects in one axis\n#' @importFrom grid unit\n#' @importFrom ggplot2 waiver\n#' @keywords internal\n#' @include layout-chain-.R\nmethods::setClass(\n \"StackLayout\",\n contains = \"ChainLayout\",\n list(\n direction = \"character\",\n heatmap = \"list\", # used by heatmap annotation\n sizes = \"ANY\" # used by stack layout\n ),\n prototype = list(\n heatmap = list(\n position = NULL,\n free_guides = waiver(),\n # indicate whether or not the data is from the quad-layout matrix\n quad_matrix = FALSE\n )\n )\n)\n"], ["/ggalign/R/ggplot-utils.R", "#' @importFrom ggplot2 .pt\nggfun <- function(fn, mode = \"any\") from_namespace(\"ggplot2\", fn, mode = mode)\n\nallow_lambda <- function(x) {\n if (rlang::is_formula(x)) rlang::as_function(x) else x\n}\n\nis.waive <- function(x) inherits(x, \"waiver\")\n\n`%|w|%` <- function(x, y) if (inherits(x, \"waiver\")) y else x\n\nsnake_class <- function(x) ggfun(\"snake_class\")(x)\n\nggadd_default <- function(plot, mapping = NULL, theme = NULL) {\n if (!is.null(mapping)) {\n plot <- plot + mapping + plot$mapping\n }\n if (!is.null(theme)) plot$theme <- theme + plot$theme\n plot\n}\n\nis_palette_unset <- function(type, aes) {\n type <- match.arg(type, c(\"discrete\", \"continuous\", \"binned\"))\n aes <- match.arg(aes, c(\"fill\", \"colour\"))\n is.null(getOption(sprintf(\"ggplot2.%s.%s\", type, aes)))\n}\n\n# A guide-box should be a `zeroGrob()` or a `gtable` object\n#' @importFrom gtable is.gtable\nmaybe_guide_box <- function(x) inherits(x, \"zeroGrob\") || is.gtable(x)\n\n######################################################\ngguse_data <- function(plot, data) {\n # ggplot use waiver() to indicate no data\n plot[\"data\"] <- list(data %||% waiver())\n plot\n}\n\nggremove_margin <- function(plot, direction) {\n if (!is.null(direction) && packageVersion(\"ggplot2\") > \"3.5.2\") {\n plot <- plot + switch_direction(\n direction,\n theme(plot.margin = margin(t = 0, r = NA, b = 0, l = NA)),\n theme(plot.margin = margin(t = NA, r = 0, b = NA, l = 0))\n )\n }\n plot\n}\n\n######################################################\ndefault_expansion <- function(x = NULL, y = NULL) {\n structure(list(x = x, y = y), class = c(\"ggalign_default_expansion\"))\n}\n\n#' @importFrom ggplot2 ggplot_add ggproto ggproto_parent\n#' @export\nggplot_add.ggalign_default_expansion <- function(object, plot, object_name,\n ...) {\n if (is.null(.subset2(object, \"x\")) && is.null(.subset2(object, \"y\"))) {\n return(plot)\n }\n ParentFacet <- plot$facet\n plot$facet <- ggproto(\n NULL,\n ParentFacet,\n init_scales = function(self, layout, x_scale = NULL, y_scale = NULL,\n params) {\n if (!is.null(x_scale) && !is.null(.subset2(object, \"x\"))) {\n x_scale$expand <- x_scale$expand %|w|% .subset2(object, \"x\")\n }\n if (!is.null(y_scale) && !is.null(.subset2(object, \"y\"))) {\n y_scale$expand <- y_scale$expand %|w|% .subset2(object, \"y\")\n }\n ggproto_parent(ParentFacet, self)$init_scales(\n layout = layout,\n x_scale = x_scale,\n y_scale = y_scale,\n params = params\n )\n }\n )\n plot\n}\n\n######################################################\nreverse_continuous_axis <- function(plot, axis) {\n if (plot$scales$has_scale(axis)) {\n # modify scale in place\n scale <- plot$scales$get_scales(axis)\n if (!scale$is_discrete()) {\n if (identical(scale$trans$name, \"identity\")) {\n scale$trans <- scales::as.transform(\"reverse\")\n } else if (identical(scale$trans$name, \"reverse\")) {\n scale$trans <- scales::as.transform(\"identity\")\n }\n }\n } else {\n plot <- plot +\n switch(axis,\n x = ggplot2::scale_x_reverse(),\n y = ggplot2::scale_y_reverse()\n )\n }\n plot\n}\n"], ["/ggalign/R/ggplot-theme.R", "#' @importFrom ggplot2 theme_bw element_blank\ndefault_theme <- function() {\n if (is_theme_unset()) {\n theme_bw() +\n theme(\n axis.text = ggplot2::element_text(color = \"black\"),\n strip.text = ggplot2::element_text(color = \"black\"),\n panel.border = element_blank(),\n panel.grid = element_blank()\n )\n } else {\n theme_get()\n }\n}\n\n# Check if user has set the theme\nis_theme_unset <- function() {\n isTRUE(all.equal(\n complete_theme(ggfun(\"ggplot_global\")$theme_default),\n complete_theme(theme_get())\n ))\n}\n\nis_theme_complete <- function(x) isTRUE(attr(x, \"complete\", exact = TRUE))\n\n#' @importFrom ggplot2 rel element_blank\ntheme_no_strip <- function() {\n theme(\n strip.text = element_blank(),\n strip.background = element_blank()\n )\n}\n\ntheme_panel_border <- function() theme(panel.border = element_rect(fill = NA))\n\n#' @importFrom utils packageVersion\n#' @importFrom rlang try_fetch\ncomplete_theme <- function(theme) {\n if (packageVersion(\"ggplot2\") > \"3.5.2\") {\n ggfun(\"complete_theme\")(theme)\n } else {\n ggfun(\"plot_theme\")(list(theme = theme))\n }\n}\n\n#' @importFrom ggplot2 register_theme_elements el_def element_line\ntheme_elements <- function() {\n register_theme_elements(\n ggalign.line = element_line(\n color = \"black\",\n linewidth = 0.5,\n linetype = 1,\n lineend = \"butt\",\n linejoin = \"round\"\n ),\n ggalign.polygon = element_polygon(\n fill = NA,\n color = \"black\",\n linewidth = 0.5,\n linetype = 1,\n alpha = NA,\n lineend = \"butt\",\n linejoin = \"round\",\n linemitre = 10\n ),\n element_tree = list(\n plot.patch_title = el_def(\"element_text\", \"text\"),\n plot.patch_title.top = el_def(\"element_text\", \"text\"),\n plot.patch_title.left = el_def(\"element_text\", \"text\"),\n plot.patch_title.bottom = el_def(\"element_text\", \"text\"),\n plot.patch_title.right = el_def(\"element_text\", \"text\"),\n plot.patch_title.position = el_def(\"character\"),\n plot.patch_title.position.top = el_def(\"character\"),\n plot.patch_title.position.left = el_def(\"character\"),\n plot.patch_title.position.bottom = el_def(\"character\"),\n plot.patch_title.position.right = el_def(\"character\"),\n panel.spacing.r = el_def(c(\"unit\", \"rel\"), \"panel.spacing\"),\n ggalign.line = el_def(\"element_line\"),\n ggalign.curve = el_def(\"element_curve\"),\n ggalign.polygon = el_def(\"element_polygon\")\n )\n )\n}\n\n#' Used to match theme\n#'\n#' @keywords internal\n#' @noRd\ntheme_recycle <- function() structure(list(), class = \"theme_recycle\")\n\n#' @importFrom ggplot2 ggplot_add ggproto ggproto_parent\n#' @export\nggplot_add.theme_recycle <- function(object, plot, object_name, ...) {\n ParentFacet <- plot$facet\n if (!inherits(ParentFacet, c(\"FacetGrid\", \"FacetWrap\"))) {\n return(plot)\n }\n # recycle axis theme elements\n plot$facet <- ggproto(\n NULL, ParentFacet,\n draw_panels = function(self, panels, layout,\n x_scales = NULL, y_scales = NULL,\n ranges, coord, data = NULL, theme, params) {\n # we recycle the theme elements of the guide axis\n theme <- recycle_theme_axis(\"x\", theme, x_scales)\n theme <- recycle_theme_axis(\"y\", theme, y_scales)\n ParentCoord <- coord\n h_tick0 <- h_text0 <- 0L\n v_tick0 <- v_text0 <- 0L\n # subset theme for each panel\n coord <- ggproto(NULL, ParentCoord,\n # `align_scales` will attach the `.__plot_index__`\n render_axis_h = function(self, panel_params, theme) {\n scale <- (.subset2(panel_params, \"x\") %||%\n .subset2(panel_params, \"theta\")\n )$scale\n h_tick1 <- h_tick0 + length(scale$get_breaks())\n h_text1 <- h_text0 + length(scale$get_labels())\n theme <- subset_theme_axis(\n \"x\", theme, h_tick0, h_text0, h_tick1, h_text1\n )\n h_tick0 <<- h_tick1\n h_text0 <<- h_text1\n ggproto_parent(ParentCoord, self)$render_axis_h(\n panel_params, theme\n )\n },\n render_axis_v = function(self, panel_params, theme) {\n scale <- (.subset2(panel_params, \"y\") %||%\n .subset2(panel_params, \"r\")\n )$scale\n v_tick1 <- v_tick0 + length(scale$get_breaks())\n v_text1 <- v_text0 + length(scale$get_labels())\n theme <- subset_theme_axis(\n \"y\", theme, v_tick0, v_text0, v_tick1, v_text1\n )\n v_tick0 <<- v_tick1\n v_text0 <<- v_text1\n ggproto_parent(ParentCoord, self)$render_axis_v(\n panel_params, theme\n )\n }\n )\n ggproto_parent(ParentFacet, self)$draw_panels(\n panels = panels, layout = layout,\n x_scales = x_scales, y_scales = y_scales,\n ranges = ranges, coord = coord, data = data,\n theme = theme, params = params\n )\n }\n )\n plot\n}\n\n#################################################################\n# Apply a function to the vectorized field of the theme object\ntheme_vec <- function(.th, .el, .fn, ...) {\n element <- calc_element(.el, .th)\n if (inherits(element, \"element\")) {\n .th[[.el]] <- element_vec(element, .fn, ...)\n } else if (!is.null(element)) {\n .th[[.el]] <- .fn(element, ...)\n }\n .th\n}\n\nrecycle_theme_axis <- function(axis, theme, scales) {\n breaks <- unlist(lapply(scales, function(s) s$get_breaks()), FALSE, FALSE)\n labels <- unlist(lapply(scales, function(x) x$get_labels()), FALSE, FALSE)\n align_theme_axis(axis, theme,\n tick_fn = function(v, arg) rep(v, length.out = length(breaks)),\n text_fn = function(v, arg) rep(v, length.out = length(labels))\n )\n}\n\nsubset_theme_axis <- function(axis, theme, tick0, text0, tick1, text1) {\n tick_index <- (tick0 + 1L):tick1\n text_index <- (text0 + 1L):text1\n align_theme_axis(\n axis, theme,\n tick_fn = function(value) vec_slice(value, tick_index),\n text_fn = function(value) vec_slice(value, text_index)\n )\n}\n\nalign_theme_axis <- function(axis, theme, text_fn, tick_fn) {\n if (axis == \"y\") {\n positions <- c(\"left\", \"right\")\n } else {\n positions <- c(\"top\", \"bottom\")\n }\n # only apply the function when the element values is not a scalar\n .text_fn <- function(v) if (length(v) > 1L) text_fn(v) else v\n .tick_fn <- function(v) if (length(v) > 1L) tick_fn(v) else v\n for (element in paste(\"axis.text\", axis, positions, sep = \".\")) {\n theme <- theme_vec(theme, element, .text_fn)\n }\n for (element in paste(\"axis.ticks\", axis, positions, sep = \".\")) {\n theme <- theme_vec(theme, element, .tick_fn)\n }\n for (element in paste(\"axis.ticks.length\", axis, positions, sep = \".\")) {\n theme <- theme_vec(theme, element, .tick_fn)\n }\n theme\n}\n"], ["/ggalign/R/layout-chain-circle-.R", "#' Arrange plots in a circular layout\n#'\n#' @description\n#' `r lifecycle::badge('experimental')`\n#'\n#' If `limits` is provided, a continuous variable will be required and aligned\n#' in the direction specified (`circle_continuous`). Otherwise, a discrete\n#' variable will be required and aligned (`circle_discrete`).\n#'\n#' @param radial A [`coord_circle()`]/[`coord_radial()`][ggplot2::coord_radial]\n#' object that defines the global parameters for coordinate across all plots\n#' in the layout. The parameters `start`, `end`, `direction`, and `expand` will\n#' be inherited and applied uniformly to all plots within the layout. The\n#' parameters `theta` and `r.axis.inside` will always be ignored and will be set\n#' to `\"x\"` and `TRUE`, respectively, for all plots.\n#' @param direction A single string of `r oxford_or(c(\"inward\", \"outward\"))`,\n#' indicating the direction in which the plot is added.\n#' - `outward`: The plot is added from the inner to the outer.\n#' - `inward`: The plot is added from the outer to the inner.\n#' @inheritParams stack_layout\n#' @return A `CircleLayout` object.\n#' @examples\n#' set.seed(123)\n#'\n#' small_mat <- matrix(rnorm(56), nrow = 7)\n#' rownames(small_mat) <- paste0(\"row\", seq_len(nrow(small_mat)))\n#' colnames(small_mat) <- paste0(\"column\", seq_len(ncol(small_mat)))\n#'\n#' # circle_layout\n#' # same for circle_discrete()\n#' circle_layout(small_mat) +\n#' ggalign() +\n#' geom_tile(aes(y = .column_index, fill = value)) +\n#' scale_fill_viridis_c() +\n#' align_dendro(aes(color = branch), k = 3L) +\n#' scale_color_brewer(palette = \"Dark2\")\n#'\n#' # same for circle_continuous()\n#' circle_layout(mpg, limits = continuous_limits(c(3, 5))) +\n#' ggalign(mapping = aes(displ, hwy, colour = class)) +\n#' geom_point(size = 2) +\n#' ggalign(mapping = aes(displ, hwy, colour = class)) +\n#' geom_point(size = 2) &\n#' scale_color_brewer(palette = \"Dark2\") &\n#' theme_bw()\n#'\n#' @export\ncircle_layout <- function(data = NULL, ..., radial = NULL,\n direction = \"outward\", sector_spacing = NULL,\n limits = waiver(), theme = NULL,\n spacing_theta = deprecated()) {\n if (is.waive(limits)) {\n circle_discrete(\n data = data, ..., radial = radial,\n direction = direction, sector_spacing = sector_spacing,\n theme = theme, spacing_theta = spacing_theta\n )\n } else {\n circle_continuous(\n data = data, ..., radial = radial,\n direction = direction, theme = theme, limits = limits,\n spacing_theta = spacing_theta\n )\n }\n}\n\n############################################################\n#' @inheritParams facet_sector\n#' @examples\n#' # circle_discrete()\n#' # direction outward\n#' circle_discrete(small_mat) +\n#' align_dendro(aes(color = branch), k = 3L) +\n#' scale_color_brewer(palette = \"Dark2\") +\n#' ggalign() +\n#' geom_tile(aes(y = .column_index, fill = value)) +\n#' scale_fill_viridis_c()\n#'\n#' # direction inward\n#' circle_discrete(small_mat, direction = \"inward\") +\n#' ggalign() +\n#' geom_tile(aes(y = .column_index, fill = value)) +\n#' scale_fill_viridis_c() +\n#' align_dendro(aes(color = branch), k = 3L) +\n#' scale_color_brewer(palette = \"Dark2\")\n#'\n#' @export\n#' @rdname circle_layout\ncircle_discrete <- function(data = NULL, ..., radial = NULL,\n direction = \"outward\", sector_spacing = NULL,\n theme = NULL, spacing_theta = deprecated()) {\n UseMethod(\"circle_discrete\", data)\n}\n\n#' @export\ncircle_discrete.default <- function(data = NULL, ..., radial = NULL,\n direction = \"outward\",\n sector_spacing = NULL,\n theme = NULL,\n spacing_theta = deprecated()) {\n # the observations are rows, we use matrix to easily\n # reshape it into a long formated data frame for ggplot,\n # and we can easily determine the number of observations\n # from matrix\n data <- data %|w|% NULL\n data <- fortify_matrix(data = data, ...)\n schemes <- default_schemes()\n if (!is.null(data) && !is.function(data)) {\n # if we have provided data, we initialize the `nobs`\n nobs <- vec_size(data)\n } else {\n nobs <- NULL\n }\n new_circle_layout(\n data = data,\n design = discrete_design(nobs = nobs),\n radial = radial, direction = direction, sector_spacing = sector_spacing,\n schemes = schemes, theme = theme, spacing_theta = spacing_theta\n )\n}\n\n#' @export\ncircle_discrete.function <- function(data = NULL, ...) {\n cli_abort(paste0(\n \"{.arg data} must be a {.cls matrix}, \",\n \"or an object coercible by {.fn fortify_matrix}, or a valid \",\n \"{.cls matrix}-like object coercible by {.fn as.matrix}\"\n ))\n}\n\n#' @export\ncircle_discrete.formula <- circle_discrete.function\n\n################################################################\n#' @examples\n#' # circle_continuous()\n#' circle_continuous(mpg, limits = continuous_limits(c(3, 5))) +\n#' ggalign(mapping = aes(displ, hwy, colour = class)) +\n#' geom_point(size = 2) +\n#' ggalign(mapping = aes(displ, hwy, colour = class)) +\n#' geom_point(size = 2) &\n#' scale_color_brewer(palette = \"Dark2\") &\n#' theme_bw()\n#' @export\n#' @rdname circle_layout\ncircle_continuous <- function(data = NULL, ..., radial = NULL,\n direction = \"outward\", sector_spacing = NULL,\n limits = NULL, theme = NULL,\n spacing_theta = deprecated()) {\n UseMethod(\"circle_continuous\", data)\n}\n\n#' @export\ncircle_continuous.default <- function(data = NULL, ..., radial = NULL,\n direction = \"outward\",\n sector_spacing = NULL,\n limits = NULL, theme = NULL,\n spacing_theta = deprecated()) {\n assert_limits(limits)\n data <- data %|w|% NULL\n data <- fortify_data_frame(data = data, ...)\n schemes <- default_schemes()\n new_circle_layout(\n data = data, design = limits,\n radial = radial, direction = direction, sector_spacing = sector_spacing,\n schemes = schemes, theme = theme, spacing_theta = spacing_theta\n )\n}\n\n#' @export\ncircle_continuous.function <- function(data = NULL, ...) {\n cli_abort(paste0(\n \"{.arg data} must be a {.cls data.frame}, \",\n \"or an object coercible by {.fn fortify_data_frame}, or a valid \",\n \"{.cls data.frame}-like object coercible by {.fn as.data.frame}\"\n ))\n}\n\n#' @export\ncircle_continuous.formula <- circle_continuous.function\n\n#' @importFrom methods new\nnew_circle_layout <- function(data, design, radial, direction,\n sector_spacing = NULL, schemes = NULL,\n theme = NULL, name = NULL,\n spacing_theta = deprecated(),\n call = caller_call()) {\n if (!is.null(theme)) assert_s3_class(theme, \"theme\", call = call)\n if (!is.null(radial) && !inherits(radial, c(\"CoordRadial\"))) {\n cli_abort(\"{.arg radial} must be created with {.fn coord_circle}\",\n call = call\n )\n }\n if (!is.null(radial) && abs(diff(radial$arc)) < pi / 2L) {\n cli_abort(\n \"Cannot create circle of acute angle < 90 in {.arg radial}\",\n call = call\n )\n }\n direction <- arg_match0(direction, c(\"inward\", \"outward\"))\n if (is.null(name)) {\n if (is_continuous_design(design)) {\n name <- \"circle_continuous\"\n } else {\n name <- \"circle_discrete\"\n }\n }\n if (lifecycle::is_present(spacing_theta)) {\n lifecycle::deprecate_warn(\n \"1.0.2\",\n \"facet_sector(spacing_theta = )\",\n \"facet_sector(sector_spacing = )\"\n )\n if (is.null(sector_spacing)) sector_spacing <- spacing_theta\n }\n new(\n \"CircleLayout\",\n name = name, data = data,\n schemes = schemes, # used by the layout\n design = design,\n sector_spacing = sector_spacing,\n theme = theme,\n radial = radial, direction = direction\n )\n}\n\n############################################################\n# Used to place multiple objects in one axis\n#' @importFrom grid unit\n#' @importFrom ggplot2 waiver\n#' @keywords internal\n#' @include layout-chain-.R\nmethods::setClass(\"CircleLayout\",\n contains = \"ChainLayout\",\n list(radial = \"ANY\", sector_spacing = \"ANY\", direction = \"character\")\n)\n"], ["/ggalign/R/ggplot-facet-sector.R", "#' Polar coordinates with Facet support\n#'\n#' Draw each panel in a sector of the polar coordinate system. If\n#' `facet_sector()` is used in a ggplot, the coordinate system must be created\n#' with [`coord_circle()`] or [`coord_radial()`][ggplot2::coord_radial].\n#'\n#' @inheritParams ggplot2::facet_wrap\n#' @param sector_spacing The size of spacing between different panel. A numeric\n#' of the radians or a [`rel()`][ggplot2::rel] object.\n#' @param radial `r lifecycle::badge(\"deprecated\")` Please add the coordinate\n#' system directly to the ggplot instead.\n#' @param spacing_theta `r lifecycle::badge(\"deprecated\")` Please use\n#' `sector_spacing` instead.\n#' @examples\n#' ggplot(mtcars, aes(disp, mpg)) +\n#' geom_point() +\n#' facet_sector(vars(cyl)) +\n#' coord_circle(\n#' start = -0.4 * pi, end = 0.4 * pi, inner.radius = 0.3,\n#' outer.radius = 0.8, expand = TRUE\n#' )\n#' @importFrom ggplot2 ggproto\n#' @export\nfacet_sector <- function(facets, sector_spacing = pi / 180, drop = TRUE,\n radial = deprecated(), spacing_theta = deprecated()) {\n if (packageVersion(\"ggplot2\") > \"3.5.2\") {\n facets <- ggfun(\"compact_facets\")(facets)\n } else {\n facets <- ggfun(\"wrap_as_facets_list\")(facets)\n }\n if (inherits(sector_spacing, \"CoordRadial\") ||\n lifecycle::is_present(radial)) {\n lifecycle::deprecate_stop(\n \"1.0.2\",\n \"facet_sector(radial = )\",\n details = \"Please add the coordinate to the ggplot instead\"\n )\n }\n if (lifecycle::is_present(spacing_theta)) {\n lifecycle::deprecate_warn(\n \"1.0.2\",\n \"facet_sector(spacing_theta = )\",\n \"facet_sector(sector_spacing = )\"\n )\n sector_spacing <- spacing_theta\n }\n\n # @param strip.position By default, the labels are displayed on the\n # `\"outer\"` of the plot. Allowed values are `r oxford_or(c(\"outer\",\n # \"inner\"))`\n # strip.position <- arg_match0(strip.position, c(\"outer\", \"inner\"))\n # strip.position <- switch(strip.position,\n # outer = \"top\",\n # inner = \"bottom\"\n # )\n # labeller <- ggfun(\"fix_labeller\")(labeller)\n assert_bool(drop)\n\n # TO-DO: remove this line and update to\n # the next version of ggplot2 (> 3.5.2)\n if (packageVersion(\"ggplot2\") > \"3.5.2\") {\n dir <- \"lt\"\n } else {\n dir <- \"h\"\n }\n ggproto(\n NULL,\n FacetSector,\n sector_spacing = sector_spacing,\n params = list(\n facets = facets,\n free = list(x = TRUE, y = FALSE),\n strip.position = \"top\",\n drop = drop, ncol = NULL, nrow = 1L,\n space_free = list(x = TRUE, y = FALSE),\n labeller = ggplot2::label_value, dir = dir,\n draw_axes = list(x = TRUE, y = FALSE),\n axis_labels = list(x = TRUE, y = FALSE),\n as.table = TRUE\n )\n )\n}\n\n#' @importFrom ggplot2 ggplot_add\n#' @export\nggplot_add.FacetSector <- function(object, plot, object_name, ...) {\n plot <- NextMethod()\n if (!inherits(plot, \"ggalign_facet_sector_plot\")) {\n plot <- add_class(plot, \"ggalign_facet_sector_plot\")\n }\n plot\n}\n\n#' @importFrom ggplot2 ggplot_build ggproto ggproto_parent\n#' @export\nggplot_build.ggalign_facet_sector_plot <- function(plot, ...) {\n if (inherits(plot$facet, \"FacetSector\")) {\n if (!inherits(plot$coordinates, \"CoordRadial\")) {\n if (!isTRUE(plot$coordinates$default)) {\n cli_abort(c(\n paste(\n \"Cannot use {.fn {snake_class(plot$coordinates)}}\",\n \"coordinate with {.fn facet_sector}\"\n ),\n i = \"Please use {.fn coord_circle}/{.fn coord_radial} instead\"\n ))\n }\n plot$coordinates <- coord_circle()\n }\n ParentLayout <- plot$layout\n plot$layout <- ggproto(\n \"FacetSectorLayout\", ParentLayout,\n setup_panel_params = function(self) {\n ggproto_parent(ParentLayout, self)$setup_panel_params()\n if (is.null(ggplot2::Facet$setup_panel_params) &&\n !is.null(self$facet$setup_panel_params)) {\n self$panel_params <- self$facet$setup_panel_params(\n self$panel_params, self$coord\n )\n }\n invisible()\n }\n )\n }\n NextMethod()\n}\n\n#' @importFrom rlang inject\n#' @importFrom grid gTree editGrob viewport\n#' @importFrom ggplot2 ggproto ggproto_parent\nFacetSector <- ggproto(\n \"FacetSector\", ggplot2::FacetWrap,\n setup_panel_params = function(self, panel_params, coord, ...) {\n # total theta for panel area and panel spacing\n arc_theta <- abs(diff(coord$arc))\n sector_spacing <- self$sector_spacing\n if (inherits(sector_spacing, \"rel\")) {\n sector_spacing <- sector_spacing * arc_theta\n }\n panel_weights <- vapply(panel_params, function(panel_param) {\n abs(diff(.subset2(panel_param, \"theta.range\")))\n }, numeric(1L), USE.NAMES = FALSE)\n\n # total theta for panel area\n panel_theta <- arc_theta -\n # substract the number of spacing between panels\n sector_spacing *\n # for the whole circle, arc_theta == 2 * pi\n # there should be as many panels as the number of panel spacing\n if (abs(arc_theta - 2 * pi) < .Machine$double.eps^0.5) {\n length(panel_weights)\n } else {\n length(panel_weights) - 1L\n }\n if (panel_theta <= 0L) {\n cli_abort(\"No panel area, try to reduce {.arg sector_spacing}\")\n }\n\n # re-distribute the arc for each panel\n panel_point <- vec_interleave(\n panel_theta * panel_weights / sum(panel_weights),\n rep_len(sector_spacing, length(panel_weights))\n )\n panel_point <- cumsum(c(coord$arc[1L], utils::head(panel_point, -1L)))\n for (i in seq_along(panel_params)) {\n panel_param <- .subset2(panel_params, i)\n panel_param$arc <- panel_point[i * 2L - 1:0]\n panel_param$bbox <- ggfun(\"polar_bbox\")(\n panel_param$arc, margin = c(0, 0, 0, 0),\n inner_radius = coord$inner_radius\n )\n panel_params[[i]] <- panel_param\n }\n panel_params\n },\n draw_panels = function(self, panels, layout, x_scales, y_scales, ranges,\n coord, data, theme, params) {\n # merge different sector into one panel\n bbox <- ggfun(\"polar_bbox\")(\n coord$arc, margin = c(0, 0, 0, 0),\n inner_radius = coord$inner_radius\n )\n for (i in seq_along(panels)) {\n panel_param <- .subset2(ranges, i)\n vp <- list(\n x = scales::rescale(panel_param$bbox$x, from = bbox$x),\n y = scales::rescale(panel_param$bbox$y, from = bbox$y)\n )\n panels[[i]] <- editGrob(\n .subset2(panels, i),\n vp = viewport(\n x = vp$x[1L], y = vp$y[1L],\n width = abs(diff(vp$x)),\n height = abs(diff(vp$y)),\n just = c(0, 0),\n clip = \"off\",\n default.units = \"native\"\n )\n )\n }\n panels <- gTree(children = inject(gList(!!!panels)))\n ranges <- lapply(ranges, function(panel_param) {\n panel_param$arc <- coord$arc\n panel_param$bbox <- bbox\n panel_param\n })\n ggplot2::FacetNull$draw_panels(\n panels = list(panels),\n layout = layout, x_scales = x_scales, y_scales = y_scales,\n ranges = ranges, coord = coord, data = data,\n theme = theme, params = params\n )\n }\n)\n"], ["/ggalign/R/layout-heatmap-oncoplot.R", "#' Create an OncoPrint\n#'\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' The `ggoncoplot()` function generates `oncoPrint` visualizations that display\n#' genetic alterations in a matrix format. This function is especially useful\n#' for visualizing complex genomic data, such as mutations, copy number\n#' variations, and other genomic alterations in cancer research.\n#'\n#' @details\n#' `ggoncoplot()` is a wrapper around the [`ggheatmap()`] function, designed to\n#' simplify the creation of `OncoPrint`-style visualizations. The function\n#' automatically processes the input character matrix by splitting the encoded\n#' alterations (delimited by `r oxford_or(c(\";\", \":\", \",\", \"|\"))`) into\n#' individual genomic events and unnesting the columns for visualization.\n#'\n#' @param data A character matrix which encodes the alterations, you can use\n#' `r oxford_or(c(\";\", \":\", \",\", \"|\"))` to separate multiple alterations.\n#' @inheritParams heatmap_layout\n#' @param map_width,map_height A named numeric value defines the width/height of\n#' each alterations.\n#'\n#' @param reorder_row A boolean value indicating whether to reorder the rows\n#' based on the frequency of alterations. You can set this to `FALSE`, then add\n#' `align_order(~rowSums(!is.na(.x)), reverse = TRUE)` to achieve the same\n#' result. You may also need to set `strit = FALSE` in [`align_order()`] if\n#' there are already groups.\n#'\n#' @param reorder_column A boolean value indicating whether to reorder the\n#' columns based on the characteristics of the alterations. You can set this to\n#' `FALSE`, then add `align_order2(memo_order)` to achieve the same result. You\n#' may also need to set `strit = FALSE` in [`align_order2()`] if there are\n#' already groups.\n#'\n#' @param remove_duplicates A logical value indicating whether to remove\n#' duplicated variants within the same cell.\n#'\n#' @param filling Same as [`ggheatmap()`], but only `\"tile\"` can be used.\n#' @examples\n#' # A simple example from `ComplexHeatmap`\n#' mat <- read.table(textConnection(\n#' \"s1,s2,s3\n#' g1,snv;indel,snv,indel\n#' g2,,snv;indel,snv\n#' g3,snv,,indel;snv\"\n#' ), row.names = 1, header = TRUE, sep = \",\", stringsAsFactors = FALSE)\n#'\n#' ggoncoplot(mat, map_width = c(snv = 0.5), map_height = c(indel = 0.9)) +\n#' guides(fill = \"none\") +\n#' anno_top(size = 0.5) +\n#' ggalign() +\n#' geom_bar(aes(fill = value), data = function(x) {\n#' subset(x, !is.na(value))\n#' }) +\n#' anno_right(size = 0.5) +\n#' ggalign() +\n#' geom_bar(aes(fill = value), orientation = \"y\", data = function(x) {\n#' subset(x, !is.na(value))\n#' }) &\n#' scale_fill_brewer(palette = \"Dark2\", na.translate = FALSE)\n#' @inherit heatmap_layout return\n#' @importFrom ggplot2 aes\n#' @export\nggoncoplot <- function(data = NULL, mapping = aes(), ...,\n map_width = NULL, map_height = NULL,\n reorder_row = reorder_column,\n reorder_column = TRUE,\n remove_duplicates = FALSE,\n width = NA, height = NA, filling = waiver(),\n theme = NULL, active = NULL) {\n UseMethod(\"ggoncoplot\")\n}\n\n#' @export\nggoncoplot.NULL <- function(data = NULL, mapping = aes(), ...) {\n cli_abort(\"{.fn ggoncoplot} only accept a valid character matrix\")\n}\n\n#' @export\nggoncoplot.functon <- ggoncoplot.NULL\n\n#' @export\nggoncoplot.formula <- ggoncoplot.functon\n\n#' @importFrom ggplot2 aes\n#' @importFrom rlang arg_match0\n#' @export\n#' @rdname ggoncoplot\nggoncoplot.default <- function(data = NULL, mapping = aes(), ...,\n map_width = NULL, map_height = NULL,\n reorder_row = reorder_column,\n reorder_column = TRUE,\n remove_duplicates = FALSE,\n width = NA, height = NA, filling = waiver(),\n theme = NULL, active = NULL) {\n # prepare the matrix\n data <- fortify_matrix(data = data, ...)\n if (!is.character(data)) {\n cli_abort(\"{.arg data} must be a character matrix\")\n }\n\n assert_bool(reorder_column)\n assert_bool(reorder_row)\n assert_bool(remove_duplicates)\n\n # convert empty string into NA\n data <- trimws(data, whitespace = \"[\\\\h\\\\v]\")\n data[data == \"\"] <- NA_character_\n\n # check filling\n if (isTRUE(filling) || is.waive(filling)) {\n filling <- \"tile\"\n } else if (isFALSE(filling)) {\n filling <- NULL\n } else if (!is.null(filling)) {\n filling <- arg_match0(filling, c(\"tile\", \"raster\"))\n if (filling == \"raster\") {\n cli_warn(\"Cannot use {.fn geom_raster} in oncoplot\")\n filling <- \"tile\"\n }\n }\n\n # prepare the plot data action\n pdata <- function(data) {\n vars <- strsplit(data$value, split = \"\\\\s*[;:,|]\\\\s*\", perl = TRUE)\n if (remove_duplicates) vars <- lapply(vars, vec_unique)\n lvls <- ggalign_lvls_get(data)\n data <- vec_rep_each(data, list_sizes(vars))\n value <- unlist(vars, recursive = FALSE, use.names = FALSE)\n if (!is.null(lvls)) value <- factor(value, levels = lvls)\n data$value <- value\n data\n }\n\n # draw the oncoplot\n ans <- heatmap_layout(\n data = data, mapping = mapping,\n width = width, height = height,\n theme = theme, active = active, filling = NULL\n ) -\n # set the default `scheme_data()`\n scheme_data(data = pdata)\n\n # prepare counts matrix to reorder the column or rows\n if (reorder_column || reorder_row) {\n counts <- !is.na(data)\n storage.mode(counts) <- \"integer\"\n weights <- rowSums(counts)\n row_index <- order(weights, decreasing = TRUE)\n }\n\n if (reorder_row) {\n ans <- ans + anno_left() + align_order(row_index, reverse = TRUE)\n }\n if (reorder_column) {\n column_scores <- .memo_order(vec_slice(counts, row_index))\n ans <- ans +\n anno_top() +\n align_order(order(column_scores, decreasing = TRUE))\n }\n\n # reset the active context\n ans <- ans + quad_active()\n if (!is.null(filling)) {\n # we always make sure heatmap body has such action data\n ans <- ans + scheme_data(data = pdata)\n\n # set mapping for width and height\n tile_mapping <- aes(\n .data$.x, .data$.y,\n fill = .data$value,\n width = replace_na(map_width[.data$value], 1),\n height = replace_na(map_height[.data$value], 1)\n )\n if (!is.null(map_width)) {\n if (!rlang::is_named(map_width) || !is.numeric(map_width)) {\n cli_abort(\"{.arg map_width} must be a named numeric\")\n }\n } else {\n tile_mapping$width <- NULL\n }\n if (!is.null(map_height)) {\n if (!rlang::is_named(map_height) || !is.numeric(map_height)) {\n cli_abort(\"{.arg map_height} must be a named numeric\")\n }\n } else {\n tile_mapping$height <- NULL\n }\n # check if user has provided and manual fill mapping\n if (!is.null(.subset2(ans@plot$mapping, \"fill\"))) {\n tile_mapping$fill <- NULL\n }\n ans <- ans + ggplot2::geom_tile(tile_mapping)\n }\n ans\n}\n\n#' Sort matrix for better visualization\n#'\n#' Helper function used to order the Oncoplot samples. Typically, you would use\n#' this in combination with [`align_order2()`], e.g.,\n#' `align_order2(memo_order)`.\n#'\n#' @param x A matrix, where `NA` values will be treated as empty.\n#' @return A vector of ordering weights.\n#' @export\nmemo_order <- function(x) {\n # For `align_order2()`, rows are considered as the observations\n # `.memo_order` will regard the columns as the observations\n .memo_order(t(x), counts = FALSE, reorder_rows = TRUE)\n}\n\n# Following code is modified from\n# \n.memo_order <- function(x, counts = TRUE, reorder_rows = FALSE) {\n if (!isTRUE(counts)) {\n x <- !is.na(x)\n storage.mode(x) <- \"integer\"\n }\n if (isTRUE(reorder_rows)) {\n row_index <- order(rowSums(x), decreasing = TRUE)\n x <- vec_slice(x, row_index)\n }\n structure(\n apply(x, 2L, function(x) {\n score <- 2^(length(x) - seq_along(x))\n score[x == 0L] <- 0\n sum(score)\n }),\n class = \"memo_weights\"\n )\n}\n\n#' @export\n#' @rdname order2\norder2.memo_weights <- function(x) order(x, decreasing = TRUE)\n"], ["/ggalign/R/alignpatch-ggplot2.R", "#' @export\nggalign_gtable.ggplot <- function(x) alignpatch(x)$patch_gtable()\n\n#' @export\nggalign_build.ggplot <- function(x) x\n\n##################################################\n#' @export\n#' @include alignpatch-build.R\nprint.patch_ggplot <- print.alignpatches\n\n#' @importFrom grid grid.draw\n#' @exportS3Method\ngrid.draw.patch_ggplot <- grid.draw.alignpatches\n\n#################################################\n#' @importFrom ggplot2 ggproto\n#' @export\nalignpatch.ggplot <- function(x) ggproto(NULL, PatchGgplot, plot = x)\n\n# ggplot2 has following grobs:\n# panel\n# axis: must follow panel\n# strip: must follow the panel\n# xlab/ylab: can be aligned or follow the panel\n# subtitle\n# title\n# caption\n# guide: can be collected or kept\n#' @importFrom ggplot2 ggplotGrob update_labels\n#' @include alignpatch-.R\nPatchGgplot <- ggproto(\"PatchGgplot\", Patch,\n set_guides = function(guides) guides,\n patch_gtable = function(self, theme, guides, plot = self$plot) {\n # extract patch titles --------------------------------\n patch_titles <- plot$ggalign_patch_labels\n\n # complete_theme() will ensure elements exist --------\n theme <- complete_theme(plot$theme)\n # here: we remove tick length when the tick is blank\n theme <- setup_tick_length_element(theme)\n plot$theme <- theme\n\n # build the grob -------------------------------------\n ans <- ggplotGrob(plot)\n strip_pos <- find_strip_pos(ans)\n # always add strips columns and/or rows\n ans <- add_strips(ans, strip_pos)\n setup_patch_titles(ans, patch_titles = patch_titles, theme = theme)\n },\n respect = function(self, gt = self$gt) .subset2(gt, \"respect\"),\n\n #' @importFrom ggplot2 find_panel\n align_panel_sizes = function(self, panel_width, panel_height,\n gt = self$gt) {\n panel_pos <- find_panel(gt)\n rows <- c(.subset2(panel_pos, \"t\"), .subset2(panel_pos, \"b\"))\n cols <- c(.subset2(panel_pos, \"l\"), .subset2(panel_pos, \"r\"))\n respect <- .subset2(gt, \"respect\")\n if (rows[1L] == rows[2L] && cols[1L] == cols[2L]) {\n if (respect) {\n can_set_width <- is.na(as.numeric(panel_width))\n can_set_height <- is.na(as.numeric(panel_height))\n w <- .subset2(gt, \"widths\")[LEFT_BORDER + 1L]\n h <- .subset2(gt, \"heights\")[TOP_BORDER + 1L]\n if (can_set_width && can_set_height) {\n panel_width <- w\n panel_height <- h\n } else if (can_set_width) {\n panel_width <- as.numeric(w) / as.numeric(h) * panel_height\n } else if (can_set_height) {\n panel_height <- as.numeric(h) / as.numeric(w) * panel_width\n } else {\n respect <- FALSE\n }\n }\n } else {\n respect <- FALSE\n }\n list(width = panel_width, height = panel_height, respect = respect)\n },\n\n #' @importFrom gtable gtable_add_grob gtable_height gtable_width\n #' @importFrom grid unit viewport\n #' @importFrom ggplot2 find_panel\n free_border = function(self, borders, gt = self$gt) {\n panel_pos <- find_panel(gt)\n for (border in borders) {\n if (border == \"top\") {\n gt <- liberate_area(\n gt,\n 1L,\n 1L,\n .subset2(panel_pos, \"t\") - 1L,\n ncol(gt),\n clip = \"off\",\n name = \"free-border-top\",\n vp = ~ viewport(\n y = 0L, just = \"bottom\",\n height = gtable_height(.x)\n )\n )\n } else if (border == \"left\") {\n gt <- liberate_area(\n gt,\n 1L,\n 1L,\n nrow(gt),\n .subset2(panel_pos, \"l\") - 1L,\n clip = \"off\",\n name = \"free-border-left\",\n vp = ~ viewport(\n x = 1L, just = \"right\",\n width = gtable_width(.x)\n )\n )\n } else if (border == \"bottom\") {\n gt <- liberate_area(\n gt,\n .subset2(panel_pos, \"b\") + 1L,\n 1L,\n nrow(gt),\n ncol(gt),\n clip = \"off\",\n name = \"free-border-bottom\",\n vp = ~ viewport(\n y = 1L, just = \"top\",\n height = gtable_height(.x)\n )\n )\n } else if (border == \"right\") {\n gt <- liberate_area(\n gt,\n 1L,\n .subset2(panel_pos, \"r\") + 1L,\n nrow(gt),\n ncol(gt),\n clip = \"off\",\n name = \"free-border-right\",\n vp = ~ viewport(\n x = 0L, just = \"left\",\n width = gtable_width(.x)\n )\n )\n }\n }\n gt\n },\n align_free_border = function(self, borders,\n t = NULL, l = NULL, b = NULL, r = NULL,\n gt = self$gt) {\n if (is.null(t) && is.null(l) && is.null(b) && is.null(r)) {\n return(gt)\n }\n # For free borders, we also align the margins\n for (border in borders) {\n i <- .subset2(.subset2(gt, \"layout\"), \"name\") ==\n sprintf(\"free-border-%s\", border)\n if (any(i)) {\n i <- which(i)\n gt$grobs[[i]] <- switch_position(\n border,\n Patch$align_border(l = l, r = r, gt = gt$grobs[[i]]),\n Patch$align_border(t = t, b = b, gt = gt$grobs[[i]])\n )\n }\n }\n gt\n },\n\n #' @importFrom ggplot2 find_panel\n #' @importFrom gtable is.gtable gtable_height gtable_width gtable_add_grob\n #' @importFrom grid grobHeight grobWidth viewport\n free_lab = function(self, labs, gt = self$gt) {\n panel_pos <- find_panel(gt)\n for (lab in labs) {\n name <- paste(\n switch_position(lab, \"xlab\", \"ylab\"),\n \"axis\", lab,\n sep = \"-\"\n )\n if (lab == \"top\") {\n panel_border <- .subset2(panel_pos, \"t\")\n gt <- liberate_area(\n gt,\n panel_border - 3L,\n .subset2(panel_pos, \"l\"),\n panel_border - 1L,\n .subset2(panel_pos, \"r\"),\n name = name,\n vp = ~ viewport(\n y = 0L, just = \"bottom\",\n height = gtable_height(.x)\n )\n )\n } else if (lab == \"left\") {\n panel_border <- .subset2(panel_pos, \"l\")\n gt <- liberate_area(\n gt,\n .subset2(panel_pos, \"t\"),\n panel_border - 3L,\n .subset2(panel_pos, \"b\"),\n panel_border - 1L,\n name = name,\n vp = ~ viewport(\n x = 1L, just = \"right\",\n width = gtable_width(.x)\n )\n )\n } else if (lab == \"bottom\") {\n panel_border <- .subset2(panel_pos, \"b\")\n gt <- liberate_area(\n gt,\n panel_border + 1L,\n .subset2(panel_pos, \"l\"),\n panel_border + 3L,\n .subset2(panel_pos, \"r\"),\n name = name,\n vp = ~ viewport(\n y = 1L, just = \"top\",\n height = gtable_height(.x)\n )\n )\n } else if (lab == \"right\") {\n panel_border <- .subset2(panel_pos, \"r\")\n gt <- liberate_area(\n gt,\n .subset2(panel_pos, \"t\"),\n panel_border + 1L,\n .subset2(panel_pos, \"b\"),\n panel_border + 3L,\n name = name,\n vp = ~ viewport(\n x = 0L, just = \"left\",\n width = gtable_width(.x)\n )\n )\n }\n }\n gt\n }\n)\n\n#' @importFrom ggplot2 calc_element\n#' @importFrom grid unit\nsetup_tick_length_element <- function(theme) {\n for (tick in c(\"x.top\", \"y.left\", \"x.bottom\", \"y.right\")) {\n for (axis in c(\"axis.minor\", \"axis\")) {\n blank <- inherits(calc_element(\n paste(axis, \"ticks\", tick, sep = \".\"), theme\n ), \"element_blank\")\n if (blank) { # No ticks, no length\n element <- paste(axis, \"ticks.length\", tick, sep = \".\")\n theme[[element]] <- unit(0, \"mm\")\n }\n }\n }\n theme\n}\n\n#' @importFrom gtable gtable_add_rows gtable_add_cols\n#' @importFrom ggplot2 find_panel\n#' @importFrom grid unit\nadd_strips <- function(gt, strip_pos) {\n panel_loc <- find_panel(gt)\n strip_pos <- switch(strip_pos, inside = 0L, outside = 2L) # styler: off\n layout <- .subset2(gt, \"layout\")\n if (!any(grepl(\"strip-b\", layout$name))) { # No strips\n gt <- gtable_add_rows(\n gt, unit(0L, \"mm\"),\n panel_loc$b + strip_pos\n )\n } else if (strip_pos == 2L && !any(layout$b == panel_loc$b + 2L)) {\n # Merge the strip-gap height into the axis and remove it. Only performed\n # if an axis exist\n gt$heights[panel_loc$b + 1L] <- sum(gt$heights[panel_loc$b + 1:2])\n gt <- gt[-(panel_loc$b + 2L), ]\n }\n if (!any(grepl(\"strip-t\", layout$name))) {\n gt <- gtable_add_rows(\n gt, unit(0L, \"mm\"),\n panel_loc$t - 1L - strip_pos\n )\n } else if (strip_pos == 2L && !any(layout$t == panel_loc$t - 2L)) {\n gt$heights[panel_loc$t - 1L] <- sum(gt$heights[panel_loc$t - 1:2])\n gt <- gt[-(panel_loc$t - 2L), ]\n }\n if (!any(grepl(\"strip-r\", layout$name))) {\n gt <- gtable_add_cols(\n gt, unit(0L, \"mm\"),\n panel_loc$r + strip_pos\n )\n } else if (strip_pos == 2L && !any(layout$r == panel_loc$r + 2L)) {\n gt$widths[panel_loc$r + 1L] <- sum(gt$widths[panel_loc$r + 1:2])\n gt <- gt[, -(panel_loc$r + 2L)]\n }\n if (!any(grepl(\"strip-l\", layout$name))) {\n gt <- gtable_add_cols(\n gt, unit(0L, \"mm\"),\n panel_loc$l - 1L - strip_pos\n )\n } else if (strip_pos == 2L && !any(layout$l == panel_loc$l - 2L)) {\n gt$widths[panel_loc$l - 1L] <- sum(gt$widths[panel_loc$l - 1:2])\n gt <- gt[, -(panel_loc$l - 2L)]\n }\n gt\n}\n\n# theme(strip.placement)\n#' @importFrom ggplot2 find_panel\nfind_strip_pos <- function(gt) {\n panel_loc <- find_panel(gt)\n layout <- .subset2(gt, \"layout\")\n nms <- .subset2(layout, \"name\")\n ind <- grep(\"strip-t\", nms)\n if (length(ind) != 0L && panel_loc$t - min(layout$t[ind]) != 1L) {\n return(\"outside\")\n }\n ind <- grep(\"strip-l\", nms)\n if (length(ind) != 0L && panel_loc$l - min(layout$l[ind]) != 1L) {\n return(\"outside\")\n }\n ind <- grep(\"strip-r\", nms)\n if (length(ind) != 0L && max(layout$r[ind]) - panel_loc$r != 1L) {\n return(\"outside\")\n }\n ind <- grep(\"strip-b\", nms)\n if (length(ind) != 0L && max(layout$b[ind]) - panel_loc$b != 1L) {\n return(\"outside\")\n }\n \"inside\"\n}\n"], ["/ggalign/R/ggplot-geom-gshape.R", "#' Layer with a customized shape graphic using grid functions.\n#'\n#' @description\n#' `r lifecycle::badge('questioning')`\n#'\n#' `geom_gshape` depends on the new aesthetics `gshape` (shape with grid\n#' functions), which should always be provided with [`scale_gshape_manual()`],\n#' in which, we can provide a list of grobs or functions that define how each\n#' value should be drawn. Any ggplot2 aesthetics can be used as the arguments.\n#'\n#' @inheritParams ggplot2::layer\n#' @inheritParams ggplot2::geom_point\n#' @section Life cycle:\n#' We're unsure whether this function is truly necessary, which is why it is\n#' marked as questioning. So far, we've found that [`geom_subrect()`] and\n#' [`geom_subtile()`] handle most use cases effectively.\n#'\n#' @aesthetics GeomGshape\n#' @examples\n#' library(grid)\n#' ggplot(data.frame(value = letters[seq_len(5)], y = seq_len(5))) +\n#' geom_gshape(aes(x = 1, y = y, gshape = value, fill = value)) +\n#' scale_gshape_manual(values = list(\n#' a = function(x, y, width, height, fill) {\n#' rectGrob(x, y,\n#' width = width, height = height,\n#' gp = gpar(fill = fill),\n#' default.units = \"native\"\n#' )\n#' },\n#' b = function(x, y, width, height, fill) {\n#' rectGrob(x, y,\n#' width = width, height = height,\n#' gp = gpar(fill = fill),\n#' default.units = \"native\"\n#' )\n#' },\n#' c = function(x, y, width, height, fill) {\n#' rectGrob(x, y,\n#' width = width, height = height,\n#' gp = gpar(fill = fill),\n#' default.units = \"native\"\n#' )\n#' },\n#' d = function(x, y, width, height, shape) {\n#' gList(\n#' pointsGrob(x, y, pch = shape),\n#' # To ensure the rectangle color is shown in the legends, you\n#' # must explicitly provide a color argument and include it in\n#' # the `gpar()` of the graphical object\n#' rectGrob(x, y, width, height,\n#' gp = gpar(col = \"black\", fill = NA)\n#' )\n#' )\n#' },\n#' e = function(xmin, xmax, ymin, ymax) {\n#' segmentsGrob(\n#' xmin, ymin,\n#' xmax, ymax,\n#' gp = gpar(lwd = 2)\n#' )\n#' }\n#' )) +\n#' scale_fill_brewer(palette = \"Dark2\") +\n#' theme_void()\n#'\n#' @importFrom rlang list2\n#' @export\ngeom_gshape <- function(mapping = NULL, data = NULL, stat = \"identity\",\n position = \"identity\", ..., na.rm = FALSE,\n show.legend = NA, inherit.aes = TRUE) {\n dots <- list2(...)\n ggplot2::layer(\n data = data,\n mapping = mapping,\n stat = stat,\n geom = GeomGshape,\n position = position,\n show.legend = show.legend,\n inherit.aes = inherit.aes,\n params = c(list(na.rm = na.rm), dots, list(.__gshape_dots__ = dots))\n )\n}\n\n#' @inherit ggplot2::draw_key_point\n#' @description\n#' Each geom has an associated function that draws the key when the geom needs\n#' to be displayed in a legend. These functions are called `draw_key_*()`, where\n#' `*` stands for the name of the respective key glyph. The key glyphs can be\n#' customized for individual geoms by providing a geom with the `key_glyph`\n#' argument. The `draw_key_gshape` function provides this interface for custom\n#' key glyphs used with [`geom_gshape()`].\n#'\n#' @importFrom rlang inject\n#' @importFrom methods formalArgs\n#' @importFrom grid gTree\n#' @export\ndraw_key_gshape <- function(data, params, size) {\n gshape <- .subset2(data$gshape, 1L)\n data$gshape <- NULL\n if (is.function(gshape)) {\n for (d in formalArgs(gshape)) {\n if (is.null(.subset2(data, d))) {\n data[[d]] <- switch(d,\n x = ,\n y = 0.5,\n xmin = ,\n ymin = 0,\n xmax = ,\n ymax = 1,\n width = ,\n height = 1,\n color = data$colour %||% GeomGshape$default_aes[[\"colour\"]],\n fill = data$colour %||% GeomGshape$default_aes[[\"fill\"]],\n GeomGshape$default_aes[[d]]\n )\n }\n }\n }\n make_draw_grob(gshape, data, .subset2(params, \".__gshape_dots__\"))\n}\n\n#' @importFrom ggplot2 ggproto zeroGrob\n#' @importFrom rlang inject\n#' @importFrom grid gList\nGeomGshape <- ggproto(\n \"GeomGshape\",\n ggplot2::Geom,\n required_aes = c(\"x\", \"y\", \"gshape\"),\n default_aes = aes(\n shape = 19,\n colour = \"black\",\n size = 1.5,\n fill = NA,\n alpha = NA,\n stroke = 0.5,\n linewidth = 0.5,\n linetype = 1\n ),\n setup_data = ggplot2::GeomTile$setup_data,\n draw_panel = function(data, panel_params, coord, .__gshape_dots__) {\n coords <- coord$transform(data, panel_params)\n\n if (!is.null(coords$colour) && is.null(coords$color)) {\n coords$color <- coords$colour\n }\n if (!is.null(coords$color) && is.null(coords$colour)) {\n coords$colour <- coords$color\n }\n\n # restore width and height\n if (!is.null(coords$xmin) && !is.null(coords$xmax)) {\n coords$width <- coords$xmax - coords$xmin\n }\n if (!is.null(coords$ymin) && !is.null(coords$ymax)) {\n coords$height <- coords$ymax - coords$ymin\n }\n\n groups <- vec_group_loc(.subset2(coords, \"gshape\"))\n coords$gshape <- NULL\n\n # reordering by drawing order\n ordering <- vapply(\n .subset2(groups, \"key\"),\n function(gshape) {\n attr(gshape, \"gshape_ordering\", exact = TRUE) %||% NA_integer_\n },\n integer(1L),\n USE.NAMES = FALSE\n )\n groups <- vec_slice(groups, order(ordering))\n coords <- vec_chop(coords, indices = .subset2(groups, \"loc\"))\n\n grobs <- .mapply(\n make_draw_grob,\n list(draw = .subset2(groups, \"key\"), data = coords),\n list(dots = .__gshape_dots__)\n )\n grobs <- grobs[vapply(grobs, is.grob, logical(1L), USE.NAMES = FALSE)]\n if (is_empty(grobs)) {\n zeroGrob()\n } else {\n gTree(children = inject(gList(!!!grobs)))\n }\n },\n draw_key = draw_key_gshape\n)\n\n#' Scale for `gshape` aesthetic\n#'\n#' @inheritDotParams ggplot2::discrete_scale -expand -position -aesthetics -palette -scale_name\n#' @param values A list of grobs or functions (including purrr-like lambda\n#' syntax) that define how each cell's grob (graphical object) should be drawn.\n#' @inheritParams ggplot2::scale_discrete_manual\n#' @inherit geom_gshape\n#' @export\nscale_gshape_manual <- function(..., values, breaks = waiver(), na.value = NA) {\n ggplot2::scale_discrete_manual(\n aesthetics = \"gshape\",\n values = .mapply(function(f, i) {\n f <- allow_lambda(f)\n attr(f, \"gshape_ordering\") <- i # save the drawing order\n f\n }, list(values, seq_along(values)), NULL),\n breaks = breaks,\n na.value = na.value,\n ...\n )\n}\n\n# `gshape` should be provided manually\nscale_gshape_discrete <- function(name = waiver(), ...) {\n cli_abort(paste(\n \"You must provide {.fn scale_gshape_manual}\",\n \"to use {.field draw} aesthetic\"\n ))\n}\n\n# `gshape` should be provided manually\nscale_gshape_continuous <- scale_gshape_discrete\n"], ["/ggalign/R/with_quad.R", "#' Modify operated Context in `quad_layout()`\n#'\n#' @description\n#' `r lifecycle::badge('experimental')`\n#'\n#' The `with_quad()` function modifies the application context of elements in\n#' `ggheatmap()`/`quad_layout()`. It controls how objects like themes, scales,\n#' or other plot modifications apply to specific annotation stacks or the main\n#' plot without altering the currently active layout or plot.\n#'\n#' @param x An object which can be added to the ggplot, including\n#' **schemes**. See [`scheme_align()`], [`scheme_data()`], and\n#' [`scheme_theme()`]\n#' @param position A string specifying one or more positions-\n#' `r oxford_and(.tlbr)`- to indicate the annotation stack context for `x`. If\n#' `NULL`, will change the operated context to the `quad_layout()` itself. For\n#' default behaivours, see `details` section.\n#' @param main A single boolean value indicating whether `x` should apply to the\n#' main plot, used only when `position` is not `NULL`. By default, if `position`\n#' is `waiver()` and the active context of `quad_layout()` is an annotation\n#' stack or the active context of `stack_layout()` is itself, `main` will be set\n#' to `TRUE`; otherwise, it defaults to `FALSE`.\n#' @return The original object with an added attribute that sets the specified\n#' context.\n#' @details\n#' Default Behavior when adding object wrapped with `with_quad()`:\n#'\n#' For `quad_layout()` object:\n#'\n#' - When `ggheatmap()`/`quad_layout()` has no active annotation stack, objects\n#' added via `+` or `-` operate normally without `with_quad()`.\n#' - When the active annotation stack is set, `with_quad()` ensures the applied\n#' object also modifies:\n#' * The main plot (by default).\n#' * Opposite annotation stacks when using `-`.\n#'\n#' For `stack_layout()` object:\n#'\n#' - When the active layout is the `stack_layout()` itself:\n#' * `-` operator will apply changes to all plots along the\n#' `stack_layout()`, which means if the stack layout is in `horizontal`,\n#' `-` operator will also add the element to the `left` and `right`\n#' annotation, if the stack layout is in `vertical`, `-` operator will\n#' also add element to the `top` and `bottom` annotation.\n#' * `+` operator won't do anything special.\n#' - When the active layout is the nested `ggheatmap()`/`quad_layout()`, the\n#' `+`/`-` operator applies the elements to this nested layout, following the\n#' same principles as for `ggheatmap()`/`quad_layout()`.\n#'\n#' @examples\n#' set.seed(123)\n#' small_mat <- matrix(rnorm(56), nrow = 7)\n#'\n#' # By wrapping object with `with_quad()`, the `+` operator will apply the\n#' # object not only to the active plot in the annotation stack, but also to\n#' # the main plot unless specified by `main` argument otherwise.\n#' ggheatmap(small_mat) +\n#' # initialize the left annotation\n#' anno_left(size = 0.2) +\n#' align_dendro() +\n#' # apply the object not only to the active plot in the annotation stack,\n#' # but also to the main plot\n#' with_quad(theme(plot.background = element_rect(fill = \"red\")))\n#'\n#' # the `-` operator will apply changes not only to the active annotation\n#' # stack but also to the opposite one (i.e., bottom if top is active, and\n#' # vice versa). The same principle applies to the left and right annotation.\n#' ggheatmap(small_mat) +\n#' anno_left(size = 0.2) +\n#' align_dendro(aes(color = branch), k = 3L) +\n#' # Change the active layout to the left annotation\n#' anno_top(size = 0.2) +\n#' align_dendro(aes(color = branch), k = 3L) +\n#' anno_bottom(size = 0.2) +\n#' align_dendro(aes(color = branch), k = 3L) -\n#' # Modify the color scale of all plots in the bottom and the opposite\n#' # annotation, in this way, the `main` argument by default would be `TRUE`\n#' with_quad(scale_color_brewer(palette = \"Dark2\", name = \"Top and bottom\"))\n#'\n#' # When the `position` argument is manually set, the\n#' # default value of the `main` argument will be `FALSE`.\n#' ggheatmap(small_mat) +\n#' anno_left(size = 0.2) +\n#' align_dendro(aes(color = branch), k = 3L) +\n#' anno_top(size = 0.2) +\n#' align_dendro(aes(color = branch), k = 3L) +\n#' anno_bottom(size = 0.2) +\n#' align_dendro(aes(color = branch), k = 3L) -\n#' # Modify the background of all plots in the left and top annotation\n#' with_quad(theme(plot.background = element_rect(fill = \"red\")), \"tl\")\n#' @export\nwith_quad <- function(x, position = waiver(), main = NULL) {\n UseMethod(\"with_quad\")\n}\n\n#' @export\nwith_quad.default <- function(x, position = waiver(), main = NULL) {\n assert_layout_position(position)\n assert_bool(main, allow_null = TRUE)\n structure(\n list(\n object = x,\n object_name = paste(deparse(substitute(x)), collapse = \" \"),\n position = position, main = main\n ),\n class = \"ggalign_with_quad\"\n )\n}\n\n#' @export\nprint.ggalign_with_quad <- function(x, ...) {\n print(.subset2(x, \"object\"))\n invisible(x)\n}\n\n#' @export\nwith_quad.CraftBox <- function(x, position = waiver(), main = NULL) {\n cli_abort(sprintf(\"Cannot used with %s\", object_name(x)))\n}\n\n#' @export\nwith_quad.layout_title <- function(x, position = waiver(), main = NULL) {\n cli_abort(\"Cannot used with {.obj_type_friendly {x}}\")\n}\n\n#' @export\nwith_quad.layout_theme <- with_quad.layout_title\n\n#' @export\nwith_quad.layout_annotation <- with_quad.layout_title\n\n#' @export\nwith_quad.quad_active <- with_quad.layout_title\n\n#' @export\nwith_quad.quad_anno <- with_quad.layout_title\n\n#' @export\nwith_quad.stack_switch <- with_quad.layout_title\n\nquad_operated_context <- function(with, active, operator) {\n if (is.waive(ans <- .subset2(with, \"position\"))) {\n if (operator == \"-\") {\n # if wrap with `with_quad`\n # we determine the `context` from current actual active position\n if (is.null(active)) {\n ans <- NULL\n } else {\n ans <- c(active, opposite_pos(active))\n if (is.null(main <- .subset2(with, \"main\")) || main) {\n ans <- c(ans, list(NULL))\n }\n }\n } else if (operator == \"+\") {\n ans <- active\n if (!is.null(ans)) {\n if (is.null(main <- .subset2(with, \"main\")) || main) {\n ans <- c(ans, list(NULL))\n }\n }\n } else {\n cli_abort(\"Not implement for {operator}\")\n }\n } else if (!is.null(ans)) { # if set manually\n ans <- setup_pos(ans)\n if (!is.null(main <- .subset2(with, \"main\")) && main) {\n ans <- c(ans, list(NULL))\n }\n }\n ans\n}\n\n#' @importFrom ggplot2 ggplot_add\n#' @export\nggplot_add.ggalign_with_quad <- function(object, plot, object_name, ...) {\n object <- .subset2(object, \"object\")\n object_name <- .subset2(object, \"object_name\")\n ggplot_add(object, plot, object_name)\n}\n"], ["/ggalign/R/pair-links.R", "#' Helper function to create pairs of observation groups\n#'\n#' @description\n#' [`ggmark()`] and [`cross_link()`] allow users to add links between\n#' observations. These functions help define the linked observations. The\n#' selected pairs will either be linked together, or each group in the pair will\n#' be linked separately to the same plot area.\n#'\n#' - `pair_links`: Helper function to create pairs of observation groups.\n#' - `range_link`: Helper function to create a range of observations.\n#'\n#' @param ... <[dyn-dots][rlang::dyn-dots]> A list of formulas, where each side\n#' of the formula should be an `integer` or `character` index of the original\n#' data, or a `range_link()` object defining the linked observations. Use\n#' `NULL` to indicate no link on that side. You can also combine these by\n#' wrapping them into a single `list()`. If only the left-hand side of the\n#' formula exists, you can input it directly. For integer indices, wrap them\n#' with [`I()`] to use the ordering from the layout. You can also use\n#' [`waiver()`][ggplot2::waiver()] to inherit values from the other group.\n#' @param .handle_missing A string of `r oxford_or(c(\"error\", \"remove\"))`\n#' indicates the action for handling missing observations.\n#' @param .reorder A string of `r oxford_or(c(\"hand1\", \"hand2\"))` indicating\n#' whether to reorder the input links to follow the specified layout ordering.\n#' @examples\n#' x <- pair_links(\n#' # group on the left hand only\n#' c(\"a\", \"b\"),\n#' # normally, integer index will be interpreted as the index of the\n#' # origianl data\n#' 1:2,\n#' # wrapped with `I()` indicate` the integer index is ordering of the\n#' # layout\n#' I(1:2),\n#' range_link(1, 6),\n#' range_link(\"a\", \"b\"),\n#' # group on the right hand only\n#' ~ 1:2,\n#' ~ c(\"a\", \"b\"),\n#' ~ range_link(1, 6),\n#' # group on the both side\n#' range_link(1, 6) ~ c(\"a\", \"b\"),\n#' # waiver() indicates the right hand is the same of the left hand\n#' range_link(1, 6) ~ waiver(),\n#' # the same for the left hand\n#' waiver() ~ 1:2,\n#' ~NULL # an empty link\n#' )\n#' x\n#'\n#' # we can modify it as usual list\n#' x[[1]] <- NULL # remove the first link\n#' x$a <- ~LETTERS\n#' x\n#'\n#' # modify with a list\n#' x[1:2] <- list(~ c(\"a\", \"b\"), ~ range_link(\"a\", \"b\"))\n#' x\n#' @export\npair_links <- function(..., .handle_missing = \"error\", .reorder = NULL) {\n .handle_missing <- arg_match0(.handle_missing, c(\"error\", \"remove\"))\n if (!is.null(.reorder)) {\n .reorder <- arg_match0(.reorder, c(\"hand1\", \"hand2\"))\n }\n pairs <- rlang::dots_list(..., .ignore_empty = \"all\", .named = NULL)\n new_pair_links(\n lapply(pairs, as_pair_link, x_arg = \"...\", call = current_call()),\n handle_missing = .handle_missing, reorder = .reorder\n )\n}\n\nnew_pair_links <- function(x = list(), ..., class = character()) {\n new_vctr(x, ..., class = c(class, \"ggalign_pair_links\"))\n}\n\n#' @export\nobj_print_header.ggalign_pair_links <- function(x, ...) {\n cat(\"<\", vec_ptype_full(x), \">\", \"\\n\", sep = \"\")\n cat(\n sprintf(\n \"A total of %d pair%s of link groups\",\n vec_size(x), if (vec_size(x) > 1L) \"s\" else \"\"\n ),\n \"\\n\",\n sep = \"\"\n )\n invisible(x)\n}\n\n#' @export\nobj_print_data.ggalign_pair_links <- function(x, ...) {\n if (vec_size(x) > 0L) {\n hand1 <- vapply(x, function(hand) {\n deparse_link(hand, ..., hand = \"hand1\")\n }, character(1L), USE.NAMES = FALSE)\n hand2 <- vapply(x, function(hand) {\n deparse_link(hand, ..., hand = \"hand2\")\n }, character(1L), USE.NAMES = FALSE)\n nms <- c(\"\", paste0(names_or_index(x), \": \"))\n nms <- format(nms, justify = \"right\")\n empty <- character(vec_size(hand2))\n empty[hand1 == \"\" & hand2 == \"\"] <- \" \"\n empty <- format(c(\"\", empty), justify = \"left\")\n hand1 <- format(c(\"hand1\", hand1), justify = \"right\")\n hand2 <- format(c(\"hand2\", hand2), justify = \"left\")\n cat(\"\\n\")\n cat(paste0(\" \", nms, hand1, \" ~ \", hand2, empty), sep = \"\\n\")\n cat(\"\\n\")\n }\n invisible(x)\n}\n\n#' @export\nobj_print_footer.ggalign_pair_links <- function(x, ...) {\n NextMethod()\n # `lengths`: will call `length.ggalign_pair_link()` method\n n <- sum(lengths(x, use.names = FALSE))\n cat(\n sprintf(\n \"A total of %d link group%s\", n,\n if (n > 1L) \"s\" else \"\"\n ),\n \"\\n\",\n sep = \"\"\n )\n invisible(x)\n}\n\n#' @export\n`[<-.ggalign_pair_links` <- function(x, i, value) {\n value <- lapply(value, as_pair_link, x_arg = \"value\", call = current_call())\n NextMethod()\n}\n\n#' @export\n`[[<-.ggalign_pair_links` <- function(x, i, value) {\n # let `NULL` to remove the link\n if (!is.null(value)) value <- as_pair_link(value)\n NextMethod()\n}\n\n#' @export\n`$<-.ggalign_pair_links` <- function(x, i, value) {\n # let `NULL` to remove the link\n if (!is.null(value)) value <- as_pair_link(value)\n NextMethod()\n}\n\n#' @export\nvec_ptype2.ggalign_pair_links.list <- function(x, y, ...) {\n x\n}\n\n#' @export\nvec_ptype2.list.ggalign_pair_links <- function(x, y, ...) {\n y\n}\n\n#' @export\nvec_cast.ggalign_pair_links.list <- function(x, to, ...,\n x_arg = caller_arg(x),\n to_arg = \"\",\n call = caller_env()) {\n new_pair_links(lapply(x, as_pair_link, x_arg = x_arg, call = call))\n}\n\n#########################################################\n#' @param point1,point2 A single integer or character index, defining the lower\n#' and higher bounds of the range. For integer indices, wrap them with [`I()`]\n#' to indicate the ordered index by the layout.\n#' @export\n#' @rdname pair_links\nrange_link <- function(point1, point2) {\n if (!is_scalar(point1) ||\n (!is.character(point1) && !is.numeric(point1))) {\n cli_abort(\"{.arg point1} must be a single numeric or character index\")\n }\n if (!is_scalar(point2) ||\n (!is.character(point2) && !is.numeric(point2))) {\n cli_abort(\"{.arg point2} must be a single numeric or character index\")\n }\n point1 <- as_obs_link(point1)\n point2 <- as_obs_link(point2)\n structure(list(point1 = point1, point2 = point2),\n class = \"ggalign_range_link\"\n )\n}\n\nis_range_link <- function(x) inherits(x, \"ggalign_range_link\")\n\n########################################################\nnew_pair_link <- function(hand1 = NULL, hand2 = NULL,\n ..., class = character()) {\n structure(\n .Data = list(hand1 = hand1, hand2 = hand2),\n ...,\n class = c(class, \"ggalign_pair_link\")\n )\n}\n\n#' @export\nvec_proxy.ggalign_pair_link <- function(x, ...) x\n\n#' @export\nprint.ggalign_pair_link <- function(x, ...) obj_print(x, ...)\n\n#' @export\nobj_print_header.ggalign_pair_link <- function(x, ...) {\n cat(sprintf(\"<%s>\", vec_ptype_full(x)), \"\\n\", sep = \"\")\n invisible(x)\n}\n\n#' @export\nobj_print_data.ggalign_pair_link <- function(x, ...) {\n if (length(x) > 0L) {\n cat(c(\n sprintf(\" hand1: %s\", deparse_link(.subset2(x, \"hand1\"), ...)),\n sprintf(\" hand2: %s\", deparse_link(.subset2(x, \"hand2\"), ...))\n ), sep = \"\\n\")\n }\n invisible(x)\n}\n\n#' @param x A `ggalign_pair_link` object.\n#' @noRd\n#' @export\nlength.ggalign_pair_link <- function(x) {\n sum(!vapply(x, is.null, logical(1L), USE.NAMES = FALSE))\n}\n\n##################################################\n#' @export\nvec_ptype2.ggalign_pair_link.ggalign_pair_link <- function(x, y, ...) {\n x\n}\n\n#' @export\nvec_ptype2.ggalign_pair_link.NULL <- function(x, y, ...) {\n x\n}\n\n#' @export\nvec_ptype2.NULL.ggalign_pair_link <- function(x, y, ...) {\n y\n}\n\n#' @export\nvec_ptype2.ggalign_pair_link.numeric <- function(x, y, ...) {\n x\n}\n\n#' @export\nvec_ptype2.numeric.ggalign_pair_link <- function(x, y, ...) {\n y\n}\n\n#' @export\nvec_ptype2.ggalign_pair_link.integer <- function(x, y, ...) {\n x\n}\n\n#' @export\nvec_ptype2.integer.ggalign_pair_link <- function(x, y, ...) {\n y\n}\n\n#' @export\nvec_ptype2.ggalign_pair_link.double <- function(x, y, ...) {\n x\n}\n\n#' @export\nvec_ptype2.double.ggalign_pair_link <- function(x, y, ...) {\n y\n}\n\n#' @export\nvec_ptype2.ggalign_pair_link.character <- function(x, y, ...) {\n x\n}\n\n#' @export\nvec_ptype2.character.ggalign_pair_link <- function(x, y, ...) {\n y\n}\n\n#' @export\nvec_ptype2.ggalign_pair_link.formula <- function(x, y, ...) {\n x\n}\n\n#' @export\nvec_ptype2.formula.ggalign_pair_link <- function(x, y, ...) {\n y\n}\n\n#' @export\nvec_ptype2.ggalign_pair_link.waiver <- function(x, y, ...) {\n x\n}\n\n#' @export\nvec_ptype2.waiver.ggalign_pair_link <- function(x, y, ...) {\n y\n}\n\n#' @export\nvec_ptype2.ggalign_pair_link.ggalign_range_link <- function(x, y, ...) {\n x\n}\n\n#' @export\nvec_ptype2.ggalign_range_link.ggalign_pair_link <- function(x, y, ...) {\n y\n}\n\n#' @export\nvec_ptype2.ggalign_pair_link.AsIs <- function(x, y, ...) {\n vec_ptype2(x, remove_class(y, \"AsIs\"), ...)\n}\n\n#' @export\nvec_ptype2.AsIs.ggalign_pair_link <- function(x, y, ...) {\n vec_ptype2(remove_class(x, \"AsIs\"), y, ...)\n}\n\n#' @export\nvec_ptype2.ggalign_pair_link.list <- function(x, y, ...) {\n x\n}\n\n#' @export\nvec_ptype2.list.ggalign_pair_link <- function(x, y, ...) {\n y\n}\n\n#############################################################\n#' @export\nvec_cast.ggalign_pair_link.numeric <- function(x, to, ...,\n x_arg = caller_arg(x),\n to_arg = \"\",\n call = caller_env()) {\n new_pair_link(as_obs_link(x, arg = x_arg, call = call))\n}\n\n#' @export\nvec_cast.ggalign_pair_link.double <- vec_cast.ggalign_pair_link.numeric\n\n#' @export\nvec_cast.ggalign_pair_link.integer <- vec_cast.ggalign_pair_link.numeric\n\n#' @export\nvec_cast.ggalign_pair_link.character <- vec_cast.ggalign_pair_link.numeric\n\n#' @export\nvec_cast.ggalign_pair_link.ggalign_range_link <-\n vec_cast.ggalign_pair_link.integer\n\n#' @export\nvec_cast.ggalign_pair_link.list <- vec_cast.ggalign_pair_link.numeric\n\n#' @export\nvec_cast.ggalign_pair_link.AsIs <- function(x, to, ...,\n x_arg = caller_arg(x),\n to_arg = \"\",\n call = caller_env()) {\n I(vec_cast(\n remove_class(x, \"AsIs\"),\n to = to, ...,\n x_arg = x_arg, call = call\n ))\n}\n\n#' @export\nvec_cast.ggalign_pair_link.formula <- function(x, to, ...,\n x_arg = caller_arg(x),\n to_arg = \"\",\n call = caller_env()) {\n hand1 <- rlang::eval_tidy(rlang::f_lhs(x), env = rlang::f_env(x))\n hand1 <- as_obs_link(hand1, arg = x_arg, call = call)\n hand2 <- rlang::eval_tidy(rlang::f_rhs(x), env = rlang::f_env(x))\n hand2 <- as_obs_link(hand2, arg = x_arg, call = call)\n new_pair_link(hand1, hand2)\n}\n\nas_pair_link <- function(x, ...) {\n if (is.null(x)) { # vec_cast() cannot convert `NULL`\n new_pair_link()\n } else {\n vec_cast(x, to = new_pair_link(), ...)\n }\n}\n\n########################################################\nas_obs_link <- function(x, ..., arg = caller_arg(x), call = caller_env()) {\n UseMethod(\"as_obs_link\")\n}\n\n#' @export\nas_obs_link.NULL <- function(x, ...) x\n\n#' @export\nas_obs_link.AsIs <- function(x, ...) {\n I(as_obs_link(remove_class(x, \"AsIs\"), ...))\n}\n\n#' @export\nas_obs_link.numeric <- function(x, ..., arg = caller_arg(x),\n call = caller_env()) {\n vec_cast(x, integer(), x_arg = arg, call = call)\n}\n\n#' @export\nas_obs_link.integer <- as_obs_link.NULL\n\n#' @export\nas_obs_link.double <- as_obs_link.numeric\n\n#' @export\nas_obs_link.character <- function(x, ..., arg = caller_arg(x),\n call = caller_env()) {\n if (any(x == \"\")) {\n cli_abort(\"empty string is not allowed\", call = call)\n }\n x\n}\n\n#' @export\nas_obs_link.waiver <- as_obs_link.NULL\n\n#' @export\nas_obs_link.list <- function(x, ..., arg = caller_arg(x),\n call = caller_env()) {\n x <- x[!vapply(x, is.null, logical(1L), USE.NAMES = FALSE)]\n if (is_empty(x)) return(NULL) # styler: off\n lapply(x, as_obs_link, arg = arg, call = call)\n}\n\n#' @export\nas_obs_link.ggalign_range_link <- as_obs_link.NULL\n\n#' @export\nas_obs_link.default <- function(x, ..., arg = caller_arg(x),\n call = caller_env()) {\n stop_incompatible_cast(\n x, new_pair_link(),\n x_arg = arg, to_arg = \"\",\n call = call\n )\n}\n\n#' @export\nprint.ggalign_range_link <- function(x, ...) {\n cat(deparse_link(x))\n invisible(x)\n}\n\n###########################################################\n#' @return A single string\n#' @noRd\ndeparse_link <- function(x, ...) deparse_link2(x, ...) %||% \"\"\n\n#' @return A single string or `NULL`\n#' @noRd\ndeparse_link2 <- function(x, ...) UseMethod(\"deparse_link2\")\n\n# Basic object\n#' @export\ndeparse_link2.integer <- function(x, trunc = 3L, head = trunc - 1L,\n tail = 1L, ...) {\n l <- length(x)\n ans <- paste(\n deparse(x, control = c(\"keepNA\", \"niceNames\", \"showAttributes\")),\n collapse = \" \"\n )\n if (l > trunc && startsWith(ans, \"c\")) {\n ans <- sprintf(\"c(%s)\", paste(c(\n x[seq_len(head)], \"...\", x[seq.int(l - tail + 1L, l)]\n ), collapse = \", \"))\n }\n ans\n}\n\n#' @export\ndeparse_link2.character <- function(x, trunc = 3L, head = trunc - 1L,\n tail = 1L, ...) {\n l <- length(x)\n if (l <= trunc) {\n ans <- paste(deparse(x), collapse = \" \")\n } else {\n ans <- sprintf(\"c(%s)\", paste(c(\n x[seq_len(head)], \"...\", x[seq.int(l - tail + 1L, l)]\n ), collapse = \", \"))\n }\n ans\n}\n\n#' @export\ndeparse_link2.waiver <- function(x, ...) \"waiver()\"\n\n#' @export\ndeparse_link2.NULL <- function(x, ...) NULL\n\n# To allow `I()` to be used to the whole formula, we must define the method for\n# this, though `ggalign_pair_link` shouldn't be considered as an observation\n#' @export\ndeparse_link2.ggalign_pair_link <- function(x, ..., hand) {\n deparse_link2(.subset2(x, hand), ...)\n}\n\n#' @export\ndeparse_link2.AsIs <- function(x, ...) {\n ans <- deparse_link2(remove_class(x, \"AsIs\"), ...)\n if (!is.null(ans)) ans <- sprintf(\"I(%s)\", ans)\n ans\n}\n\n# Recurse version\n#' @export\ndeparse_link2.ggalign_range_link <- function(x, ...) {\n sprintf(\n \"range_link(%s, %s)\",\n deparse_link(.subset2(x, \"point1\"), ...),\n deparse_link(.subset2(x, \"point2\"), ...)\n )\n}\n\n#' @export\ndeparse_link2.list <- function(x, trunc = 3L, head = trunc - 1L,\n tail = 1L, ...) {\n l <- length(x)\n if (l <= trunc) {\n ans <- vapply(x, deparse_link, character(1L), ...,\n trunc = trunc, head = head, tail = tail,\n USE.NAMES = FALSE\n )\n } else {\n ans <- c(\n vapply(x[seq_len(head)],\n deparse_link, character(1L), ...,\n trunc = trunc, head = head, tail = tail,\n USE.NAMES = FALSE\n ),\n \"...\",\n vapply(x[seq.int(l - tail + 1L, l)],\n deparse_link, character(1L), ...,\n trunc = trunc, head = head, tail = tail,\n USE.NAMES = FALSE\n )\n )\n }\n sprintf(\"list(%s)\", paste(ans, collapse = \", \"))\n}\n\n###################################################\nmake_links_data <- function(links, design1, design2,\n labels1, labels2) {\n link_index_list <- lapply(\n links, make_pair_link_index,\n design1 = design1, design2 = design2,\n labels1 = labels1, labels2 = labels2,\n handle_missing = attr(links, \"handle_missing\")\n )\n names(link_index_list) <- names_or_index(links)\n if (!is.null(reorder <- attr(links, \"reorder\"))) {\n index <- vapply(link_index_list, function(link_index) {\n if (is.null(link_index) ||\n is.null(index <- .subset2(link_index, reorder))) {\n NA_integer_\n } else {\n vec_slice(index, 1L)\n }\n }, integer(1L), USE.NAMES = FALSE)\n link_index_list <- link_index_list[order(index)]\n }\n link_index_list\n}\n\nmake_pair_link_index <- function(pair_link, design1, design2,\n labels1, labels2, handle_missing) {\n input1 <- .subset2(pair_link, 1L)\n input2 <- .subset2(pair_link, 2L)\n\n # make the data\n hand1 <- make_link_index(input1,\n design = design1, labels = labels1,\n other = input2, data_index = !inherits(pair_link, \"AsIs\"),\n handle_missing = handle_missing\n )\n hand2 <- make_link_index(input2,\n design = design2, labels = labels2,\n other = input1, data_index = !inherits(pair_link, \"AsIs\"),\n handle_missing = handle_missing\n )\n if (is.null(hand1) && is.null(hand2)) {\n return(NULL)\n }\n list(hand1 = hand1, hand2 = hand2)\n}\n\nmake_link_index <- function(link, design, labels, other, data_index,\n handle_missing, arg = caller_arg(link),\n call = caller_call()) {\n link <- link_to_location(\n link,\n n = .subset2(design, \"nobs\"),\n labels = labels,\n index = .subset2(design, \"index\"),\n other = other,\n data_index = data_index,\n handle_missing = handle_missing,\n arg = arg, call = call\n )\n if (is_empty(link)) {\n return(NULL)\n }\n # always use integer, otherwise, will cause error when drawing\n # due to loss of precision, I don't know why, it should be integer already?\n vec_unique(vec_cast(link, integer()))\n}\n\nlink_to_location <- function(x, ...) UseMethod(\"link_to_location\")\n\n#' @export\nlink_to_location.AsIs <- function(x, ..., data_index) {\n link_to_location(remove_class(x, \"AsIs\"), ..., data_index = FALSE)\n}\n\n#' @export\nlink_to_location.character <- function(x, ..., n, labels, index, handle_missing,\n arg = caller_arg(x),\n call = caller_call()) {\n if (identical(handle_missing, \"remove\") && !is.null(labels)) {\n x <- x[x %in% labels]\n }\n ans <- vec_as_location(x, n = n, names = labels, arg = arg, call = call)\n match(ans, index) # character always match the original data\n}\n\n#' @export\nlink_to_location.integer <- function(x, ..., n, index, data_index,\n handle_missing, arg = caller_arg(x),\n call = caller_call()) {\n ans <- num_as_location(x,\n n = n,\n arg = arg, call = call,\n negative = \"error\",\n zero = \"error\",\n oob = handle_missing\n )\n # integer index by default match the original data\n if (isTRUE(data_index)) match(ans, index) else ans\n}\n\n#' @export\nlink_to_location.ggalign_range_link <- function(x, ..., arg = caller_arg(x),\n call = caller_call()) {\n point1 <- link_to_location(\n .subset2(x, \"point1\"),\n ...,\n arg = \"point1\",\n call = quote(range_link())\n )\n point2 <- link_to_location(\n .subset2(x, \"point2\"),\n ...,\n arg = \"point2\",\n call = quote(range_link())\n )\n point1:point2\n}\n\n#' @export\nlink_to_location.list <- function(x, ...) {\n unlist(lapply(x, link_to_location, ...), FALSE, FALSE)\n}\n\n#' @export\nlink_to_location.waiver <- function(x, ..., other) {\n link_to_location(other %|w|% NULL, ...)\n}\n\n#' @export\nlink_to_location.NULL <- function(x, ...) NULL\n"], ["/ggalign/R/fortify-matrix-maftools.R", "#' Build a Matrix for OncoPrint\n#'\n#' @description\n#' Convert `MAF` object to a matrix:\n#' - `fortify_matrix.MAF`: Extract genomic alterations for genes.\n#' - `fortify_matrix.MAF_pathways`: Extract genomic alterations for pathways.\n#' [`tune.MAF()`] helps convert `MAF` object to a `MAF_pathways` object.\n#'\n#' @inheritParams rlang::args_dots_empty\n#' @param data A [`MAF`][maftools::read.maf] object.\n#' @param genes An atomic character defines the genes to draw.\n#' @param n_top A single number indicates how many top genes to be drawn.\n#' @param remove_empty_genes A single boolean value indicats whether to drop\n#' genes without any genomic alterations.\n#' @param remove_empty_samples A single boolean value indicats whether to drop\n#' samples without any genomic alterations.\n#' @param collapse_vars A single boolean value indicating whether to collapse\n#' multiple alterations in the same sample and gene into a single value\n#' `\"Multi_Hit\"`. Alternatively, you can provide a single string indicates the\n#' collapsed values.\n#' @param use_syn A single boolean value indicates whether to include synonymous\n#' variants when Classifies SNPs into transitions and transversions.\n#' @param missing_genes A string, either `\"error\"` or `\"remove\"`, specifying the\n#' action for handling missing genes.\n#' @inheritParams fortify_matrix\n#' @section ggalign attributes:\n#' For `fortify_matrix.MAF`:\n#' - `gene_summary`: A data frame of gene summary informations. See\n#' `maftools::getGeneSummary()` for details.\n#' - `sample_summary`: A data frame of sample summary informations. See\n#' `maftools::getSampleSummary()` for details.\n#' - `sample_anno`: A data frame of sample clinical informations. See\n#' `maftools::getClinicalData()` for details.\n#' - `variant_weights`: A data frame of variant weights. Each gene in a sample\n#' is assigned a total weight of `1`. When multiple variants occur in the\n#' same gene-sample pair, the weight for each variant reflects its proportion\n#' of the total.\n#' - `n_genes`: Total number of genes.\n#' - `n_samples`: Total number of samples.\n#' - `titv`: A list of data frame with Transitions and Transversions\n#' summary. See `maftools::titv()` for details.\n#'\n#' The levels of `Variant_Classification` will be stored in [`ggalign_lvls()`].\n#' If they do not exist, alphabetical ordering will be used.\n#'\n#' @family fortify_matrix\n#' @importFrom utils getFromNamespace\n#' @importFrom rlang is_string\n#' @export\nfortify_matrix.MAF <- function(data, ..., genes = NULL, n_top = NULL,\n remove_empty_genes = TRUE,\n remove_empty_samples = TRUE,\n collapse_vars = TRUE, use_syn = TRUE,\n missing_genes = \"error\",\n data_arg = NULL, call = NULL) {\n call <- call %||% current_call()\n rlang::check_dots_empty(call = call)\n rlang::check_installed(\n \"maftools\", \"to make alterations matrix from `MAF` object\"\n )\n # prepare arguments\n missing_genes <- arg_match0(\n missing_genes, c(\"error\", \"remove\"),\n error_call = call\n )\n if (isTRUE(collapse_vars)) {\n collapse_vars <- \"Multi_Hit\"\n } else if (isFALSE(collapse_vars)) {\n collapse_vars <- NULL\n } else if (is_string(collapse_vars)) {\n if (collapse_vars == \"\") {\n cli_abort(\"{.arg collapse_vars} cannot be an empty string\",\n call = call\n )\n }\n } else {\n cli_abort(\n paste(\n \"{.arg collapse_vars} must be a single boolean value or a string,\",\n \"but you provide {.obj_type_friendly {collapse_vars}}\"\n ),\n call = call\n )\n }\n\n getSampleSummary <- getExportedValue(\"maftools\", \"getSampleSummary\")\n getGeneSummary <- getExportedValue(\"maftools\", \"getGeneSummary\")\n getClinicalData <- getExportedValue(\"maftools\", \"getClinicalData\")\n\n # if `maftools` is installed, `data.table` must have been installed\n # No need to check if `data.table` is installed\n dcast <- getExportedValue(\"data.table\", \"dcast\")\n setDT <- getExportedValue(\"data.table\", \"setDT\")\n setDF <- getExportedValue(\"data.table\", \"setDF\")\n\n sample_summary <- new_data_frame(getSampleSummary(data))\n gene_summary <- new_data_frame(getGeneSummary(data))\n sample_anno <- new_data_frame(getClinicalData(data))\n\n titv <- getExportedValue(\"maftools\", \"titv\")\n titv <- titv(data, useSyn = use_syn, plot = FALSE)\n titv <- lapply(titv, new_data_frame)\n\n # we transform the data into a normal data frame\n data <- new_data_frame(data@data)[\n c(\"Tumor_Sample_Barcode\", \"Hugo_Symbol\", \"Variant_Classification\")\n ]\n n_genes <- vec_unique_count(.subset2(data, \"Hugo_Symbol\"))\n n_samples <- vec_unique_count(.subset2(data, \"Tumor_Sample_Barcode\"))\n\n # filter by genes --------------------------------------\n if (!is.null(genes)) {\n # reorder the gene annotation based on the provided genes\n genes <- vec_cast(genes, character())\n if (vec_any_missing(genes)) {\n cli_abort(\n \"{.arg genes} cannot contain missing values\",\n call = call\n )\n }\n if (vec_duplicate_any(genes)) {\n cli_abort(\n \"{.arg genes} cannot contain duplicated values\",\n call = call\n )\n }\n if (identical(missing_genes, \"remove\")) {\n genes <- genes[genes %in% .subset2(gene_summary, \"Hugo_Symbol\")]\n }\n if (is_empty(genes)) {\n cli_abort(\n \"No {.arg genes} remain after removing missing genes\",\n call = call\n )\n }\n gene_summary <- vec_slice(\n gene_summary,\n vec_as_location(\n genes,\n n = vec_size(gene_summary),\n names = .subset2(gene_summary, \"Hugo_Symbol\"),\n missing = \"error\"\n )\n )\n }\n genes <- .subset2(gene_summary, \"Hugo_Symbol\")\n if (!is.null(n_top)) {\n n_top <- min(n_top, vec_size(genes))\n index <- vec_slice(\n order(gene_summary$AlteredSamples, decreasing = TRUE),\n seq_len(n_top)\n )\n index <- sort(index) # don't change the order, we do only subset\n genes <- vec_slice(genes, index)\n gene_summary <- vec_slice(gene_summary, index)\n }\n data <- vec_slice(data, .subset2(data, \"Hugo_Symbol\") %in% genes)\n\n # Group variants --------------------------------------\n indices <- vec_group_loc(data[c(\"Tumor_Sample_Barcode\", \"Hugo_Symbol\")])\n vars <- .subset2(data, \"Variant_Classification\")\n lvls <- levels(vars) %||% sort(vec_unique(vars))\n nlvls <- vec_size(lvls)\n var_list <- vec_chop(as.character(vars), indices = .subset2(indices, \"loc\"))\n\n # calcualte the variant weights -----------------------\n variant_weights <- lapply(var_list, function(var) {\n o <- numeric(nlvls)\n names(o) <- lvls\n counts <- vec_count(var)\n o[.subset2(counts, \"key\")] <- .subset2(counts, \"count\") /\n sum(.subset2(counts, \"count\"))\n o\n })\n variant_weights <- inject(rbind(!!!variant_weights))\n gene_indices <- vec_group_loc(\n .subset2(.subset2(indices, \"key\"), \"Hugo_Symbol\")\n )\n variant_weights <- lapply(\n vec_chop(variant_weights, indices = .subset2(gene_indices, \"loc\")),\n colSums\n )\n variant_weights <- vec_cbind(\n Hugo_Symbol = .subset2(gene_indices, \"key\"),\n vec_rbind(!!!variant_weights)\n )\n\n # collapse the vars ------------------------------------\n if (is.null(collapse_vars)) {\n vars <- vapply(var_list, function(var) {\n if (length(var) > 1L) {\n paste(var, collapse = \";\")\n } else {\n var\n }\n }, character(1L), USE.NAMES = FALSE)\n } else {\n vars <- vapply(var_list, function(var) {\n if (vec_unique_count(var) > 1L) {\n collapse_vars\n } else if (length(var) > 1L) {\n paste(var, collapse = \";\")\n } else {\n var\n }\n }, character(1L), USE.NAMES = FALSE)\n if (any(vars == collapse_vars)) lvls <- c(lvls, collapse_vars)\n }\n ans <- vec_cbind(\n .subset2(indices, \"key\"),\n new_data_frame(list(Variant_Classification = vars))\n )\n\n # restore all samples, this will introduce `NA` in `Hugo_Symbol`\n ans <- right_join(ans, data_frame0(\n Tumor_Sample_Barcode = vec_unique(sample_summary$Tumor_Sample_Barcode)\n ))\n setDT(ans)\n ans <- dcast(ans, Hugo_Symbol ~ Tumor_Sample_Barcode,\n value.var = \"Variant_Classification\"\n )\n setDF(ans)\n ans <- vec_slice(ans, !is.na(.subset2(ans, \"Hugo_Symbol\")))\n\n # convert data into a matrix\n if (remove_empty_genes) {\n # convert to a matrix\n ans <- as.matrix(column_to_rownames(ans, \"Hugo_Symbol\"))\n\n # reorder the rows based on the `genes` specified\n index <- match(genes, rownames(ans))\n ans <- vec_slice(ans, index[!is.na(index)])\n } else {\n # restore all genes\n ans <- right_join(ans, data_frame0(Hugo_Symbol = genes))\n\n # convert to a matrix\n ans <- as.matrix(column_to_rownames(ans, \"Hugo_Symbol\"))\n\n # reorder the rows based on the `genes` specified\n ans <- vec_slice(ans, genes)\n }\n\n # filter samples when necessary\n if (remove_empty_samples) {\n keep <- colSums(!is.na(ans)) > 0L\n ans <- ans[, keep, drop = FALSE]\n }\n\n # reorder the rows based on the gene ordering\n gene_summary <- vec_slice(\n gene_summary,\n vec_as_location(\n rownames(ans),\n n = vec_size(gene_summary),\n names = vec_cast(gene_summary$Hugo_Symbol, character())\n )\n )\n variant_weights <- vec_slice(\n variant_weights,\n vec_as_location(\n rownames(ans),\n n = vec_size(variant_weights),\n names = variant_weights$Hugo_Symbol\n )\n )\n\n # reorder columns based on the sample ordering\n sample_summary <- vec_slice(\n sample_summary,\n vec_as_location(\n colnames(ans),\n n = vec_size(sample_summary),\n names = vec_cast(sample_summary$Tumor_Sample_Barcode, character())\n )\n )\n sample_anno <- vec_slice(\n sample_anno,\n vec_as_location(\n colnames(ans),\n n = vec_size(sample_anno),\n names = sample_anno$Tumor_Sample_Barcode\n )\n )\n titv <- lapply(titv, function(data) {\n data <- left_join(\n data_frame0(Tumor_Sample_Barcode = colnames(ans)),\n data\n )\n vec_slice(data, vec_as_location(\n colnames(ans),\n n = vec_size(data),\n names = vec_cast(data$Tumor_Sample_Barcode, character())\n ))\n })\n ggalign_data_set(ans,\n sample_summary = sample_summary,\n gene_summary = gene_summary,\n sample_anno = sample_anno,\n variant_weights = variant_weights,\n n_samples = n_samples, n_genes = n_genes, titv = titv,\n .lvls = lvls\n )\n}\n\n#' Convert the shape of a MAF for fortify method\n#'\n#' @param data A [`MAF`][maftools::read.maf] object.\n#' @param shape Not used currently.\n#' @seealso [`fortify_matrix.MAF_pathways()`]\n#' @family tune\n#' @export\ntune.MAF <- function(data, shape = NULL) {\n if (!is.null(shape)) {\n cli_abort(\"{.arg shape} cannot be used currently for {.cls MAF} object\")\n }\n new_tune(data, class = \"MAF_pathways\")\n}\n\n#' @param pathdb A string of `r oxford_or(c(\"smgbp\", \"sigpw\"))`, or a named list\n#' of genes to define the pathways.\n#' @param remove_empty_pathways A single boolean value indicats whether to drop\n#' pathways without any genomic alterations.\n#' @section ggalign attributes:\n#' For `fortify_matrix.MAF_pathways`:\n#' - `gene_list`: the pathway contents.\n#' - `pathway_summary`: pathway summary informations. See\n#' `maftools::pathways()` for details.\n#' - `sample_summary`: sample summary informations. See\n#' `maftools::getSampleSummary()` for details.\n#' - `sample_anno`: sample clinical informations. See\n#' `maftools::getClinicalData()` for details.\n#' @export\n#' @rdname fortify_matrix.MAF\nfortify_matrix.MAF_pathways <- function(data, ..., pathdb = \"smgbp\",\n remove_empty_pathways = TRUE,\n remove_empty_samples = TRUE,\n data_arg = NULL,\n call = NULL) {\n call <- call %||% current_call()\n rlang::check_dots_empty(call = call)\n rlang::check_installed(\n \"maftools\", \"to make alterations matrix from `MAF` object\"\n )\n get_pw_summary <- getFromNamespace(\"get_pw_summary\", \"maftools\")\n maf <- tune_data(data)\n if (rlang::is_string(pathdb)) {\n pathdb <- arg_match0(pathdb, c(\"sigpw\", \"smgbp\"))\n pathway_summary <- get_pw_summary(maf, pathways = pathdb)\n } else if (is.data.frame(pathdb)) {\n cli_abort(\"{.arg pathdb} cannot be a data frame\", call = call)\n } else if (is.list(pathdb)) {\n if (!rlang::is_named(pathdb)) {\n cli_abort(sprintf(\n \"{.arg pathdb} must be a named list of a single string of %s\",\n oxford_or(c(\"sigpw\", \"smgbp\"))\n ), call = call)\n }\n pathdb <- data_frame0(\n Pathway = factor(\n vec_rep_each(names(pathdb), lengths(pathdb)),\n names(pathdb)\n ),\n Gene = unlist(pathdb, FALSE, FALSE)\n )\n pathdb <- vec_unique(pathdb)\n pathway_summary <- get_pw_summary(maf, pathways = pathdb)\n }\n getSampleSummary <- getExportedValue(\"maftools\", \"getSampleSummary\")\n getClinicalData <- getExportedValue(\"maftools\", \"getClinicalData\")\n sample_summary <- new_data_frame(getSampleSummary(maf))\n sample_anno <- new_data_frame(getClinicalData(maf))\n\n gene_list <- attr(pathway_summary, \"genes\") # a list of genes\n ans <- new_data_frame(maf@data)[\n c(\"Tumor_Sample_Barcode\", \"Hugo_Symbol\", \"Variant_Classification\")\n ]\n full_genes <- unlist(gene_list, FALSE, FALSE)\n ans$pathways <- vec_slice(\n vec_set_names(\n vec_rep_each(names(gene_list), lengths(gene_list)),\n full_genes\n ),\n if_else(ans$Hugo_Symbol %in% full_genes,\n ans$Hugo_Symbol, NA_character_\n )\n )\n ans$Alt <- if_else(is.na(.subset2(ans, \"pathways\")), NA_character_, \"Alt\")\n ans <- vec_unique(ans[c(\"Tumor_Sample_Barcode\", \"pathways\", \"Alt\")])\n\n # if `maftools` is installed, `data.table` must have been installed\n # No need to check if `data.table` is installed\n dcast <- getExportedValue(\"data.table\", \"dcast\")\n setDT <- getExportedValue(\"data.table\", \"setDT\")\n setDF <- getExportedValue(\"data.table\", \"setDF\")\n setDT(ans)\n ans <- dcast(ans, pathways ~ Tumor_Sample_Barcode,\n value.var = \"Alt\", fill = NA_character_\n )\n setDF(ans)\n ans <- vec_slice(ans, !is.na(.subset2(ans, \"pathways\")))\n\n # convert data into a matrix\n if (remove_empty_pathways) {\n # convert to a matrix\n ans <- as.matrix(column_to_rownames(ans, \"pathways\"))\n\n # reorder the rows based on the `pathways` specified\n index <- match(names(gene_list), rownames(ans))\n gene_list <- gene_list[!is.na(index)]\n ans <- vec_slice(ans, index[!is.na(index)])\n } else {\n # restore all pathways\n ans <- right_join(ans, data_frame0(pathways = names(gene_list)))\n\n # convert to a matrix\n ans <- as.matrix(column_to_rownames(ans, \"pathways\"))\n\n # reorder the rows based on the `pathways` specified\n ans <- vec_slice(ans, names(gene_list))\n }\n\n # filter samples when necessary\n if (remove_empty_samples) {\n keep <- colSums(!is.na(ans)) > 0L\n ans <- ans[, keep, drop = FALSE]\n }\n\n # reorder the rows based on the pathways ordering\n setDF(pathway_summary)\n pathway_summary <- vec_slice(\n pathway_summary,\n vec_as_location(\n rownames(ans),\n n = vec_size(pathway_summary),\n names = vec_cast(pathway_summary$Pathway, character())\n )\n )\n\n # reorder columns based on the sample ordering\n sample_summary <- vec_slice(\n sample_summary,\n vec_as_location(\n colnames(ans),\n n = vec_size(sample_summary),\n names = vec_cast(sample_summary$Tumor_Sample_Barcode, character())\n )\n )\n sample_anno <- vec_slice(\n sample_anno,\n vec_as_location(\n colnames(ans),\n n = vec_size(sample_anno),\n names = sample_anno$Tumor_Sample_Barcode\n )\n )\n ggalign_data_set(ans,\n gene_list = gene_list,\n pathway_summary = pathway_summary,\n sample_summary = sample_summary,\n sample_anno = sample_anno\n )\n}\n\n#' Build a matrix from a maftools object\n#'\n#' @inheritParams rlang::args_dots_empty\n#' @param data A [`GISTIC`][maftools::readGistic] object.\n#' @param n_top A single number indicates how many top bands to be drawn.\n#' @param bands An atomic character defines the bands to draw.\n#' @param ignored_bands An atomic character defines the bands to be ignored.\n#' @param sample_anno A data frame of sample clinical features to be added.\n#' @param remove_empty_samples A single boolean value indicating whether to drop\n#' samples without any genomic alterations.\n#' @inheritParams fortify_matrix\n#' @section ggalign attributes:\n#' - `sample_anno`: sample clinical informations provided in `sample_anno`.\n#' - `sample_summary`: sample copy number summary informations. See\n#' `data@@cnv.summary` for details.\n#' - `cytoband_summary`: cytoband summary informations. See\n#' `data@@cytoband.summary` for details.\n#' - `gene_summary`: gene summary informations. See\n#' `data@@gene.summary` for details.\n#' - `summary`: A data frame of summary information. See `data@@summary` for\n#' details.\n#' @family fortify_matrix\n#' @export\nfortify_matrix.GISTIC <- function(data, ..., n_top = NULL, bands = NULL,\n ignored_bands = NULL, sample_anno = NULL,\n remove_empty_samples = TRUE,\n data_arg = NULL,\n call = NULL) {\n call <- call %||% current_call()\n rlang::check_dots_empty(call = call)\n rlang::check_installed(\n \"maftools\",\n \"to make CNV matrix from `GISTIC` object\"\n )\n assert_number_whole(n_top,\n allow_null = TRUE,\n call = call\n )\n assert_character(bands,\n allow_null = TRUE,\n call = call\n )\n assert_character(ignored_bands,\n allow_null = TRUE,\n call = call\n )\n assert_s3_class(sample_anno, \"data.frame\",\n allow_null = TRUE,\n call = call\n )\n assert_bool(remove_empty_samples,\n call = call\n )\n cn_mat <- data@cnMatrix\n if (is.null(bands)) {\n bands <- rownames(cn_mat)\n } else {\n bands <- intersect(bands, rownames(cn_mat))\n }\n if (!is.null(ignored_bands)) {\n bands <- setdiff(bands, ignored_bands)\n }\n if (!is.null(bands)) {\n cn_mat <- vec_slice(cn_mat, rownames(cn_mat) %in% bands)\n }\n if (!is.null(n_top)) {\n cn_mat <- vec_slice(cn_mat, seq_len(min(n_top, nrow(cn_mat))))\n }\n if (remove_empty_samples) {\n keep <- colSums(cn_mat != \"\") > 0L\n cn_mat <- cn_mat[, keep, drop = FALSE]\n }\n if (!is.null(sample_anno)) {\n loc <- vec_locate_matches(\n colnames(cn_mat),\n .subset2(sample_anno, \"Tumor_Sample_Barcode\") %||%\n .subset2(sample_anno, 1L),\n relationship = \"one-to-one\",\n needles_arg = \"data\",\n haystack_arg = \"sample_anno\",\n error_call = call\n )\n sample_anno <- vec_slice(sample_anno, .subset2(loc, \"haystack\"))\n }\n sample_summary <- new_data_frame(data@cnv.summary)\n sample_summary <- vec_slice(\n sample_summary,\n vec_as_location(\n colnames(cn_mat),\n n = vec_size(sample_summary),\n names = vec_cast(sample_summary$Tumor_Sample_Barcode, character())\n )\n )\n gene_summary <- new_data_frame(data@gene.summary)\n cytoband_sumamry <- new_data_frame(data@cytoband.summary)\n cytoband_sumamry <- vec_slice(\n cytoband_sumamry,\n vec_as_location(\n rownames(cn_mat),\n n = vec_size(cytoband_sumamry),\n names = vec_cast(cytoband_sumamry$Unique_Name, character())\n )\n )\n ggalign_data_set(cn_mat,\n sample_anno = sample_anno,\n sample_summary = sample_summary,\n cytoband_sumamry = cytoband_sumamry,\n gene_summary = gene_summary,\n sumamry = data@summary\n )\n}\n"], ["/ggalign/R/ggplot-geom-subrect.R", "#' Subdivide Rectangles\n#'\n#' @description\n#' These geoms subdivide rectangles with shared borders into a grid. Both geoms\n#' achieve the same result but differ in how the rectangles are parameterized:\n#' - **`geom_subrect()`**: Defines rectangles using their four corners (`xmin`,\n#' `xmax`, `ymin`, `ymax`).\n#' - **`geom_subtile()`**: Defines rectangles using the center (`x`, `y`) and\n#' dimensions (`width`, `height`).\n#'\n#' @param byrow A single boolean value indicates whether we should arrange the\n#' divided rectangles in the row-major order.\n#' @param nrow,ncol A single positive integer specifying the number of rows or\n#' columns in the layout of the subdivided cell. By default, the layout\n#' dimensions are determined automatically using logic similar to\n#' [`facet_wrap()`][ggplot2::facet_wrap].\n#' @param direction `r lifecycle::badge(\"deprecated\")` A string specifying the\n#' arrangement direction:\n#' - `\"h\"`(`horizontal`): Creates a single row (one-row layout).\n#' - `\"v\"`(`vertical`): Creates a single column (one-column layout).\n#' @inheritParams ggplot2::geom_rect\n#' @inheritParams ggplot2::geom_segment\n#' @aesthetics GeomSubrect\n#' @examples\n#' # arranges by row\n#' ggplot(data.frame(value = letters[seq_len(5)])) +\n#' geom_subtile(aes(x = 1, y = 1, fill = value), byrow = TRUE)\n#'\n#' # arranges by column\n#' ggplot(data.frame(value = letters[seq_len(9)])) +\n#' geom_subtile(aes(x = 1, y = 1, fill = value))\n#'\n#' # one-row\n#' ggplot(data.frame(value = letters[seq_len(4)])) +\n#' geom_subtile(aes(x = 1, y = 1, fill = value), nrow = 1)\n#'\n#' # one-column\n#' ggplot(data.frame(value = letters[seq_len(4)])) +\n#' geom_subtile(aes(x = 1, y = 1, fill = value), ncol = 1)\n#'\n#' @importFrom rlang list2\n#' @export\ngeom_subrect <- function(mapping = NULL, data = NULL,\n stat = \"identity\", position = \"identity\",\n ...,\n byrow = FALSE, nrow = NULL, ncol = NULL,\n lineend = \"butt\", linejoin = \"mitre\",\n na.rm = FALSE, show.legend = NA, inherit.aes = TRUE,\n direction = deprecated()) {\n assert_bool(byrow)\n assert_number_whole(nrow, min = 1, allow_null = TRUE)\n assert_number_whole(ncol, min = 1, allow_null = TRUE)\n if (lifecycle::is_present(direction)) {\n lifecycle::deprecate_warn(\n \"1.0.2\",\n \"geom_subtile(direction = )\",\n details = \"Please use the `nrow`/`ncol` argument instead.\"\n )\n if (is_horizontal(direction)) {\n nrow <- 1L\n ncol <- NULL\n } else {\n nrow <- NULL\n ncol <- 1L\n }\n }\n ggplot2::layer(\n data = data,\n mapping = mapping,\n stat = stat,\n geom = GeomSubrect,\n position = position,\n show.legend = show.legend,\n inherit.aes = inherit.aes,\n params = list2(\n byrow = byrow,\n nrow = nrow,\n ncol = ncol,\n lineend = lineend,\n linejoin = linejoin,\n na.rm = na.rm,\n ...\n )\n )\n}\n\n#' @importFrom ggplot2 ggproto ggproto_parent wrap_dims\nGeomSubrect <- ggproto(\n \"GeomSubrect\",\n ggplot2::GeomRect,\n extra_params = c(ggplot2::GeomRect$extra_params, \"byrow\", \"nrow\", \"ncol\"),\n setup_data = function(self, data, params) {\n data <- ggproto_parent(ggplot2::GeomRect, self)$setup_data(data, params)\n indices <- vec_group_loc(data[c(\"xmin\", \"xmax\", \"ymin\", \"ymax\")])\n data_list <- vec_chop(data, indices = .subset2(indices, \"loc\"))\n max_n_tiles <- max(list_sizes(data_list))\n if (max_n_tiles == 1L) return(data) # styler: off\n cli_inform(paste(\n \"{.fn {snake_class(self)}} subdivide tile into a maximal\",\n \"of {max_n_tiles} rectangles\"\n ))\n nrow <- .subset2(params, \"nrow\")\n ncol <- .subset2(params, \"ncol\")\n vec_rbind(!!!lapply(data_list, function(data) {\n n <- vec_size(data)\n if (n == 1L) return(data) # styler: off\n dims <- wrap_dims(n, nrow = nrow, ncol = ncol)\n n_rows <- dims[1L]\n n_cols <- dims[2L]\n one_row <- vec_slice(data, 1L)\n width <- (one_row$xmax - one_row$xmin) / n_cols\n height <- (one_row$ymax - one_row$ymin) / n_rows\n\n if (.subset2(params, \"byrow\")) {\n # we arrange the rectangles from from left to\n # right, then from top to bottom\n data$xmin <- data$xmin +\n vec_rep(width * (seq_len(n_cols) - 1L), n_rows)[\n seq_len(n)\n ]\n data$xmax <- data$xmax -\n vec_rep(width * rev(seq_len(n_cols) - 1L), n_rows)[\n seq_len(n)\n ]\n\n data$ymin <- data$ymin +\n vec_rep_each(height * rev(seq_len(n_rows) - 1L), n_cols)[\n seq_len(n)\n ]\n data$ymax <- data$ymax -\n vec_rep_each(height * (seq_len(n_rows) - 1L), n_cols)[\n seq_len(n)\n ]\n } else {\n # we arrange the rectangles from top to bottom,\n # then from left to right\n data$xmin <- data$xmin +\n vec_rep_each(width * (seq_len(n_cols) - 1L), n_rows)[\n seq_len(n)\n ]\n data$xmax <- data$xmax -\n vec_rep_each(width * rev(seq_len(n_cols) - 1L), n_rows)[\n seq_len(n)\n ]\n\n data$ymin <- data$ymin +\n vec_rep(height * rev(seq_len(n_rows) - 1L), n_cols)[\n seq_len(n)\n ]\n data$ymax <- data$ymax -\n vec_rep(height * (seq_len(n_rows) - 1L), n_cols)[\n seq_len(n)\n ]\n }\n\n data\n }))\n }\n)\n\n#' @aesthetics GeomSubtile\n#' @importFrom rlang list2\n#' @export\n#' @rdname geom_subrect\ngeom_subtile <- function(mapping = NULL, data = NULL,\n stat = \"identity\", position = \"identity\",\n ...,\n byrow = TRUE, nrow = NULL, ncol = NULL,\n lineend = \"butt\", linejoin = \"mitre\",\n na.rm = FALSE, show.legend = NA, inherit.aes = TRUE,\n direction = deprecated()) {\n assert_bool(byrow)\n assert_number_whole(nrow, min = 1, allow_null = TRUE)\n assert_number_whole(ncol, min = 1, allow_null = TRUE)\n if (lifecycle::is_present(direction)) {\n lifecycle::deprecate_warn(\n \"1.0.2\",\n \"geom_subtile(direction = )\",\n details = \"Please use the `nrow`/`ncol` argument instead.\"\n )\n if (is_horizontal(direction)) {\n nrow <- 1L\n ncol <- NULL\n } else {\n nrow <- NULL\n ncol <- 1L\n }\n }\n ggplot2::layer(\n data = data,\n mapping = mapping,\n stat = stat,\n geom = GeomSubtile,\n position = position,\n show.legend = show.legend,\n inherit.aes = inherit.aes,\n params = list2(\n byrow = byrow,\n nrow = nrow,\n ncol = ncol,\n lineend = lineend,\n linejoin = linejoin,\n na.rm = na.rm,\n ...\n )\n )\n}\n\n#' @importFrom ggplot2 ggproto ggproto_parent\nGeomSubtile <- ggproto(\n \"GeomSubtile\",\n ggplot2::GeomTile,\n extra_params = c(ggplot2::GeomRect$extra_params, \"byrow\", \"nrow\", \"ncol\"),\n setup_data = function(self, data, params) {\n data <- ggproto_parent(ggplot2::GeomTile, self)$setup_data(data, params)\n ggproto_parent(GeomSubrect, self)$setup_data(data, params)\n }\n)\n"], ["/ggalign/R/layout-chain-circle-genomic.R", "#' Create a Circular Layout for Genomic Data\n#'\n#' `circle_genomic()` constructs a circular layout specifically for genomic\n#' data. It is a specialized variant of `circle_continuous()` that applies\n#' default axis limits and coerces the first column of each plot’s data to use\n#' chromosome (`seqname`) identifiers—matching those in the layout data—as\n#' factor levels.\n#'\n#' @param data The input data, which can be:\n#' - A `character` string (\"hg19\" or \"hg38\") to load a predefined cytoband\n#' reference.\n#' - A `data.frame` with at least three columns: `chromosome`, `start`, and\n#' `end` positions.\n#' - A genomic object convertible via `fortify_data_frame()`.\n#' @param ... Additional arguments passed to specific methods or\n#' `fortify_data_frame()`.\n#' @inheritParams circle_continuous\n#' @return A `circle_layout` object representing the genomic layout.\n#' @export\ncircle_genomic <- function(data, ..., radial = NULL,\n direction = \"outward\",\n sector_spacing = NULL,\n theme = NULL) {\n UseMethod(\"circle_genomic\")\n}\n\n#' @export\ncircle_genomic.NULL <- function(data, ...) {\n cli_abort(\"{.arg data} must be provided to initialize `circle_genomic()`\")\n}\n\n#' @export\ncircle_genomic.waiver <- circle_genomic.NULL\n\n#' @export\ncircle_genomic.character <- function(data, ...) {\n data <- arg_match0(data, c(\"hg19\", \"hg38\"))\n data <- readRDS(\n pkg_extdata(\n switch(data,\n hg19 = \"ref_cytoband_hg19.rds\",\n hg38 = \"ref_cytoband_hg38.rds\"\n ),\n mustWork = TRUE\n )\n )\n circle_genomic(data, ...)\n}\n\n#' @export\n#' @keywords internal\ncircle_genomic.data.frame <- function(data, ..., radial = NULL,\n direction = \"outward\",\n sector_spacing = NULL,\n theme = NULL) {\n rlang::check_dots_empty()\n if (ncol(data) < 3L) {\n cli_abort(\"{.arg data} must have at least 3 columns: chromosome, start, and end\")\n }\n if (anyNA(data[[1L]]) || anyNA(data[[2L]]) || anyNA(data[[3L]])) {\n cli_abort(\"Columns 1, 2, and 3 of {.arg data} must not contain missing values\")\n }\n if (!is.numeric(data[[2L]]) || !is.numeric(data[[3L]])) {\n cli_abort(\"Columns 2 and 3 of {.arg data} must be numeric (start and end positions)\")\n }\n if (any(data[[2L]] > data[[3L]])) {\n cli_abort(\"Column 2 (start) must not be greater than column 3 (end) in any row of {.arg data}\")\n }\n data[[1L]] <- as.factor(data[[1L]])\n # seqnames, start, end\n # Special considerations for `data.table`, we cannot use `data[1:2]`\n groups <- vec_split(\n data.frame(start = data[[2L]], end = data[[3L]]),\n data[[1L]]\n )\n ranges <- lapply(\n .subset2(groups, \"val\"),\n function(d) genomic_range(.subset2(d, 1L), .subset2(d, 2L))\n )\n lvls <- levels(data[[1L]])\n names(ranges) <- .subset2(groups, \"key\")\n ranges <- ranges[lvls]\n limits <- continuous_limits(!!!ranges)\n ranges <- vec_rbind(!!!ranges, .names_to = \"seqnames\")\n ranges$seqnames <- factor(ranges$seqnames, levels = lvls)\n new_circle_layout(\n data = ggalign_data_set(data, seqnames = lvls, ranges = ranges),\n design = limits,\n radial = radial, direction = direction,\n sector_spacing = sector_spacing,\n schemes = default_schemes(data), theme = theme,\n name = \"circle_genomic\"\n )\n}\n\n#' @export\ncircle_genomic.default <- function(data, ..., radial = NULL,\n direction = \"outward\",\n sector_spacing = NULL,\n theme = NULL) {\n data <- fortify_data_frame(data = data, ...)\n circle_genomic(data,\n radial = radial, direction = direction,\n sector_spacing = sector_spacing, theme = theme\n )\n}\n\ngenomic_range <- function(start, end) {\n if (length(start) == 1) return(c(start = start, end = end)) # styler: off\n ordering <- order(start)\n s <- start[ordering[1L]]\n e <- end[ordering[1L]]\n for (i in ordering[-1L]) {\n if (start[ordering[i]] - e > 1) {\n cli_abort(\"Input genomic ranges cannot contain intervals\")\n }\n e <- end[ordering[i]]\n }\n c(start = s, end = e)\n}\n\n#' @export\nchain_decorate.CircleLayout <- function(layout, plot) {\n if (!identical(layout@name, \"circle_genomic\")) {\n return(plot)\n }\n if (is.data.frame(data <- plot$data)) {\n data[[1L]] <- factor(\n data[[1L]],\n levels = ggalign_attr(layout@data, \"seqnames\")\n )\n missing <- is.na(data[[1L]])\n if (any(missing)) {\n cli_warn(\"Removing {.val {sum(missing)}} rows contain missing {.field seqnames}\")\n data <- vec_slice(data, !missing)\n }\n plot$data <- data\n }\n plot\n}\n"], ["/ggalign/R/layout-chain-operator.R", "#' @keywords internal\nchain_layout_subtract <- function(object, layout, object_name) {\n UseMethod(\"chain_layout_subtract\")\n}\n\n#' @export\nchain_layout_subtract.default <- function(object, layout, object_name) {\n if (is.null(active_index <- layout@active) ||\n is_craftbox(plot <- .subset2(layout@plot_list, active_index))) {\n layout@plot_list <- lapply(layout@plot_list, function(plot) {\n if (is_craftbox(plot)) {\n chain_plot_add(plot, object, object_name, force = FALSE)\n } else {\n plot\n }\n })\n } else {\n layout@plot_list[[active_index]] <- quad_layout_subtract(\n object, plot, object_name\n )\n }\n layout\n}\n\n# for objects can inherit from layout\n#' @export\nchain_layout_subtract.ggalign_scheme <- function(object, layout, object_name) {\n if (is.null(active_index <- layout@active) ||\n is_craftbox(plot <- .subset2(layout@plot_list, active_index))) {\n layout <- update_layout_scheme(object, layout, object_name)\n } else {\n layout@plot_list[[active_index]] <- quad_layout_subtract(\n object, plot, object_name\n )\n }\n layout\n}\n\n#' @export\nchain_layout_subtract.ggalign_with_quad <- function(object, layout,\n object_name) {\n if (!is_stack_layout(layout)) {\n cli_abort(sprintf(\n \"Cannot add {.var {object_name}} to %s\",\n object_name(layout)\n ))\n }\n if (is.null(active_index <- layout@active) ||\n is_craftbox(plot <- .subset2(layout@plot_list, active_index))) {\n inner <- .subset2(object, \"object\")\n inner_name <- .subset2(object, \"object_name\")\n\n # subtract set at layout level, if it is a plot option\n # we only apply to current active layout\n if (inherits(inner, \"ggalign_scheme\")) {\n layout <- update_layout_scheme(inner, layout, inner_name)\n return(layout)\n }\n\n # otherwise, we apply the object to all plots in the stack layout\n direction <- layout@direction\n layout@plot_list <- lapply(layout@plot_list, function(plot) {\n if (is_craftbox(plot)) {\n plot <- chain_plot_add(plot, inner, inner_name, force = FALSE)\n } else if (is.waive(.subset2(object, \"position\"))) {\n # default behaviour for object wrap with `with_quad()`\n # we add the object along the stack layout\n # if means for horizontal stack, we'll add it\n # to the left and right annotation, and the main plot\n positions <- switch_direction(\n direction,\n c(\"left\", \"right\"),\n c(\"top\", \"bottom\")\n )\n for (position in positions) {\n if (!is.null(slot(plot, position))) {\n slot(plot, position) <- chain_layout_subtract(\n inner, slot(plot, position), inner_name\n )\n }\n }\n if (is.null(main <- .subset2(object, \"main\")) || main) {\n plot <- quad_body_add(inner, plot, inner_name)\n }\n } else {\n # we respect the context setting\n plot <- quad_layout_subtract(object, plot, object_name)\n }\n plot\n })\n } else {\n layout@plot_list[[active_index]] <- quad_layout_subtract(\n object, plot, object_name\n )\n }\n layout\n}\n\n##################################################################\n#' @keywords internal\nchain_layout_and_add <- function(object, layout, object_name) {\n UseMethod(\"chain_layout_and_add\")\n}\n\n#' @export\nchain_layout_and_add.ggalign_with_quad <- function(object, layout, object_name) {\n if (!is_stack_layout(layout)) {\n cli_abort(sprintf(\n \"Cannot add {.var {object_name}} to %s\",\n object_name(layout)\n ))\n }\n object <- .subset2(object, \"object\")\n object_name <- .subset2(object, \"object_name\")\n NextMethod()\n}\n\n#' @export\nchain_layout_and_add.default <- function(object, layout, object_name) {\n layout@plot_list <- lapply(layout@plot_list, function(plot) {\n if (is_craftbox(plot)) {\n plot <- chain_plot_add(plot, object, object_name, force = FALSE)\n } else {\n plot <- quad_layout_and_add(object, plot, object_name)\n }\n plot\n })\n layout\n}\n\n#' @export\nchain_layout_and_add.theme <- function(object, layout, object_name) {\n ans <- NextMethod()\n # to align with `patchwork`, we also modify the layout theme\n # when using `&` to add the theme object.\n ans@theme <- ggfun(\"add_theme\")(ans@theme, object)\n ans\n}\n"], ["/ggalign/R/layout-operator.R", "#' Layout operator\n#'\n#' @description\n#' `r lifecycle::badge('experimental')`\n#'\n#' - `+`: Adds elements to the active plot in the active layout.\n#' - `&`: Applies elements to all plots in the layout.\n#' - `-`: Adds elements to multiple plots in the layout.\n#'\n#' @details\n#' The `+` operator is straightforward and should be used as needed.\n#'\n#' In order to reduce code repetition `ggalign` provides two operators for\n#' adding ggplot elements (geoms, themes, facets, etc.) to multiple/all plots in\n#' `r rd_layout()`: `-` and `&`.\n#'\n#' @param e1 A `r rd_layout()`.\n#' @param e2 An object to be added to the plot.\n#' @return A modified `Layout` object.\n#' @examples\n#' set.seed(123)\n#' small_mat <- matrix(rnorm(56), nrow = 7)\n#' ggheatmap(small_mat) +\n#' anno_top() +\n#' ggalign() +\n#' geom_point(aes(y = value))\n#'\n#' # `&` operator apply it to all plots\n#' ggheatmap(small_mat) +\n#' anno_top() +\n#' align_dendro() &\n#' theme(panel.border = element_rect(\n#' colour = \"red\", fill = NA, linewidth = unit(2, \"mm\")\n#' ))\n#'\n#' # If the active layout is the annotation stack, the `-` operator will only\n#' # add the elements to all plots in the active annotation stack:\n#' ggheatmap(small_mat) +\n#' anno_left(size = 0.2) +\n#' align_dendro(aes(color = branch), k = 3L) +\n#' align_dendro(aes(color = branch), k = 3L) -\n#' # Modify the the color scales of all plots in the left annotation\n#' scale_color_brewer(palette = \"Dark2\")\n#'\n#' # If the active layout is the `stack_layout()` itself, `-`\n#' # applies the elements to all plots in the layout except the nested\n#' # `ggheatmap()`/`quad_layout()`.\n#' stack_alignv(small_mat) +\n#' align_dendro() +\n#' ggtitle(\"I'm from the parent stack\") +\n#' ggheatmap() +\n#' # remove any active context\n#' stack_active() +\n#' align_dendro() +\n#' ggtitle(\"I'm from the parent stack\") -\n#' # Modify the the color scales of all plots in the stack layout except the\n#' # heatmap layout\n#' scale_color_brewer(palette = \"Dark2\") -\n#' # set the background of all plots in the stack layout except the heatmap\n#' # layout\n#' theme(plot.background = element_rect(fill = \"red\"))\n#'\n#' @name layout-operator\nNULL\n\nutils::globalVariables(\".Generic\")\n\nmethods::setMethod(\"Ops\", c(\"LayoutProto\", \"ANY\"), function(e1, e2) {\n if (missing(e2)) {\n cli_abort(c(\n \"Cannot use {.code {.Generic}} with a single argument.\",\n \"i\" = \"Did you accidentally put {.code {.Generic}} on a new line?\"\n ))\n }\n\n if (is.null(e2)) return(e1) # styler: off\n\n # Get the name of what was passed in as e2, and pass along so that it\n # can be displayed in error messages\n e2name <- deparse(substitute(e2))\n switch(.Generic, # nolint\n `+` = layout_add(e1, e2, e2name),\n `-` = layout_subtract(e1, e2, e2name),\n `&` = layout_and_add(e1, e2, e2name),\n stop_incompatible_op(.Generic, e1, e2)\n )\n})\n\n#################################################################\nlayout_add <- function(layout, object, object_name) {\n UseMethod(\"layout_add\")\n}\n\n#' @export\nlayout_add.QuadLayout <- function(layout, object, object_name) {\n quad_layout_add(object, layout, object_name)\n}\n\n#' @export\nlayout_add.ChainLayout <- function(layout, object, object_name) {\n chain_layout_add(object, layout, object_name)\n}\n\n#################################################################\nlayout_subtract <- function(layout, object, object_name) {\n UseMethod(\"layout_subtract\")\n}\n\n#' @export\nlayout_subtract.QuadLayout <- function(layout, object, object_name) {\n quad_layout_subtract(object, layout, object_name)\n}\n\n#' @export\nlayout_subtract.ChainLayout <- function(layout, object, object_name) {\n chain_layout_subtract(object, layout, object_name)\n}\n\n#################################################################\n# we use and_add suffix here, since `and` is very similar with `add`.\nlayout_and_add <- function(layout, object, object_name) {\n UseMethod(\"layout_and_add\")\n}\n\n#' @export\nlayout_and_add.QuadLayout <- function(layout, object, object_name) {\n quad_layout_and_add(object, layout, object_name)\n}\n\n#' @export\nlayout_and_add.ChainLayout <- function(layout, object, object_name) {\n chain_layout_and_add(object, layout, object_name)\n}\n\n# For objects cannot be used with `-` or `&`\n#' @include layout-quad-operator.R\n#' @include layout-chain-operator.R\nlapply(\n c(\n \"quad_layout_subtract\", \"chain_layout_subtract\",\n \"quad_layout_and_add\", \"chain_layout_and_add\"\n ),\n function(genname) {\n params <- .subset2(strsplit(genname, \"_\"), 1L)\n\n # function argument list\n pairlist <- rlang::pairlist2(object = , layout = , object_name = )\n names(pairlist) <- c(\"object\", .subset(params, 1L), \"object_name\")\n operator <- switch(.subset(params, 3L),\n subtract = \"-\",\n and = \"&\"\n )\n # styler: off\n for (class in c(\"ggplot\", \"quad_active\", \"quad_anno\", \"layout_title\",\n \"layout_theme\", \"CraftBox\", \"ChainLayout\",\n \"QuadLayout\", \"continuous_limits\")) {\n # styler: on\n registerS3method(\n genname, class,\n rlang::new_function(pairlist, substitute(\n {\n cli_abort(c(\n sprintf(\n \"Cannot add %s with {.code %s}\",\n name, operator\n ),\n i = \"Try to use {.code +} instead\"\n ))\n },\n list(\n name = switch(class,\n CraftBox = ,\n ChainLayout = ,\n QuadLayout = quote(object_name(object)),\n # for all others\n \"{.var {object_name}}\"\n ),\n operator = operator\n )\n ))\n )\n }\n }\n)\n"], ["/ggalign/R/alignpatch-title.R", "#' Add patch titles to plot borders\n#'\n#' This function extends ggplot2's title functionality, allowing you to add\n#' titles to each border of the plot: top, left, bottom, and right.\n#'\n#' @details\n#'\n#' The appearance and alignment of these patch titles can be customized using\n#' [theme()][ggplot2::theme]:\n#' - `plot.patch_title`/`plot.patch_title.*`: Controls the text appearance of\n#' patch titles. By default, `plot.patch_title` inherit from `plot.title`, and\n#' settings for each border will inherit from `plot.patch_title`, with the\n#' exception of the `angle` property, which is not inherited.\n#' - `plot.patch_title.position`/`plot.patch_title.position.*`: Determines the\n#' alignment of the patch titles. By default, `plot.patch_title.position`\n#' inherit from `plot.title.position`, and settings for each border will\n#' inherit from `plot.patch_title`. The value `\"panel\"` aligns the patch\n#' titles with the plot panels. Setting this to `\"plot\"` aligns the patch\n#' title with the entire plot (excluding margins and plot tags).\n#'\n#' @param top,left,bottom,right A string specifying the title to be added to the\n#' top, left, bottom, and right border of the plot.\n#' @return A [`labels`][ggplot2::labs] object to be added to ggplot.\n#' @examples\n#' ggplot(mtcars) +\n#' geom_point(aes(mpg, disp)) +\n#' patch_titles(\n#' top = \"I'm top patch title\",\n#' left = \"I'm left patch title\",\n#' bottom = \"I'm bottom patch title\",\n#' right = \"I'm right patch title\"\n#' )\n#' @export\n#' @importFrom ggplot2 waiver\npatch_titles <- function(top = waiver(), left = waiver(), bottom = waiver(),\n right = waiver()) {\n structure(\n list(top = top, left = left, bottom = bottom, right = right),\n class = \"ggalign_patch_labels\"\n )\n}\n\n#' @importFrom ggplot2 find_panel calc_element zeroGrob element_grob merge_element\n#' @importFrom rlang arg_match0\n#' @importFrom grid grobName\nsetup_patch_titles <- function(table, patch_titles, theme) {\n # complete_theme() will ensure `plot_title` exists\n old_text <- calc_element(\"plot.title\", theme)\n # always justification by center for patch title\n old_text$hjust <- 0.5\n if (is.null(text <- .subset2(theme, \"plot.patch_title\"))) {\n text <- old_text\n } else if (inherits(text, \"element_text\")) {\n text <- merge_element(text, old_text)\n } else {\n cli_abort(paste(\n \"Theme element {.var plot.patch_title} must be a\",\n \"{.cls element_text}.\"\n ), call = quote(theme()))\n }\n # inherit from plot.title.position, default use \"panel\"\n position <- .subset2(theme, \"plot.patch_title.position\") %||%\n .subset2(theme, \"plot.title.position\") %||% \"panel\"\n for (border in .TLBR) {\n panel_pos <- find_panel(table)\n patch_title <- .subset2(patch_titles, border)\n name <- paste(\"plot.patch_title\", border, sep = \".\")\n if (is.null(patch_title)) {\n title <- zeroGrob()\n } else {\n # set the default angle\n text$angle <- switch(border,\n top = 0L,\n left = 90L,\n bottom = 0L,\n right = -90L\n )\n # we merge the element with `plot.patch_title`\n if (is.null(el <- .subset2(theme, name))) {\n el <- text\n } else if (inherits(el, \"element_text\")) {\n el <- merge_element(el, text)\n } else {\n cli_abort(paste(\n \"Theme element {.var {name}} must have\",\n \"class {.cls element_text}.\"\n ), call = quote(theme()))\n }\n # render the patch title grob\n title <- element_grob(el, patch_title,\n margin_y = TRUE, margin_x = TRUE\n )\n title$name <- grobName(title, name)\n }\n\n name <- paste(\"plot.patch_title.position\", border, sep = \".\")\n pos <- arg_match0(\n .subset2(theme, name) %||% position,\n c(\"panel\", \"plot\"),\n arg_nm = name,\n error_call = quote(theme())\n )\n if (border == \"top\") {\n height <- grobHeight(title)\n if (pos == \"panel\") {\n l <- panel_pos$l\n r <- panel_pos$r\n } else {\n l <- 1L\n r <- ncol(table)\n }\n h <- .subset2(panel_pos, \"t\") - 4L # above original xlab\n table <- gtable_add_rows(table, height, pos = h)\n table <- gtable_add_grob(table, title,\n name = \"patch-title-top\",\n t = h + 1L, b = h + 1L, l = l, r = r,\n clip = \"off\"\n )\n } else if (border == \"left\") {\n width <- grobWidth(title)\n if (pos == \"panel\") {\n t <- panel_pos$t\n b <- panel_pos$b\n } else {\n t <- 1L\n b <- nrow(table)\n }\n v <- .subset2(panel_pos, \"l\") - 4L # left of the ylab\n table <- gtable_add_cols(table, width, pos = v)\n table <- gtable_add_grob(table, title,\n name = \"patch-title-left\",\n t = t, b = b, l = v + 1L, r = v + 1L,\n clip = \"off\"\n )\n } else if (border == \"bottom\") {\n height <- grobHeight(title)\n if (pos == \"panel\") {\n l <- panel_pos$l\n r <- panel_pos$r\n } else {\n l <- 1L\n r <- ncol(table)\n }\n h <- .subset2(panel_pos, \"b\") + 3L # below original xlab\n table <- gtable_add_rows(table, height, pos = h)\n table <- gtable_add_grob(table, title,\n name = \"patch-title-bottom\",\n t = h + 1L, b = h + 1L, l = l, r = r,\n clip = \"off\"\n )\n } else if (border == \"right\") {\n width <- grobWidth(title)\n if (pos == \"panel\") {\n t <- panel_pos$t\n b <- panel_pos$b\n } else {\n t <- 1L\n b <- nrow(table)\n }\n v <- .subset2(panel_pos, \"r\") + 3L # right of the ylab\n table <- gtable_add_cols(table, width, pos = v)\n table <- gtable_add_grob(table, title,\n name = \"patch-title-right\",\n t = t, b = b, l = v + 1L, r = v + 1L,\n clip = \"off\"\n )\n }\n }\n table\n}\n\n#' @importFrom ggplot2 ggplot_add\n#' @export\nggplot_add.ggalign_patch_labels <- function(object, plot, object_name, ...) {\n plot$ggalign_patch_labels <- update_non_waive(\n plot$ggalign_patch_labels %||% list(), object\n )\n if (!inherits(plot, \"patch_ggplot\")) {\n plot <- add_class(plot, \"patch_ggplot\")\n }\n plot\n}\n"], ["/ggalign/R/alignpatch-area.R", "# We are removing the patchwork dependency by defining our own version of\n# patchwork::area, as some desired features won't be merged (see this\n# https://github.com/thomasp85/patchwork/issues/379). Therefore, ggalign will\n# retain `alignpatch-*` scripts.\n\n#' Define the plotting areas in `align_plots`\n#'\n#' @inherit patchwork::area\n#' @details\n#' The grid that the areas are specified in reference to enumerate rows from top\n#' to bottom, and coloumns from left to right. This means that `t` and `l`\n#' should always be less or equal to `b` and `r` respectively. Instead of\n#' specifying area placement with a combination of `area()` calls, it is\n#' possible to instead pass in a single string\n#'\n#' ```\n#' areas <- c(area(1, 1, 2, 1),\n#' area(2, 3, 3, 3))\n#' ```\n#'\n#' is equivalent to\n#'\n#' ```\n#' areas < -\"A##\n#' A#B\n#' ##B\"\n#' ```\n#' @return A `ggalign_area` object.\n#' @examples\n#' p1 <- ggplot(mtcars) +\n#' geom_point(aes(mpg, disp))\n#' p2 <- ggplot(mtcars) +\n#' geom_boxplot(aes(gear, disp, group = gear))\n#' p3 <- ggplot(mtcars) +\n#' geom_bar(aes(gear)) +\n#' facet_wrap(~cyl)\n#'\n#' layout <- c(\n#' area(1, 1),\n#' area(1, 3, 3),\n#' area(3, 1, 3, 2)\n#' )\n#'\n#' # Show the layout to make sure it looks as it should\n#' plot(layout)\n#'\n#' # Apply it to a alignpatches\n#' align_plots(p1, p2, p3, design = layout)\n#' @export\narea <- function(t, l, b = t, r = l) {\n if (missing(t) || missing(l)) {\n one_area <- list(\n t = integer(0L),\n l = integer(0L),\n b = integer(0L),\n r = integer(0L)\n )\n } else {\n one_area <- df_list(\n t = vec_cast(t, integer()),\n l = vec_cast(l, integer()),\n b = vec_cast(b, integer()),\n r = vec_cast(r, integer())\n )\n if (any(.subset2(one_area, \"t\") > .subset2(one_area, \"b\"))) {\n cli_abort(\"{.arg t} must be less than {.arg b}\")\n }\n if (any(.subset2(one_area, \"l\") > .subset2(one_area, \"r\"))) {\n cli_abort(\"{.arg l} must be less than {.arg r}\")\n }\n }\n new_areas(one_area)\n}\n\n# Define a custom S3 class `ggalign_area`, without using S7 directly\n# Patchwork expects traditional S3 classes, and S7 classes are not fully\n# interoperable with patchwork layouts.\nS3_area <- S7::new_S3_class(\"ggalign_area\")\n\nnew_areas <- function(x) new_rcrd(x, class = c(\"ggalign_area\", \"patch_area\"))\n\ncreate_area <- function(ncol, nrow, byrow) {\n mat <- matrix(seq_len(ncol * nrow),\n nrow = nrow, ncol = ncol, byrow = byrow\n )\n ind <- as.vector(mat)\n ind <- match(seq_along(ind), ind)\n area(t = row(mat)[ind], l = col(mat)[ind])\n}\n\n#' @export\nobj_print_data.ggalign_area <- function(x, ...) {\n x <- vec_data(x)\n if (vec_size(x) > 0) {\n x <- vec_set_names(x, paste0(vec_seq_along(x), \": \"))\n print(x = x, ..., quote = FALSE)\n } else {\n cat(\" \", names(x), \"\\n\", sep = \" \")\n }\n}\n\n#' @export\nobj_print_footer.ggalign_area <- function(x, ...) {\n if (vec_size(x) == 0) {\n ncols <- 0\n nrows <- 0\n } else {\n ncols <- max(field(x, \"r\"))\n nrows <- max(field(x, \"b\"))\n }\n cat(\"\\n\\n\")\n}\n\n#' @export\nvec_ptype_abbr.ggalign_area <- function(x, ...) \"areas\"\n\ntrim_area <- function(area) {\n area <- vec_data(area)\n w <- min(.subset2(area, \"l\"), .subset2(area, \"r\"))\n h <- min(.subset2(area, \"t\"), .subset2(area, \"b\"))\n area$l <- .subset2(area, \"l\") - w + 1L\n area$r <- .subset2(area, \"r\") - w + 1L\n area$t <- .subset2(area, \"t\") - h + 1L\n area$b <- .subset2(area, \"b\") - h + 1L\n new_areas(area)\n}\n\nas_areas <- function(x) UseMethod(\"as_areas\")\n\n#' @export\nas_areas.default <- function(x) {\n cli_abort(\"Cannot convert {.obj_type_friendly {x}} into a design area\")\n}\n\n#' @export\nas_areas.NULL <- function(x) NULL\n\n#' @export\nas_areas.ggalign_area <- function(x) x\n\n#' @export\nas_areas.character <- function(x) {\n call <- current_call() # used for message only\n # split into rows\n x <- .subset2(strsplit(x, split = \"\\n\"), 1L)\n x <- lapply(x, trimws)\n if (identical(x[[1L]], \"\")) x[[1L]] <- NULL\n if (identical(x[[length(x)]], \"\")) x[[length(x)]] <- NULL\n x <- lapply(x, function(x) .subset2(strsplit(x, split = \"\"), 1L))\n ncols <- list_sizes(x)\n ncol <- .subset(ncols, 1L)\n if (any(ncols != ncol)) {\n cli_abort(\"character layout must be rectangular\", call = call)\n }\n row <- rep(seq_along(x), each = ncol)\n col <- rep(seq_len(ncol), length(x))\n x <- unlist(x, use.names = FALSE)\n # here, area will be reordered by the levels of `x`\n area_list <- imap(split(seq_along(x), x), function(i, name) {\n if (identical(name, \"#\")) {\n return(area())\n }\n area_rows <- range(row[i])\n area_cols <- range(col[i])\n t <- .subset(area_rows, 1L)\n l <- .subset(area_cols, 1L)\n b <- .subset(area_rows, 2L)\n r <- .subset(area_cols, 2L)\n if (!all(x[row >= t & row <= b & col >= l & col <= r] ==\n x[.subset(i, 1L)])) {\n cli_abort(\"Patch areas must be rectangular\", call = call)\n }\n new_areas(list(t = t, l = l, b = b, r = r))\n })\n vec_c(!!!vec_set_names(area_list, NULL))\n}\n\n# For area from patchwork\n#' @export\nas_areas.patch_area <- function(x) add_class(x, \"ggalign_area\")\n\n#' @importFrom grid unit\n#' @importFrom ggplot2 aes margin theme ggplot\n#' @importFrom utils packageVersion\n#' @export\nplot.ggalign_area <- function(x, ...) {\n data <- vec_data(x)\n data$l <- data$l - 0.45\n data$r <- data$r + 0.45\n data$t <- data$t - 0.45\n data$b <- data$b + 0.45\n data$name <- as.factor(vec_seq_along(x))\n b_fun <- function(lim) {\n if (lim[1] < lim[2]) {\n lim <- seq(floor(lim[1]), ceiling(lim[2]), by = 1)\n } else {\n lim <- seq(ceiling(lim[1]), floor(lim[2]), by = -1)\n }\n lim[-c(1, length(lim))]\n }\n ggplot(data) +\n ggplot2::geom_rect(aes(\n xmin = .data$l, xmax = .data$r,\n ymin = .data$t, ymax = .data$b, fill = .data$name\n ), alpha = 0.3) +\n ggplot2::scale_y_reverse(breaks = b_fun, expand = c(0, 0.04)) +\n ggplot2::scale_x_continuous(\n breaks = b_fun, expand = c(0, 0.04), position = \"top\"\n ) +\n ggplot2::labs(fill = \"Patch\") +\n ggplot2::theme_void() +\n theme(\n panel.grid.minor = if (packageVersion(\"ggplot2\") >= \"3.4.0\") {\n ggplot2::element_line(linewidth = 0.5, colour = \"grey\")\n } else {\n ggplot2::element_line(size = 0.5, colour = \"grey\")\n },\n axis.text = ggplot2::element_text(),\n axis.ticks.length = unit(3, \"mm\"),\n plot.margin = margin(10, 10, 10, 10)\n )\n}\n"], ["/ggalign/R/alignpatch-guides.R", "#' Returns a list of guide boxes collected from all plots.\n#' Each element in the list corresponds to a specific position, containing a\n#' sub-list of guide boxes, where each guide box represents a single plot.\n#' @noRd\ncollect_guides_list <- function(guides_list, empty = NULL) {\n ans <- lapply(c(.TLBR, \"inside\"), function(guide_pos) {\n guides <- lapply(guides_list, function(guides) {\n # IF no guide-box, a single `zeroGrob()` will be given\n # here, we regard each position is a `zeroGrob()`\n if (is_null_grob(guides)) return(list(guides)) # styler: off\n o <- .subset2(guides, guide_pos)\n # A guide-box should be a `zeroGrob()` or a `gtable` object\n if (maybe_guide_box(o)) {\n return(list(o))\n }\n # For other grobs, we just removed them silently\n if (is.grob(o)) {\n list(NULL)\n } else if (is.list(o)) {\n o[\n vapply(o, maybe_guide_box, # styler: off\n logical(1L), USE.NAMES = FALSE # styler: off\n )\n ]\n } else {\n list(NULL)\n }\n })\n guides <- unlist(guides, FALSE, FALSE)\n guides <- guides[\n !vapply(guides, is.null, logical(1L), USE.NAMES = FALSE)\n ]\n if (is_empty(guides)) empty else guides\n })\n names(ans) <- c(.TLBR, \"inside\")\n ans[!vapply(ans, is.null, logical(1L), USE.NAMES = FALSE)]\n}\n\n#' @param guides A list of guide-box\n#' @importFrom ggplot2 zeroGrob\n#' @importFrom gtable gtable gtable_add_grob\n#' @noRd\nassemble_guides <- function(guides, guide_pos, theme) {\n if (guide_pos == \"inside\") {\n # for `zeroGrob()`, it doesn't record the `viewport` information\n # used to identify the inside guide groups, we just removed them\n guides <- guides[\n !vapply(guides, is_null_grob, logical(1L), USE.NAMES = FALSE)\n ]\n if (is_empty(guides)) {\n guide_box <- zeroGrob()\n } else {\n positions <- justs <- vector(\"list\", length(guides))\n for (i in seq_along(guides)) {\n guide <- .subset2(guides, i)\n # for inside guides, it may contain multiple guide-box\n is_box <- grepl(\"guide-box-inside\", guide$layout$name)\n if (any(is_box)) {\n guides[[i]] <- guide$grobs[is_box]\n } else {\n guides[[i]] <- list(guide)\n }\n positions[[i]] <- lapply(guides[[i]], function(guide_box) {\n unit.c(guide_box$vp$x, guide_box$vp$y)\n })\n justs[[i]] <- lapply(guides[[i]], function(guide_box) {\n guide_box$vp$justification\n })\n }\n guides <- unlist(guides, FALSE, FALSE)\n groups <- data_frame0(\n positions = unlist(positions, FALSE, FALSE),\n justs = unlist(justs, FALSE, FALSE)\n )\n groups <- vec_group_loc(groups)\n index <- vec_seq_along(groups)\n\n # pakcage each group into a guide-box\n box_list <- vector(\"list\", vec_size(index))\n for (i in index) {\n box_list[[i]] <- assemble_box(\n guides[groups$loc[[i]]], guide_pos,\n theme = theme + theme(\n legend.position.inside = groups$key$positions[[i]],\n legend.justification.inside = groups$key$justs[[i]]\n )\n )\n }\n if (vec_size(box_list) > 1L) {\n guide_box <- gtable(unit(1L, \"npc\"), unit(1L, \"npc\"))\n guide_box <- gtable_add_grob(\n guide_box, box_list,\n t = 1L, l = 1L, clip = \"off\",\n name = paste(\"guide-box-collected-inside\", index, sep = \"-\")\n )\n } else {\n guide_box <- box_list[[1L]]\n }\n }\n } else {\n guide_box <- assemble_box(guides, guide_pos, theme = theme)\n }\n guide_box\n}\n\n#' @param guides A list of guide-box\n#' @importFrom rlang try_fetch\n#' @importFrom ggplot2 zeroGrob\n#' @noRd\nassemble_box <- function(guides, guide_pos, theme) {\n guides <- guides[\n !vapply(guides, is_null_grob, logical(1L), USE.NAMES = FALSE)\n ]\n if (is_empty(guides)) {\n zeroGrob()\n } else {\n # Remove the guide box background\n grobs <- lapply(guides, function(box) {\n box$grobs[grepl(\"guides\", box$layout$name)]\n })\n grobs <- unlist(grobs, FALSE, FALSE)\n\n # remove duplicated guides\n grobs <- collapse_guides(grobs)\n if (is_empty(grobs)) return(zeroGrob()) # styler: off\n # for every position, collect all individual guides and arrange them\n # into a guide box which will be inserted into the main gtable\n package_box <- try_fetch(\n .subset2(ggfun(\"Guides\"), \"package_box\"),\n error = function(cnd) package_box\n )\n package_box(grobs, guide_pos, theme)\n }\n}\n\n# The following code was used in earlier versions of ggplot2; \n# coverage is not calculated here.\n# nocov start\n#' @importFrom gtable gtable_add_rows gtable_add_cols\n#' @importFrom ggplot2 calc_element\n#' @importFrom grid valid.just editGrob viewport\npackage_box <- function(guides, guide_pos, theme) {\n theme <- complete_guide_theme(guide_pos, theme)\n guides <- guides_build(guides, theme)\n\n # Set the justification of the legend box\n # First value is xjust, second value is yjust\n just <- valid.just(calc_element(\"legend.justification\", theme))\n xjust <- just[1L]\n yjust <- just[2L]\n guides <- editGrob(guides,\n vp = viewport(x = xjust, y = yjust, just = c(xjust, yjust))\n )\n guides <- gtable_add_rows(guides, unit(yjust, \"null\"))\n guides <- gtable_add_rows(guides, unit(1L - yjust, \"null\"), 0L)\n guides <- gtable_add_cols(guides, unit(xjust, \"null\"), 0L)\n guides <- gtable_add_cols(guides, unit(1L - xjust, \"null\"))\n guides\n}\n\n#' @importFrom gtable gtable_width gtable_height gtable gtable_add_grob\n#' @importFrom grid editGrob heightDetails widthDetails valid.just unit.c unit\n#' @importFrom ggplot2 margin element_grob element_blank calc_element element_render\nguides_build <- function(guides, theme) {\n legend.spacing.y <- .subset2(theme, \"legend.spacing.y\")\n legend.spacing.x <- .subset2(theme, \"legend.spacing.x\")\n legend.box.margin <- calc_element(\"legend.box.margin\", theme) %||%\n margin()\n widths <- do.call(`unit.c`, lapply(guides, gtable_width))\n heights <- do.call(`unit.c`, lapply(guides, gtable_height))\n\n just <- valid.just(.subset2(theme, \"legend.box.just\"))\n xjust <- just[1]\n yjust <- just[2]\n vert <- identical(.subset2(theme, \"legend.box\"), \"horizontal\")\n guides <- lapply(guides, function(g) {\n editGrob(g, vp = viewport(\n x = xjust, y = yjust, just = c(xjust, yjust),\n height = if (vert) heightDetails(g) else 1,\n width = if (!vert) widthDetails(g) else 1\n ))\n })\n guide_ind <- seq(by = 2, length.out = length(guides))\n sep_ind <- seq(2, by = 2, length.out = length(guides) - 1)\n if (vert) {\n heights <- max(heights)\n if (length(widths) != 1) {\n w <- unit(rep_len(0, length(widths) * 2 - 1), \"mm\")\n w[guide_ind] <- widths\n w[sep_ind] <- legend.spacing.x\n widths <- w\n }\n } else {\n widths <- max(widths)\n if (length(heights) != 1) {\n h <- unit(rep_len(0, length(heights) * 2 - 1), \"mm\")\n h[guide_ind] <- heights\n h[sep_ind] <- legend.spacing.y\n heights <- h\n }\n }\n widths <- unit.c(legend.box.margin[4], widths, legend.box.margin[2])\n heights <- unit.c(legend.box.margin[1], heights, legend.box.margin[3])\n guides <- gtable_add_grob(\n gtable(widths, heights, name = \"guide-box\"),\n guides,\n t = 1 + if (!vert) guide_ind else 1,\n l = 1 + if (vert) guide_ind else 1,\n name = \"guides\"\n )\n gtable_add_grob(\n guides,\n element_render(theme, \"legend.box.background\"),\n t = 1, l = 1, b = -1, r = -1,\n z = -Inf, clip = \"off\", name = \"legend.box.background\"\n )\n}\n\n#' @importFrom ggplot2 calc_element\ncomplete_guide_theme <- function(guide_pos, theme) {\n if (guide_pos %in% c(\"top\", \"bottom\")) {\n theme$legend.box <- calc_element(\"legend.box\", theme) %||% \"horizontal\"\n theme$legend.direction <- calc_element(\"legend.direction\", theme) %||%\n \"horizontal\"\n theme$legend.box.just <- calc_element(\"legend.box.just\", theme) %||%\n c(\"center\", \"top\")\n } else {\n theme$legend.box <- calc_element(\"legend.box\", theme) %||% \"vertical\"\n theme$legend.direction <- calc_element(\"legend.direction\", theme) %||%\n \"vertical\"\n theme$legend.box.just <- calc_element(\"legend.box.just\", theme) %||%\n c(\"left\", \"top\")\n }\n theme\n}\n# nocov end\n\n################################################################ 3\n# Copied from patchwork\ncollapse_guides <- function(guides) {\n unnamed <- lapply(guides, unname_grob)\n for (i in rev(seq_along(unnamed)[-1])) {\n for (j in seq_len(i - 1)) {\n if (isTRUE(all.equal(unnamed[[i]], unnamed[[j]],\n check.names = FALSE, check.attributes = FALSE\n ))) {\n guides[i] <- NULL\n break\n }\n }\n }\n guides\n}\n\n#' @importFrom grid is.unit absolute.size\nunname_vp <- function(x) {\n if (inherits(x, \"vpTree\")) {\n x$parent <- unname_vp(x$parent)\n x$children <- lapply(x$children, unname_vp)\n } else if (inherits(x, \"viewport\")) {\n x$name <- \"\"\n if (!is.null(x$layout$widths)) {\n x$layout$widths <- absolute.size(x$layout$widths)\n }\n if (!is.null(x$layout$heights)) {\n x$layout$heights <- absolute.size(x$layout$heights)\n }\n }\n unit_elements <- vapply(x, is.unit, logical(1), USE.NAMES = FALSE)\n x[unit_elements] <- lapply(.subset(x, unit_elements), absolute.size)\n x\n}\n\n#' @importFrom grid is.grob is.unit absolute.size\n#' @importFrom gtable is.gtable\nunname_grob <- function(x) {\n if (is.gtable(x)) {\n x$name <- \"\"\n x$rownames <- NULL\n x$vp <- unname_vp(x$vp)\n names(x$grobs) <- NULL\n x$grobs <- lapply(x$grobs, unname_grob)\n } else if (is.grob(x)) {\n x$name <- \"\"\n x$vp <- unname_vp(x$vp)\n x$children <- unname(lapply(x$children, unname_grob))\n x$childrenOrder <- rep_len(\"\", length(x$childrenOrder))\n }\n unit_elements <- vapply(x, is.unit, logical(1), USE.NAMES = FALSE)\n x[unit_elements] <- lapply(.subset(x, unit_elements), absolute.size)\n x\n}\n"], ["/ggalign/R/utils-assert.R", "# `assert_*()` functions will do the side effects\n# `check_*()` functions will return the arguments\n#' @importFrom rlang caller_arg caller_call\nassert_gp <- function(gp, arg = caller_arg(gp), call = caller_call()) {\n assert_s3_class(gp, \"gpar\", arg = arg, call = call)\n}\n\n#' @importFrom rlang caller_arg caller_call\nassert_mapping <- function(mapping, arg = caller_arg(mapping),\n call = caller_call()) {\n if (!inherits(mapping, \"uneval\")) {\n cli_abort(c(\"{.arg {arg}} must be created with {.fn aes}.\",\n x = \"You've supplied {.obj_type_friendly {mapping}}.\"\n ), call = call)\n }\n}\n\nassert_mismatch_nobs <- function(align, n, nobs, arg) {\n if (n != nobs) {\n cli_abort(sprintf(\n \"{.arg %s} (nobs: %d) of %s is not compatible with the %s (nobs: %d)\",\n arg, nobs, object_name(align), align$layout_name, n\n ))\n }\n}\n\nassert_sub_split <- function(align, panel) {\n if (!is.null(panel)) {\n cli_abort(c(\n sprintf(\"%s cannot do sub-split\", object_name(align)),\n i = sprintf(\n \"Group of layout %s-axis already exists\",\n to_coord_axis(align$direction)\n )\n ), call = align$call)\n }\n}\n\nassert_reorder <- function(align, panel, index, strict) {\n if (!is.null(panel) && nlevels(panel) > 1L && strict &&\n !all(index == reorder_index(panel, index))) {\n layout_name <- align$layout_name\n object_name <- object_name(align)\n cli_abort(c(\n sprintf(\"Cannot add %s to %s\", object_name, layout_name),\n i = sprintf(\n \"Group of %s will disrupt the ordering index of %s\", layout_name, object_name\n ),\n i = \"try to set {.code strict = FALSE} to reorder within each group\"\n ), call = align$call)\n }\n}\n\nassert_position <- function(position, arg = caller_arg(position),\n call = caller_call()) {\n assert_string(position, empty_ok = FALSE, arg = arg, call = call)\n if (grepl(\"[^tlbr]\", position)) {\n cli_abort(sprintf(\n \"{.arg {arg}} can only contain the %s characters\",\n oxford_and(.tlbr)\n ), call = call)\n }\n}\n\nassert_guides <- function(guides, arg = caller_arg(guides),\n call = caller_call()) {\n assert_string(guides, empty_ok = FALSE, arg = arg, call = call)\n if (grepl(\"[^tlbri]\", guides)) {\n cli_abort(sprintf(\n \"{.arg {arg}} can only contain the %s characters\",\n oxford_and(c(.tlbr, \"i\"))\n ), call = call)\n }\n}\n\nassert_layout_position <- function(position, arg = caller_arg(position),\n call = caller_call()) {\n if (!is.waive(position) && !is.null(position)) {\n assert_position(position, arg = arg, call = call)\n }\n}\n\nassert_layout_guides <- function(guides, arg = caller_arg(guides),\n call = caller_call()) {\n if (!is.waive(guides) && !is.null(guides)) {\n assert_guides(guides, arg = arg, call = call)\n }\n}\n\n#' @importFrom grid is.unit\ncheck_stack_sizes <- function(sizes, arg = caller_arg(sizes),\n call = caller_call()) {\n if (!(all(is.na(sizes)) || is.numeric(sizes) || is.unit(sizes))) {\n cli_abort(\n \"{.arg {arg}} must be a numeric or {.cls unit} object\",\n call = call\n )\n }\n l <- length(sizes)\n if (l != 1L && l != 3L) {\n cli_abort(\n \"{.arg {arg}} must have size `1` or `3`, not size {l}\",\n call = call\n )\n }\n if (!is.unit(sizes)) sizes <- unit(sizes, \"null\")\n sizes\n}\n\n#' @importFrom rlang arg_match0\ncheck_direction <- function(direction, arg = caller_arg(direction),\n call = caller_call()) {\n direction <- arg_match0(direction, c(\"h\", \"v\"),\n arg_nm = arg, error_call = call\n )\n switch(direction, h = \"horizontal\", v = \"vertical\") # styler: off\n}\n\nassert_limits <- function(limits, allow_null = TRUE, arg = caller_arg(limits),\n call = caller_call()) {\n if (is.null(limits) && allow_null) {\n return(invisible(NULL))\n }\n if (!inherits(limits, \"continuous_limits\")) {\n cli_abort(\n \"{.arg {arg}} must be specified with {.fn continuous_limits}\",\n call = call\n )\n }\n if (rlang::is_named(limits)) {\n cli_abort(\n \"{.arg {arg}} shouldn't be created with {.arg x}/{.arg y} argument in {.fn continuous_limits}\",\n call = call\n )\n }\n}\n\n#' @importFrom grid is.unit\ncheck_size <- function(size, arg = caller_arg(size), call = caller_call()) {\n if (!is_scalar(size) &&\n !(is.na(size) || is.numeric(size) || is.unit(size))) {\n cli_abort(\n \"{.arg {arg}} must be a single numeric or unit object\",\n call = call\n )\n }\n if (!is.unit(size)) size <- unit(size, \"null\")\n size\n}\n\ncheck_scheme_data <- function(data, arg = caller_arg(data),\n call = caller_call()) {\n if (!is.waive(data) && !is.null(data) &&\n !is.function(data <- allow_lambda(data))) {\n cli_abort(paste(\n \"{.arg {arg}} must be a function,\",\n \"{.code NULL} or {.fn waiver}\"\n ), call = call)\n }\n data\n}\n\ncheck_stack_context <- function(what, arg = caller_arg(what),\n call = caller_call()) {\n if (is.null(what)) return(what) # styler: off\n if (.rlang_check_number(what, allow_decimal = FALSE, min = 1) != 0L &&\n !is_string(what)) {\n cli_abort(\n \"{.arg {arg}} must be a single positive integer number or string\",\n call = call\n )\n }\n what\n}\n\ncheck_order <- function(order, arg = caller_arg(order), call = caller_call()) {\n if (is.null(order)) {\n NA_integer_\n } else if (.rlang_check_number(order, allow_decimal = FALSE) == 0L) {\n as.integer(order)\n } else {\n cli_abort(\"{.arg {arg}} must be single integer number\", call = call)\n }\n}\n\nassert_align <- function(x, arg = caller_arg(x), call = caller_call()) {\n if (!inherits(x, \"scheme_align\")) {\n cli_abort(\n \"{.arg {arg}} must be created by {.fn scheme_align}\",\n call = call\n )\n }\n}\n\nassert_active <- function(x, allow_null = TRUE,\n arg = caller_arg(x), call = caller_call()) {\n if (is.null(x) && allow_null) {\n return(invisible(NULL))\n }\n if (!inherits(x, \"ggalign_active\")) {\n cli_abort(\n \"{.arg {arg}} must be created by {.fn active}\",\n call = call\n )\n }\n}\n\nassert_obs_size <- function(obs_size, arg = caller_arg(obs_size),\n call = caller_call()) {\n if (.rlang_check_number(obs_size, allow_decimal = TRUE, # styler: off\n .Machine$double.eps, 1) != 0L) { # styler: off\n cli_abort(\n \"{.arg {arg}} must be a single number in `(0, 1]`\",\n call = call\n )\n }\n}\n"], ["/ggalign/R/alignpatch-wrap.R", "#' Wrap Arbitrary Graphics to ggplot\n#'\n#' The `ggwrap()` function allows non-ggplot2 elements to be converted into a\n#' compliant representation for use with [`align_plots()`]. This is useful for\n#' adding any graphics that can be converted into a [`grob`][grid::grob] with\n#' the [`patch()`] method.\n#'\n#' @param plot Any graphic that can be converted into a [`grob`][grid::grob]\n#' using [`patch()`].\n#' @param ... Additional arguments passed to the [`patch()`] method.\n#' @param align A string specifying the area to place the plot: `\"full\"` for the\n#' full area, `\"plot\"` for the full plotting area (including the axis label), or\n#' `\"panel\"` for only the actual area where data is drawn.\n#' @param clip A single boolean value indicating whether the grob should be\n#' clipped if they expand outside their designated area.\n#' @param on_top A single boolean value indicates whether the graphic plot\n#' should be put frontmost. Note: the graphic plot will always put above the\n#' background.\n#' @param vp A [`viewport`][grid::viewport] object, you can use this to define\n#' the plot area.\n#' @return A `wrapped_plot` object that can be directly placed into\n#' [`align_plots()`].\n#' @inherit patch seealso\n#' @examples\n#' library(grid)\n#' ggwrap(rectGrob(gp = gpar(fill = \"goldenrod\")), align = \"full\") +\n#' inset(rectGrob(gp = gpar(fill = \"steelblue\")), align = \"panel\") +\n#' inset(textGrob(\"Here are some text\", gp = gpar(color = \"black\")),\n#' align = \"panel\"\n#' )\n#' p1 <- ggplot(mtcars) +\n#' geom_point(aes(mpg, disp)) +\n#' ggtitle(\"Plot 1\")\n#' align_plots(p1, ggwrap(\n#' ~ plot(mtcars$mpg, mtcars$disp),\n#' mar = c(0, 2, 0, 0), bg = NA\n#' ))\n#'\n#' @importFrom ggplot2 theme element_blank ggplot\n#' @importFrom grid is.grob\n#' @export\nggwrap <- function(plot, ..., align = \"panel\", on_top = FALSE,\n clip = TRUE, vp = NULL) {\n patch <- ggplot() +\n theme(\n plot.background = element_blank(),\n panel.background = element_blank()\n )\n inset <- make_inset(\n plot = plot, ..., align = align, on_top = on_top,\n clip = clip, vp = vp\n )\n make_wrap(patch, inset)\n}\n\nmake_wrap <- function(patch, inset) UseMethod(\"make_wrap\")\n\nmake_wrapped_plot <- function(patch, inset) {\n if (.subset2(inset, \"on_top\")) {\n patch$ggalign_wrapped_insets_above <- c(\n patch$ggalign_wrapped_insets_above, list(inset)\n )\n } else {\n patch$ggalign_wrapped_insets_under <- c(\n patch$ggalign_wrapped_insets_under, list(inset)\n )\n }\n add_class(patch, \"wrapped_plot\")\n}\n\n#' @export\nmake_wrap.ggplot <- function(patch, inset) {\n patch <- add_class(patch, \"patch_ggplot\")\n make_wrap(patch, inset)\n}\n\n#' @export\nmake_wrap.patch_ggplot <- make_wrapped_plot\n\n#' @export\nmake_wrap.alignpatches <- make_wrapped_plot\n\n#################################################\n#' @importFrom ggplot2 ggproto ggproto_parent\n#' @export\nalignpatch.wrapped_plot <- function(x) {\n Parent <- NextMethod()\n ggproto(\n \"PatchWrapped\", Parent,\n ggalign_wrapped_insets_under = x$ggalign_wrapped_insets_under,\n ggalign_wrapped_insets_above = x$ggalign_wrapped_insets_above,\n patch_gtable = function(self, theme, guides, plot = Parent$plot) {\n ans <- ggproto_parent(Parent, self)$patch_gtable(\n theme = theme, guides = guides, plot = plot\n )\n ans <- add_wrapped_insets(\n ans, self$ggalign_wrapped_insets_under, FALSE\n )\n add_wrapped_insets(ans, self$ggalign_wrapped_insets_above, TRUE)\n }\n )\n}\n\n# For wrapped plot -------------------\n#' @export\nalignpatch.grob <- function(x) alignpatch(ggwrap(x))\n\n#' @export\nalignpatch.gList <- alignpatch.grob\n\n#' @export\nalignpatch.formula <- alignpatch.grob\n\n#' @export\nalignpatch.function <- alignpatch.grob\n\n#' @export\nalignpatch.recordedplot <- alignpatch.grob\n\n#' @export\nalignpatch.trellis <- alignpatch.grob\n\n#' @export\nalignpatch.Heatmap <- function(x) alignpatch(ggwrap(x, align = \"full\"))\n\n#' @export\nalignpatch.HeatmapList <- alignpatch.Heatmap\n\n#' @export\nalignpatch.HeatmapAnnotation <- alignpatch.Heatmap\n\n#' @export\nalignpatch.pheatmap <- function(x) alignpatch(ggwrap(x, align = \"full\"))\n\n################################################## 3\nadd_wrapped_insets <- function(gt, insets, on_top) {\n if (is.null(insets)) return(gt) # styler: off\n for (i in seq_along(insets)) {\n gt <- add_wrapped_inset(gt, .subset2(insets, i), on_top, i)\n }\n gt\n}\n\n#' @importFrom gtable gtable is.gtable gtable_add_grob\nadd_wrapped_inset <- function(gt, inset, on_top, i) {\n align <- .subset2(inset, \"align\")\n clip <- .subset2(inset, \"clip\")\n layout <- .subset2(gt, \"layout\")\n grob <- .subset2(inset, \"grob\")\n if (on_top) {\n z <- Inf\n } else {\n background <- .subset2(layout, \"name\") == \"background\"\n z <- .subset2(layout, \"z\")[background] + 1L\n gt$layout$z[layout$z >= z] <- layout$z[layout$z >= z] + 1L\n }\n\n # add the grob to the gtable\n if (align == \"full\") {\n gt <- gtable_add_grob(gt,\n list(grob), 1L, 1L, nrow(gt), ncol(gt),\n clip = clip, name = sprintf(\"wrap-full-%d\", i), z = z\n )\n } else {\n panel_loc <- find_panel(gt)\n gt <- switch(align,\n plot = gtable_add_grob(gt,\n list(grob),\n .subset2(panel_loc, \"t\") - 3L,\n .subset2(panel_loc, \"l\") - 3L,\n .subset2(panel_loc, \"b\") + 3L,\n .subset2(panel_loc, \"r\") + 3L,\n clip = clip, name = sprintf(\"wrap-plot-%d\", i), z = z\n ),\n panel = gtable_add_grob(gt,\n list(grob),\n .subset2(panel_loc, \"t\"),\n .subset2(panel_loc, \"l\"),\n .subset2(panel_loc, \"b\"),\n .subset2(panel_loc, \"r\"),\n clip = clip, name = sprintf(\"wrap-panel-%d\", i), z = z\n )\n )\n }\n gt\n}\n"], ["/ggalign/R/alignpatch-free-align.R", "#' Free from alignment\n#'\n#' [align_plots] will try to align plot panels, and every elements of the plot,\n#' following functions romove these restrictions:\n#' - `free_align`: if we want to compose plots without alignment of some panel\n#' axes (panel won't be aligned). we can wrap the plot with `free_align`.\n#' - `free_border`: attaches borders (e.g., axis titles, tick marks) directly to\n#' the plot panel. This keeps them visually close to the panel during\n#' alignment.\n#' - `free_lab()`: Similar to `free_border()`, but only attaches axis titles\n#' and tick labels, not full borders. It’s mainly included for completeness;\n#' in most cases, combining `free_border()` and `free_space()` is sufficient.\n#' - `free_space`: Removing the ggplot element sizes when aligning.\n#' - `free_vp`: Customize the [viewport][grid::viewport] when aligning.\n#' - `free_guide`: If we want to override the behaviour of the overall guides\n#' behaviour, we can wrap the plot with `free_guide`.\n#'\n#' @param plot A [ggplot][ggplot2::ggplot] or [alignpatches][align_plots]\n#' object.\n#' @param axes Which axes shouldn't be aligned? A string containing\n#' one or more of `r oxford_and(.tlbr)`.\n#' @return\n#' - `free_align`: A modified version of `plot` with a `free_align` class.\n#' @examples\n#' # directly copied from `patchwork`\n#' # Sometimes you have a plot that defies good composition alginment, e.g. due\n#' # to long axis labels\n#' p1 <- ggplot(mtcars) +\n#' geom_bar(aes(y = factor(gear), fill = factor(gear))) +\n#' scale_y_discrete(\n#' \"\",\n#' labels = c(\n#' \"3 gears are often enough\",\n#' \"But, you know, 4 is a nice number\",\n#' \"I would def go with 5 gears in a modern car\"\n#' )\n#' )\n#'\n#' # When combined with other plots it ends up looking bad\n#' p2 <- ggplot(mtcars) +\n#' geom_point(aes(mpg, disp))\n#'\n#' align_plots(p1, p2, ncol = 1L)\n#'\n#' # We can fix this be using `free_align`\n#' align_plots(free_align(p1), p2, ncol = 1L)\n#'\n#' # If we still want the panels to be aligned to the right, we can choose to\n#' # free only the left side\n#' align_plots(free_align(p1, axes = \"l\"), p2, ncol = 1L)\n#'\n#' # We could use `free_lab` to fix the layout in a different way\n#' align_plots(p1, free_lab(p2), ncol = 1L)\n#'\n#' # `free_border` is similar with `free_lab`, they have a distinction in terms\n#' # of placement on either the top or bottom side of the panel. Specifically,\n#' # the top side contains the `title` and `subtitle`, while the bottom side\n#' # contains the `caption`. free_lab() does not attach these elements in the\n#' # panel area.\n#' p3 <- ggplot(mtcars) +\n#' geom_point(aes(hp, wt, colour = mpg)) +\n#' ggtitle(\"Plot 3\")\n#' p_axis_top <- ggplot(mtcars) +\n#' geom_point(aes(mpg, disp)) +\n#' ggtitle(\"Plot axis in top\") +\n#' scale_x_continuous(position = \"top\")\n#' align_plots(p_axis_top, free_lab(p3))\n#' align_plots(p_axis_top, free_border(p3))\n#'\n#' # Another issue is that long labels can occupy much spaces\n#' align_plots(NULL, p1, p2, p2)\n#'\n#' # This can be fixed with `free_space`\n#' align_plots(NULL, free_space(p1, \"l\"), p2, p2)\n#'\n#' @export\n#' @rdname free\nfree_align <- function(plot, axes = \"tlbr\") {\n UseMethod(\"free_align\")\n}\n\n# free_guides: set_guides\n# free_lab: collect_guides\n# free_border: collect_guides and align_border\n# free_space: get_sizes\n# free_align: get_sizes and align_border\n# free_vp: align_border\n\n#' @export\nfree_align.ggplot <- function(plot, axes = \"tlbr\") {\n assert_position(axes)\n attr(plot, \"free_axes\") <- axes\n add_class(plot, \"free_align\")\n}\n\n#' @export\nfree_align.alignpatches <- free_align.ggplot\n\n#' @importFrom rlang is_empty\n#' @export\nfree_align.free_lab <- function(plot, axes = \"tlbr\") {\n assert_position(axes)\n # if axes are free, it's not necessary to free the labs\n free_labs <- setdiff_position(attr(plot, \"free_labs\"), axes)\n if (nzchar(free_labs)) {\n attr(plot, \"free_labs\") <- free_labs\n } else {\n attr(plot, \"free_labs\") <- NULL\n plot <- remove_class(plot, \"free_lab\")\n }\n NextMethod()\n}\n\n#' @importFrom rlang is_empty\n#' @export\nfree_align.free_space <- function(plot, axes = \"tlbr\") {\n assert_position(axes)\n free_spaces <- setdiff_position(attr(plot, \"free_spaces\"), axes)\n if (nzchar(free_spaces)) {\n attr(plot, \"free_spaces\") <- free_spaces\n } else {\n attr(plot, \"free_spaces\") <- NULL\n plot <- remove_class(plot, \"free_space\")\n }\n NextMethod()\n}\n\n#' @importFrom rlang is_empty\n#' @export\nfree_align.free_border <- function(plot, axes = \"tlbr\") {\n assert_position(axes)\n free_borders <- setdiff_position(attr(plot, \"free_borders\"), axes)\n if (nzchar(free_borders)) {\n attr(plot, \"free_borders\") <- free_borders\n } else {\n attr(plot, \"free_borders\") <- NULL\n plot <- remove_class(plot, \"free_border\")\n }\n NextMethod()\n}\n\n#' @export\nfree_align.free_align <- function(plot, axes = \"tlbr\") {\n assert_position(axes)\n attr(plot, \"free_axes\") <- union_position(attr(plot, \"free_axes\"), axes)\n plot\n}\n\n#' @export\nfree_align.default <- function(plot, axes = \"tlbr\") {\n cli_abort(\"Cannot use with {.obj_type_friendly {plot}}\")\n}\n\n#' @importFrom ggplot2 ggproto ggproto_parent\n#' @export\nalignpatch.free_align <- function(x) {\n Parent <- NextMethod()\n ggproto(\n \"PatchFreeAlign\", Parent,\n free_axes = split_position(attr(x, \"free_axes\")),\n get_sizes = function(self, free = NULL, gt = self$gt) {\n ggproto_parent(Parent, self)$get_sizes(\n union(free, self$free_axes),\n gt = gt\n )\n },\n align_border = function(self, t = NULL, l = NULL, b = NULL, r = NULL,\n gt = self$gt) {\n for (axis in self$free_axes) {\n assign(x = axis, value = NULL, envir = environment())\n }\n ggproto_parent(Parent, self)$align_border(\n t = t, l = l, b = b, r = r, gt = gt\n )\n }\n )\n}\n"], ["/ggalign/R/genomic-helper.R", "#' Calculate inter-region distances for genomic rainfall plots\n#'\n#' This function computes distances between adjacent genomic regions, grouped by\n#' chromosome. Useful for visualizing clustering or dispersion of genomic\n#' features.\n#'\n#' @param region A data frame with at least 3 columns: chromosome, start, and\n#' end.\n#' @param mode How to assign distance for intermediate regions: one of `\"min\"`,\n#' `\"max\"`, `\"mean\"`, `\"left\"`, or `\"right\"`.\n#' @details\n#' The distance between two adjacent regions is calculated as the number of\n#' bases between the **end position of the upstream region** and the\n#' **start position of the downstream region**. If two regions overlap or are\n#' adjacent (≤1 bp apart), the distance is set to `0`. The resulting distance is\n#' assigned to each region according to the selected `mode`:\n#'\n#' - `\"left\"`: assign the distance to the upstream region\n#' - `\"right\"`: assign to the downstream region\n#' - `\"min\"` / `\"max\"` / `\"mean\"`: for intermediate regions, calculate the\n#' minimum, maximum, or average of the distances to neighboring regions\n#'\n#' @return A data frame with an additional `dist` column.\n#' @export\ngenomic_dist <- function(region, mode = NULL) {\n # Check input validity\n if (is.null(mode)) {\n mode <- \"min\"\n } else {\n mode <- arg_match0(mode, c(\"min\", \"max\", \"mean\", \"left\", \"right\"))\n }\n if (!is.data.frame(region) || ncol(region) < 3L) {\n cli_abort(\"{.arg region} must have at least 3 columns: chromosome, start, and end\")\n }\n if (anyNA(region[[1L]]) || anyNA(region[[2L]]) || anyNA(region[[3L]])) {\n cli_abort(\"Columns 1, 2, and 3 of {.arg region} must not contain missing values\")\n }\n if (!is.numeric(region[[2L]]) || !is.numeric(region[[3L]])) {\n cli_abort(\"Columns 2 and 3 of {.arg region} must be numeric (start and end positions)\")\n }\n if (any(region[[2L]] > region[[3L]])) {\n cli_abort(\"Column 2 (start) must not be greater than column 3 (end) in any row of {.arg region}\")\n }\n\n # Split the region data frame by chromosome (first column)\n groups <- vec_split(region, .subset2(region, 1L))\n dist_list <- lapply(.subset2(groups, \"val\"), function(d) {\n n <- nrow(d)\n if (n < 2L) {\n d$dist <- NA_real_\n return(d)\n }\n\n # Sort regions by start, then end positions\n ordering <- order(.subset2(d, 2L), .subset2(d, 3L))\n\n # Compute distances between adjacent regions\n dists <- vapply(seq_len(n - 1L), function(i) {\n first <- vec_slice(d, ordering[i])\n second <- vec_slice(d, ordering[i + 1])\n out <- .subset2(second, 2L) - .subset2(first, 3L)\n # If overlapping or adjacent (≤1 bp), treat distance as 0\n if (out <= 1L) out <- 0L else out <- as.integer(out)\n out\n }, integer(1L), USE.NAMES = FALSE)\n\n # If only two regions, just repeat the distance\n if (n == 2L) {\n d$dist <- rep_len(dists, n)\n return(d)\n }\n\n # For intermediate regions (not first or last), choose how to assign\n # distance\n d1 <- dists[seq_len(n - 2L)]\n d2 <- dists[2:(n - 1L)]\n if (mode == \"min\") {\n body_dists <- pmin(d1, d2)\n } else if (mode == \"max\") {\n body_dists <- pmax(d1, d2)\n } else if (mode == \"mean\") {\n body_dists <- (d1 + d2) / 2L\n } else if (mode == \"left\") {\n body_dists <- d1\n } else if (mode == \"right\") {\n body_dists <- d2\n }\n\n # Combine distances: head, body, and tail\n d$dist <- c(dists[1L], body_dists, dists[n - 1L])[order(ordering)]\n d\n })\n vec_rbind(!!!dist_list)\n}\n\n#' Calculate Genomic Region Density\n#'\n#' Computes the density or count of genomic regions in sliding or fixed windows\n#' across the genome. The density can be reported as the percentage of uncovered\n#' bases or the number of overlapping regions within each window.\n#'\n#' This function splits the input by chromosome and tiles the genomic space\n#' into windows, optionally overlapping. For each window, it calculates:\n#'\n#' - the number of regions that overlap it (if `mode = \"count\"`), or\n#' - the fraction of bases covered by any region (if `mode = \"percent\"`).\n#'\n#' @param region A data frame with at least 3 columns: chromosome, start, and\n#' end.\n#' - Column 1: character or factor, chromosome name.\n#' - Column 2: numeric, start position (must be ≤ end).\n#' - Column 3: numeric, end position.\n#' @param window_size Numeric, the width of each window (default is `1e+07`).\n#' Ignored if `n_window` is specified.\n#' @param n_window Integer, the number of windows per chromosome. If provided,\n#' overrides `window_size` and evenly splits the chromosome into `n_window`\n#' (non-overlapping) or `2*n_window - 1` (overlapping) windows.\n#' @param overlap Logical, whether to use overlapping windows (default `TRUE`).\n#' Overlapping windows are spaced by half the window size.\n#' @param mode Character, either `\"coverage\"` or `\"count\"`:\n#' - `\"count\"`: reports the number of regions overlapping each window.\n#' - `\"coverage\"`: reports the fraction of each window covered by regions.\n#' @param seqlengths Optional named vector of chromosome lengths. If missing,\n#' the maximum `end` value in the input is used as the chromosome length.\n#'\n#' @return A data frame with columns:\n#' - `seqnames`: The sequence (e.g., chromosome) names.\n#' - `start`: start of each window\n#' - `end`: end of each window\n#' - `density`: the region count or covered percent, depending on `mode`\n#'\n#' @examples\n#' region <- data.frame(\n#' chr = rep(\"chr1\", 3),\n#' start = c(100, 5000000, 15000000),\n#' end = c(2000000, 7000000, 17000000)\n#' )\n#' genomic_density(region, window_size = 1e7, mode = \"count\")\n#' genomic_density(region, n_window = 3, overlap = FALSE, mode = \"coverage\")\n#'\n#' @export\ngenomic_density <- function(region, window_size = 1e+07, n_window = NULL,\n overlap = TRUE, mode = c(\"coverage\", \"count\"),\n seqlengths = NULL) {\n # Check input validity\n assert_number_whole(window_size, allow_null = TRUE, min = 1)\n assert_number_whole(n_window, allow_null = TRUE, min = 1)\n if (is.null(window_size) && is.null(n_window)) {\n cli_abort(c(\n \"Both {.arg window_size} and {.arg n_window} are {.val NULL}.\",\n \"i\" = \"You must supply at least one of these arguments to define the binning strategy.\"\n ))\n }\n assert_bool(overlap)\n if (is.null(mode)) {\n mode <- \"coverage\"\n } else {\n mode <- arg_match0(mode, c(\"coverage\", \"count\"))\n }\n if (!is.data.frame(region) || ncol(region) < 3L) {\n cli_abort(\"{.arg region} must have at least 3 columns: chromosome, start, and end\")\n }\n if (anyNA(region[[1L]]) || anyNA(region[[2L]]) || anyNA(region[[3L]])) {\n cli_abort(\"Columns 1, 2, and 3 of {.arg region} must not contain missing values\")\n }\n if (!is.numeric(region[[2L]]) || !is.numeric(region[[3L]])) {\n cli_abort(\"Columns 2 and 3 of {.arg region} must be numeric (start and end positions)\")\n }\n if (any(region[[2L]] > region[[3L]])) {\n cli_abort(\"Column 2 (start) must not be greater than column 3 (end) in any row of {.arg region}\")\n }\n\n # Split the region data frame by chromosome (first column)\n groups <- vec_split(region, .subset2(region, 1L))\n density_list <- lapply(.subset2(groups, \"val\"), function(d) {\n chr <- .subset2(d, 1L)[1L]\n if (is.null(seqlengths)) {\n max_pos <- max(.subset2(region, 3L))\n } else {\n max_pos <- seqlengths[chr]\n if (is.na(max_pos)) {\n cli_abort(\"Chromosome {.val {chr}} is not found in {.arg seqlengths}. Please check that all chromosomes in {.arg region} have corresponding sequence lengths.\")\n }\n }\n if (overlap) {\n if (is.null(n_window)) {\n # Half-step sliding windows: start at 1, step = half window size\n b <- seq(0L, max_pos, by = window_size %/% 2L)\n s <- b[-length(b)]\n s <- s[-length(s)] + 1L\n e <- s + window_size - 1L\n } else {\n b <- seq(0L, max_pos, length.out = 2L * n_window + 1L)\n s <- b[-length(b)]\n s <- s[-length(s)] + 1L\n e <- s + b[3L] - b[1L] - 1L\n }\n } else {\n if (is.null(n_window)) {\n b <- seq(0L, max_pos, by = window_size)\n s <- b[-length(b)] + 1L\n e <- s + window_size - 1L\n } else {\n b <- seq(0, max_pos, length.out = n_window + 1L)\n s <- b[-length(b)] + 1L\n e <- s + b[2L] - b[1L]\n }\n }\n s <- as.integer(s)\n e <- as.integer(e)\n region_s <- .subset2(d, 2L)\n region_e <- .subset2(d, 3L)\n if (mode == \"count\") {\n # For each window, count how many regions overlap with it\n density <- vapply(seq_along(s), function(i) {\n si <- s[i]\n ei <- e[i]\n sum(!(region_s > ei | region_e < si))\n }, integer(1L), USE.NAMES = FALSE)\n } else {\n region_s <- as.integer(ceiling(region_s))\n region_e <- as.integer(floor(region_e))\n # For each window, calculate the proportion of bases covered by\n # regions\n density <- vapply(seq_along(s), function(i) {\n si <- s[i]\n ei <- e[i]\n # Keep regions that overlap with current window\n keep <- !(region_s > ei | region_e < si)\n\n # Clip regions to fit within the current window\n region_s_used <- pmax(region_s[keep], si)\n region_e_used <- pmin(region_e[keep], ei)\n\n # If no overlapping region, coverage is zero\n if (length(region_s_used) == 0L) {\n return(0)\n }\n\n # Sort intervals by start, then end\n ordering <- order(region_s_used, region_e_used)\n region_s_used <- region_s_used[ordering]\n region_e_used <- region_e_used[ordering]\n\n # Initialize with the first interval\n start <- region_s_used[1L]\n end <- region_e_used[1L]\n\n # If there's only one interval, just compute its coverage\n if (length(region_s_used) == 1L) {\n cov <- end - start + 1L\n return(cov / (ei - si + 1L))\n }\n # Merge overlapping/adjacent intervals and compute total\n # coverage\n cov <- 0L\n for (j in 2:length(region_s_used)) {\n if (region_s_used[j] - end <= 1L) {\n end <- max(end, region_e_used[j])\n } else {\n cov <- cov + (end - start + 1L)\n start <- region_s_used[j]\n end <- region_e_used[j]\n }\n }\n cov <- cov + (end - start + 1L)\n cov / (ei - si + 1L)\n }, numeric(1L), USE.NAMES = FALSE)\n }\n data_frame0(seqnames = chr, start = s, end = e, density = density)\n })\n vec_rbind(!!!density_list)\n}\n"], ["/ggalign/R/craft-align-group.R", "#' Group and align observations based on a group vector\n#'\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' Splits observations into groups, with slice ordering based on group levels.\n#'\n#' @param group A character define the groups of the observations.\n#' @inheritParams align\n#' @examples\n#' set.seed(1L)\n#' small_mat <- matrix(rnorm(81), nrow = 9)\n#' ggheatmap(small_mat) +\n#' anno_top() +\n#' align_group(sample(letters[1:4], ncol(small_mat), replace = TRUE))\n#' @export\nalign_group <- function(group, active = NULL) {\n assert_active(active)\n if (vec_size(group) == 0L) {\n cli_abort(\"{.arg group} cannot be empty\")\n }\n active <- update_active(active, new_active(use = FALSE))\n align(\n align = AlignGroup,\n group = group,\n active = active,\n check.param = TRUE\n )\n}\n\n#' @importFrom ggplot2 ggproto\nAlignGroup <- ggproto(\"AlignGroup\", CraftAlign,\n interact_layout = function(self, layout) {\n layout <- ggproto_parent(CraftAlign, self)$interact_layout(layout)\n if (is.null(layout_nobs <- .subset2(layout@design, \"nobs\"))) {\n layout@design[\"nobs\"] <- list(vec_size(self$group))\n } else {\n assert_mismatch_nobs(\n self, layout_nobs, vec_size(self$group),\n arg = \"group\"\n )\n }\n layout\n },\n align = function(self, panel, index) list(self$group, index),\n summary_align = function(self) c(FALSE, TRUE)\n)\n"], ["/ggalign/R/grid-grob-channel.R", "#' Create a Grob That Spans Multiple Viewports\n#'\n#' This function initializes a communication channel to share location signals\n#' across different viewports. It returns a `channelSenderGrob` object, which\n#' can transmit multiple signals using its `$signal` method (see the \"Signal\"\n#' section below for details). When drawn, all collected signals are passed to\n#' the `make_content` function to generate the final [`grob`][grid::grob].\n#'\n#' @param make_content A function that accepts the list of signal locations and\n#' returns a [`grob`][grid::grob].\n#' @param ... Additional arguments passed to `make_content`.\n#' @inheritParams grid::grob\n#'\n#' @section Signal:\n#' A `channelSenderGrob` can emit multiple location signals using the `$signal`\n#' method. This method accepts the following arguments:\n#'\n#' - `x`: X-coordinate.\n#' - `y`: Y-coordinate.\n#' - `default.units`: The default units for `x` and `y`.\n#' - `tag`: A character string used to identify the location.\n#' - `name`: A name for the returned grob.\n#' - `vp`: A [`viewport`][grid::viewport] for the returned grob.\n#'\n#' The `$signal` method returns a `channelSignalGrob`.\n#'\n#' @return A `channelSenderGrob` object.\n#' @examples\n#' # we create a new channel, we will emit two singals\n#' # here: we just add a line between the two signals\n#' channel <- channelGrob(function(locations) {\n#' # you can also use `tag` to identify the locations\n#' loc1 <- .subset2(locations, 1L)\n#' loc2 <- .subset2(locations, 2L)\n#' grid::segmentsGrob(loc1$x, loc1$y, loc2$x, loc2$y)\n#' })\n#'\n#' gt <- gtable::gtable(unit(1:2, c(\"cm\")), unit(5, \"cm\"))\n#' gt <- gtable::gtable_add_grob(\n#' gt,\n#' list(\n#' grid::rectGrob(gp = gpar(color = \"black\", fill = NA)),\n#' channel$signal(0.5, 0.5, \"npc\")\n#' ),\n#' t = 1, l = 1, name = c(\"rect1\", \"signal1\")\n#' )\n#' gt <- gtable::gtable_add_grob(\n#' gt,\n#' list(\n#' grid::rectGrob(gp = gpar(color = \"red\", fill = NA)),\n#' channel$signal(0.5, 0.5, \"npc\")\n#' ),\n#' t = 1, l = 2, name = c(\"rect2\", \"signal2\")\n#' )\n#' grid::grid.newpage()\n#' grid::grid.draw(gt)\n#' @importFrom grid unit is.unit grob\n#' @importFrom rlang list2\n#' @export\nchannelGrob <- function(make_content, ..., name = NULL, vp = NULL) {\n make_content <- allow_lambda(make_content)\n if (!is.function(make_content)) {\n cli_abort(\"{.arg make_content} must be a function\")\n }\n # Used to communicate between different signals\n channel <- new.env(parent = emptyenv())\n channel$make_content <- make_content\n channel$dots <- list2(...)\n channel$n <- 0L # total number of signals\n grob(\n channel = channel,\n name = name,\n vp = vp,\n\n # method used to release signal and retutn a new grob\n signal = function(self, x, y, default.units = \"native\",\n tag = NULL, name = NULL, vp = NULL) {\n if (!is.unit(x)) x <- unit(x, default.units)\n if (!is.unit(y)) y <- unit(y, default.units)\n if (length(x) != length(y)) {\n cli_abort(\"{.arg x} and {.arg y} must have the same length\")\n }\n assert_string(tag, allow_empty = FALSE, allow_null = TRUE)\n signal <- list(list(x = x, y = y))\n if (!is.null(tag)) names(signal) <- tag\n channel <- .subset2(self, \"channel\")\n channel$signals <- c(channel$signals, signal)\n i <- channel$n <- channel$n + 1L\n grob(\n channel = channel,\n i = i,\n name = name,\n vp = vp,\n cl = c(\"channelSignalGrob\", \"channelGrob\")\n )\n },\n # Grob used to send signals\n cl = c(\"channelSenderGrob\", \"channelGrob\")\n )\n}\n\n#' @export\n`$.channelGrob` <- function(self, name) {\n field <- .subset2(self, name)\n if (!is.function(field)) {\n return(field)\n }\n args <- formals(field)\n # is.null is a fast path for a common case; the %in% check is slower but\n # also catches the case where there's a `self = NULL` argument.\n has_self <- !is.null(args[[\"self\"]]) || \"self\" %in% names(args)\n\n # We assign the method with its correct name and construct a call to it to\n # make errors reported as coming from the method name rather than `field()`\n assign(name, field, envir = environment())\n args <- list(quote(...))\n if (has_self) {\n args$self <- quote(self)\n }\n rlang::new_function(alist(... = ), rlang::call2(name, !!!args))\n}\n\n#' @export\n`[[.channelGrob` <- `$.channelGrob`\n\n# https://www.stat.auckland.ac.nz/~paul/Reports/CustomGrobs/custom-grob.html\n# preDraw:\n# - makeContext\n# - pushvpgp\n# - preDrawDetails: by default, do noting\n# makeContent:\n# drawDetails:\n# postDraw:\n# - postDrawDetails: by default, do noting\n# - popgrobvp\n#' @importFrom grid makeContent drawDetails viewport is.grob gTree grob\n#' @export\nmakeContent.channelGrob <- function(x) {\n channel <- .subset2(x, \"channel\")\n # If no signals, do nothing\n if (channel$n == 0L) return(x) # styler: off\n\n if (inherits(x, \"channelSenderGrob\")) {\n # we use the viewport from the signals sender\n channel$vp <- grid::current.viewport()\n } else if (inherits(x, \"channelSignalGrob\")) {\n if (is.null(channel$locations)) {\n channel$locations <- vector(\"list\", channel$n)\n names(channel$locations) <- names(channel$signals)\n }\n\n # convert the viewport coordinates to the device coordinates\n i <- .subset2(x, \"i\")\n signal <- .subset2(channel$signals, i)\n channel$locations[[i]] <- grid::deviceLoc(signal$x, signal$y)\n if (all(!vapply(channel$locations, is.null, logical(1L), # styler: off\n USE.NAMES = FALSE))) { # styler: off\n # When all locations have been prepared\n # we output the grob with all device locations\n x <- grob(\n channel = channel,\n vp = .subset2(x, \"vp\"), # Don't change the viewport\n cl = c(\"channelReceiverGrob\", \"channelGrob\")\n )\n }\n }\n x\n}\n\n#' @export\ndrawDetails.channelGrob <- function(x, recording) {\n}\n\n#' @importFrom grid grid.draw viewport gTree is.grob\n#' @export\ndrawDetails.channelReceiverGrob <- function(x, recording) {\n # we always reset the locations after drawing\n old <- grid::current.viewport()$name\n on.exit(grid::seekViewport(old), add = TRUE)\n channel <- .subset2(x, \"channel\")\n locations <- channel$locations\n on.exit(channel$locations <- NULL, add = TRUE)\n if (!is.null(vp <- channel$vp)) {\n grid::seekViewport(vp$name)\n # convert the device cooridnates into the drawing viewport coordinates\n trans <- solve(grid::current.transform())\n locations <- lapply(locations, grid_solve_loc, trans = trans)\n } else { # If no viewport, we use the `ROOT` viewport\n grid::upViewport(0)\n grid::pushViewport(viewport())\n }\n grob <- rlang::inject(channel$make_content(locations, !!!channel$dots))\n if (is.gList(grob)) grob <- gTree(children = grob)\n if (is.grob(grob)) grid.draw(grob, recording = recording)\n}\n"], ["/ggalign/R/utils.R", "# `vec_rep`\nrecycle_whole <- function(x, len) {\n out <- x %% len\n if (out == 0L) len else out\n}\n\n# `vec_rep_each`\nrecycle_each <- function(x, len) {\n (x - 1L) %/% len + 1L\n}\n\n#' @importFrom utils modifyList\nupdate_non_waive <- function(old, new, keep_null = TRUE) {\n modifyList(old,\n new[!vapply(new, is.waive, logical(1L), USE.NAMES = FALSE)],\n keep.null = keep_null\n )\n}\n\nis_s3 <- function(x) is.object(x) && !isS4(x) && !inherits(x, \"R6\")\n\n#' @importFrom rlang names2\nnames_or_index <- function(x) {\n nms <- names2(x)\n empty <- nms == \"\"\n nms[empty] <- seq_along(x)[empty]\n nms\n}\n\n#################################################################\n#' Read Example Data\n#'\n#' This function reads example data from the file. If no file is specified, it\n#' returns a list of available example files.\n#'\n#' @param file A string representing the name of the example file to be read. If\n#' `NULL`, the function will return a list of available example file names.\n#' @return If `file` is `NULL`, returns a character vector of available example\n#' file names. Otherwise, returns the contents of the specified example file,\n#' read as an R object.\n#' @examples\n#' read_example()\n#' @export\nread_example <- function(file = NULL) {\n if (is.null(file)) {\n dir(pkg_extdata())\n } else {\n readRDS(pkg_extdata(file, mustWork = TRUE))\n }\n}\n\nwith_options <- function(code, ...) {\n opts <- options(...)\n on.exit(options(opts))\n force(code)\n}\n\n#' @param ans Whether to assign the final results into the 'ans' variable.\n#' @noRd\nfn_body_append <- function(fn, ..., ans = FALSE) {\n args <- rlang::fn_fmls(fn)\n body <- rlang::fn_body(fn)\n body <- as.list(body)\n if (ans) body[[length(body)]] <- rlang::expr(ans <- !!body[[length(body)]])\n body <- as.call(c(body, rlang::enexprs(...)))\n rlang::new_function(args, body)\n}\n\n# This will work with most things but be aware that it might fail with some\n# complex objects. For example, according to `?S3Methods`, calling foo on\n# matrix(1:4, 2, 2) would try `foo.matrix`, then `foo.numeric`, then\n# `foo.default`; whereas this code will just look for `foo.matrix` and\n# `foo.default`.\n#' @importFrom utils getS3method\n#' @importFrom methods extends\nhas_method <- function(x, f, inherit = TRUE, default = inherit) {\n x_class <- class(x)\n if (inherit) {\n if (isS4(x)) x_class <- extends(x_class)\n if (default) x_class <- c(x_class, \"default\")\n } else {\n x_class <- .subset(x_class, 1L)\n }\n for (cls in x_class) {\n if (!is.null(getS3method(f, cls, optional = TRUE))) {\n return(TRUE)\n }\n }\n return(FALSE)\n}\n\n#' For functions with a `call` argument, we check if the call originates from\n#' the current package. If it does, we use the caller's call; if not, we use the\n#' current call directly. Used by `align()` and `free()`\n#' @noRd\n#' @importFrom utils packageName\noverride_call <- function(call = NULL) {\n # if no caller call\n if (is.null(call) || is.function(f <- .subset2(call, 1L))) {\n return(TRUE)\n }\n # if call from the current package\n !identical(\n packageName(environment(eval(f))),\n pkg_nm()\n )\n}\n\n# library(data.table)\n# library(vctrs)\n# `%nest_unique%` <- function(x, y) {\n# ans <- new_data_frame(list(x = x, y = y))\n# ans <- unique(ans)\n# !anyDuplicated(ans$x)\n# }\n# `%nest_vctrs%` <- function(x, y) {\n# ans <- new_data_frame(list(x = x, y = y))\n# ans <- vec_unique(ans)\n# !vec_duplicate_any(.subset2(ans, \"x\"))\n# }\n# `%nest_vctrs_loc%` <- function(x, y) {\n# # we don't check the inputs for performance\n# loc <- vec_unique_loc(new_data_frame(list(x = x, y = y)))\n# !vec_duplicate_any(vec_slice(x, loc))\n# }\n# `%nest_data_table%` <- function(x, y) {\n# ans <- data.table(x = x, y = y)\n# ans <- unique(ans)\n# !anyDuplicated(.subset2(ans, \"x\"))\n# }\n# `%nest_split%` <- function(x, y) {\n# all(lengths(lapply(split(y, x), unique)) == 1L)\n# }\n# `%nest_table%` <- function(x, y) {\n# all(rowSums(table(x, y) > 0L) == 1L)\n# }\n# foo <- rep(seq(10^4L / 2L), each = 4)\n# bar <- rep(seq(10^4L), each = 2)\n# bench::mark(\n# nest_unique = bar %nest_unique% foo,\n# nest_vctrs = bar %nest_vctrs% foo,\n# nest_vctrs_loc = bar %nest_vctrs_loc% foo,\n# nest_data_table = bar %nest_data_table% foo,\n# nest_split = bar %nest_split% foo,\n# nest_table = bar %nest_table% foo,\n# )\n#> Warning: Some expressions had a GC in every iteration; so filtering is\n#> disabled.\n#> # A tibble: 6 x 6\n#> expression min median `itr/sec` mem_alloc `gc/sec`\n#> \n#> 1 nest_unique 5.37ms 7.49ms 134. 1.33MB 69.2\n#> 2 nest_vctrs 200.3us 214.57us 3591. 754.7KB 6.00\n#> 3 nest_vctrs_loc 193.99us 207.29us 4490. 706.95KB 6.00\n#> 4 nest_data_table 402.71us 459.55us 1918. 985.25KB 4.00\n#> 5 nest_split 11.87ms 14.08ms 69.8 1.15MB 54.3\n#> 6 nest_table 183.52ms 189.87ms 5.20 576.35MB 8.67\n`%nest%` <- function(x, y) {\n # we don't check the inputs for performance\n loc <- vec_unique_loc(new_data_frame(list(x = x, y = y)))\n !vec_duplicate_any(vec_slice(x, loc))\n}\n\nsave_png <- function(code, width = 400L, height = 400L) {\n path <- tempfile(fileext = \".png\")\n grDevices::png(path, width = width, height = height)\n on.exit(grDevices::dev.off())\n print(code)\n path\n}\n\nadd_class <- function(x, ...) {\n if (is.null(x)) return(x) # styler: off\n class(x) <- vec_unique(c(..., class(x)))\n x\n}\n\nremove_class <- function(x, ...) {\n oldClass(x) <- vec_set_difference(oldClass(x), c(...))\n x\n}\n\n###########################################################\nswitch_position <- function(position, x, y) {\n switch(position,\n top = ,\n bottom = x,\n left = ,\n right = y\n )\n}\n\nto_direction <- function(position) {\n switch_position(position, \"vertical\", \"horizontal\")\n}\n\nis_vertical <- function(direction) direction == \"vertical\"\n\nis_horizontal <- function(direction) direction == \"horizontal\"\n\nswitch_direction <- function(direction, h, v) {\n if (is_horizontal(direction)) {\n h\n } else {\n v\n }\n}\n\nto_coord_axis <- function(direction) {\n switch_direction(direction, \"y\", \"x\")\n}\n\nto_matrix_axis <- function(direction) {\n switch_direction(direction, \"row\", \"column\")\n}\n\n##########################################################\ndata_frame0 <- function(...) data_frame(..., .name_repair = \"minimal\")\n\nas_data_frame0 <- function(data, ...) {\n as.data.frame(\n x = data, ...,\n make.names = FALSE,\n stringsAsFactors = FALSE,\n fix.empty.names = FALSE\n )\n}\n\nquickdf <- function(x) {\n class(x) <- \"data.frame\"\n attr(x, \"row.names\") <- .set_row_names(length(.subset2(x, 1L)))\n x\n}\n\nfct_rev <- function(x) {\n ans <- as.factor(x)\n factor(ans, levels = rev(levels(ans)))\n}\n\nreverse_trans <- function(x) sum(range(x, na.rm = TRUE)) - x\n\nfclass <- function(x) .subset(class(x), 1L)\n\nis_scalar <- function(x) length(x) == 1L\n\nis_scalar_numeric <- function(x) length(x) == 1L && is.numeric(x)\n"], ["/ggalign/R/ggplot-geom-pie.R", "#' Pie charts\n#' @section new aesthetics:\n#' - `angle`: the pie circle angle.\n#' - `angle0`: the initial pie circle angle.\n#' - `radius`: the circle radius.\n#' @inheritParams ggplot2::layer\n#' @inheritParams ggplot2::geom_polygon\n#' @inheritParams ggplot2::geom_path\n#' @param steps An integer indicating the number of steps to generate the pie\n#' chart radian. Increasing this value results in a smoother pie circular.\n#' @param clockwise A single boolean value indicates clockwise or not.\n#' @aesthetics GeomPie\n#' @examples\n#' ggplot(data.frame(x = 1:10, y = 1:10, value = 1:10 / sum(1:10))) +\n#' geom_pie(aes(x, y, angle = value * 360))\n#' @export\ngeom_pie <- function(mapping = NULL, data = NULL, stat = \"identity\",\n position = \"identity\", ...,\n clockwise = TRUE, steps = 100,\n lineend = \"butt\", linejoin = \"round\", linemitre = 10,\n na.rm = FALSE,\n show.legend = NA, inherit.aes = TRUE) {\n ggplot2::layer(\n data = data,\n mapping = mapping,\n stat = stat,\n geom = GeomPie,\n position = position,\n show.legend = show.legend,\n inherit.aes = inherit.aes,\n params = list(\n lineend = lineend,\n linejoin = linejoin,\n linemitre = linemitre,\n clockwise = clockwise,\n na.rm = na.rm, steps = steps, ...\n )\n )\n}\n\n#' @importFrom grid gpar\n#' @importFrom ggplot2 ggproto aes resolution fill_alpha\n#' @importFrom rlang set_names\nGeomPie <- ggproto(\"GeomPie\",\n ggplot2::GeomPolygon,\n default_aes = aes(\n !!!set_names(\n ggplot2::GeomPolygon$default_aes,\n function(nms) {\n nms <- set_names(nms)\n vec_slice(nms, \"subgroup\") <- \"radius\"\n nms\n }\n ),\n angle0 = 0\n ),\n non_missing_aes = c(\"x\", \"y\", \"angle\", \"angle0\", \"radius\"),\n required_aes = c(\"x\", \"y\", \"angle\"),\n handle_na = ggplot2::Geom$handle_na,\n setup_params = function(self, data, params) {\n steps <- vec_cast(.subset2(params, \"steps\"), integer(),\n x_arg = \"steps\",\n call = call(snake_class(self))\n )\n assert_bool(.subset2(params, \"clockwise\"),\n arg = \"clockwise\", call = call(snake_class(self))\n )\n params$steps <- max(steps, 1L) + 1L\n params\n },\n setup_data = function(data, params) {\n # use the same strategy of geom_bar\n data$radius <- data$radius %||%\n params$radius %||% (\n min(\n vapply(\n split(data$x, data$PANEL, drop = TRUE),\n resolution, numeric(1),\n zero = FALSE,\n USE.NAMES = FALSE\n ),\n vapply(\n split(data$y, data$PANEL, drop = TRUE),\n resolution, numeric(1),\n zero = FALSE,\n USE.NAMES = FALSE\n )\n ) * 0.45)\n data\n },\n draw_panel = function(data, panel_params, coord, steps = 100L,\n clockwise = TRUE, lineend = \"butt\",\n linejoin = \"round\", linemitre = 10) {\n # Expand x, y, radius data to points along circle\n circular_data <- .mapply(\n function(x, y, radius, ang, ang0) {\n if (clockwise) {\n ang0 <- 90 - ang0\n radians <- seq(ang0, ang0 - ang, length.out = steps)[-1L]\n } else {\n ang0 <- 90 + ang0\n radians <- seq(ang0, ang0 + ang, length.out = steps)[-1L]\n }\n radians <- radians / 180 * pi\n data_frame0(\n x = c(x, cos(radians) * radius + x),\n y = c(y, sin(radians) * radius + y)\n )\n },\n list(\n x = data$x, y = data$y,\n radius = data$radius, ang = data$angle, ang0 = data$angle0\n ),\n MoreArgs = NULL\n )\n circular_data <- vec_rbind(!!!circular_data)\n\n # Transform to viewport coords\n circular_data <- coord$transform(circular_data, panel_params)\n\n # Draw as grob\n grid::polygonGrob(\n x = circular_data$x,\n y = circular_data$y,\n id.lengths = rep_len(steps, nrow(data)),\n default.units = \"native\",\n gp = gpar(\n col = data$colour,\n fill = fill_alpha(data$fill, data$alpha),\n lwd = data$linewidth,\n lty = data$linetype,\n lineend = lineend,\n linejoin = linejoin,\n linemitre = linemitre\n )\n )\n }\n)\n"], ["/ggalign/R/layout-heatmap-build.R", "#' @export\nquad_build.HeatmapLayout <- function(quad, schemes = NULL, theme = NULL,\n direction = NULL) {\n ans <- NextMethod()\n\n # add heatmap filling in the first layer --------------\n if (!is.null(filling <- quad@filling)) {\n # we always ensure the filling layer has a fill mapping\n if (is.null(.subset2(ans$plots$main$mapping, \"fill\"))) {\n mapping <- aes(.data$.x, .data$.y, fill = .data$value)\n } else {\n mapping <- aes(.data$.x, .data$.y)\n }\n if (is.waive(filling)) {\n if (nrow(quad@data) * ncol(quad@data) > 20000L) {\n cli_inform(c(\">\" = \"heatmap built with {.fn geom_raster}\"))\n filling <- \"raster\"\n } else {\n cli_inform(c(\">\" = \"heatmap built with {.fn geom_tile}\"))\n filling <- \"tile\"\n }\n }\n ans$plots$main <- ans$plots$main + layer_order(switch(filling,\n raster = ggplot2::geom_raster(mapping = mapping),\n tile = ggplot2::geom_tile(mapping = mapping)\n ))\n }\n # add class to set the default color mapping --------\n ans$plots$main <- add_class(ans$plots$main, \"ggalign_heatmap\")\n ans\n}\n\n#' @importFrom ggplot2 ggplot_build\n#' @export\nggplot_build.ggalign_heatmap <- function(plot, ...) {\n with_options(\n NextMethod(),\n ggplot2.discrete.fill = heatmap_fill(\"discrete\"),\n ggplot2.continuous.fill = heatmap_fill(\"continuous\")\n )\n}\n\nheatmap_fill <- function(type) {\n opt <- sprintf(\"%s.heatmap_%s_fill\", pkg_nm(), type)\n if (is.null(ans <- getOption(opt, default = NULL))) {\n if (type == \"continuous\") {\n ans <- function(...) {\n ggplot2::scale_fill_gradient2(low = \"blue\", high = \"red\")\n }\n } else {\n ans <- getOption(\"ggplot2.discrete.fill\")\n }\n }\n ans\n}\n"], ["/ggalign/R/fortify-data-frame-.R", "#' Build a data frame\n#'\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' This function converts various objects to a data frame.\n#'\n#' @param data An object to be converted to a data frame.\n#' @param ... Arguments passed to methods.\n#' @inheritParams fortify_matrix\n#' @return A data frame.\n#' @eval\n#' rd_collect_family(\"fortify_data_frame\",\n#' \"`fortify_data_frame` method collections\"\n#' )\n#' @export\nfortify_data_frame <- function(data, ..., data_arg = NULL, call = NULL) {\n UseMethod(\"fortify_data_frame\")\n}\n\n#' @inherit fortify_data_frame title description\n#' @param ... Additional arguments passed to [`fortify()`][ggplot2::fortify].\n#' @inheritParams fortify_data_frame\n#' @details\n#' By default, it calls [`fortify()`][ggplot2::fortify] to build the\n#' data frame.\n#' @family fortify_data_frame\n#' @export\nfortify_data_frame.default <- function(data, ..., data_arg = NULL,\n call = NULL) {\n ggplot2::fortify(model = data, ...)\n}\n\n#' @inherit fortify_data_frame.default title description\n#' @param data An object to be converted to a data frame.\n#' @inheritParams rlang::args_dots_empty\n#' @inheritParams fortify_data_frame\n#' @return A data frame with following columns:\n#'\n#' - `.names`: the names for the vector (only applicable if names exist).\n#' - `value`: the actual value of the vector.\n#'\n#' @family fortify_data_frame\n#' @export\nfortify_data_frame.character <- function(data, ..., data_arg = NULL,\n call = NULL) {\n call <- call %||% current_call()\n rlang::check_dots_empty(call = call)\n ans <- list(.names = vec_names(data), value = data)\n if (is.null(.subset2(ans, \".names\"))) ans$.names <- NULL\n new_data_frame(ans)\n}\n\n#' @rdname fortify_data_frame.character\n#' @export\nfortify_data_frame.numeric <- fortify_data_frame.character\n\n#' @rdname fortify_data_frame.character\n#' @export\nfortify_data_frame.logical <- fortify_data_frame.character\n\n#' @rdname fortify_data_frame.character\n#' @export\nfortify_data_frame.complex <- fortify_data_frame.character\n\n#' @export\nfortify_data_frame.waiver <- function(data, ..., data_arg = NULL,\n call = NULL) {\n call <- call %||% current_call()\n rlang::check_dots_empty(call = call)\n data\n}\n\n#' @export\nfortify_data_frame.NULL <- fortify_data_frame.waiver\n\n#' @inherit fortify_data_frame.default title description\n#' @param data An object to be converted to a data frame.\n#' @inheritParams fortify_data_frame\n#' @return A data frame with at least following columns:\n#'\n#' - `seqnames`: The sequence (e.g., chromosome) names.\n#' - `start`: The start positions of the ranges.\n#' - `end`: The end positions of the ranges.\n#' - `width`: The width of each range.\n#'\n#' @family fortify_data_frame\n#' @export\nfortify_data_frame.GRanges <- function(data, ..., data_arg = NULL,\n call = NULL) {\n as.data.frame(data, ...)\n}\n\n#' @inherit fortify_data_frame.default title description\n#' @param data A matrix-like object.\n#' @param lvls A logical value indicating whether to restore factor levels using\n#' those stored in [`ggalign_lvls()`], or a character vector specifying custom\n#' levels for the `value` column. If levels are provided or restored, the\n#' `value` column will be returned as a factor.\n#' @inheritParams rlang::args_dots_empty\n#' @inheritParams fortify_data_frame\n#' @return\n#' Matrix will be transformed into a long-form data frame, where each row\n#' represents a unique combination of matrix indices and their corresponding\n#' values. The resulting data frame will contain the following columns:\n#'\n#' - `.row_names` and `.row_index`: the row names (only applicable when names\n#' exist) and an integer representing the row index of the original matrix.\n#'\n#' - `.column_names` and `.column_index`: the column names (only applicable\n#' when names exist) and column index of the original matrix.\n#'\n#' - `value`: the matrix value, returned as a factor if levels are specified or\n#' restored.\n#'\n#' @family fortify_data_frame\n#' @export\nfortify_data_frame.matrix <- function(data, lvls = NULL, ...,\n data_arg = NULL, call = NULL) {\n call <- call %||% current_call()\n rlang::check_dots_empty(call = call)\n row_nms <- vec_names(data)\n col_nms <- colnames(data)\n if (isFALSE(lvls)) {\n lvls <- NULL\n } else if (isTRUE(lvls)) {\n lvls <- ggalign_lvls_get(lvls)\n } else if (!is.null(lvls) && !is.character(lvls)) {\n cli_abort(\n \"{.arg lvls} must be a single boolean value or a character\",\n call = call\n )\n }\n data <- new_data_frame(list(\n .row_index = vec_rep(seq_len(nrow(data)), ncol(data)),\n .column_index = vec_rep_each(seq_len(ncol(data)), nrow(data)),\n value = c(data)\n ))\n if (!is.null(row_nms)) data$.row_names <- row_nms[data$.row_index]\n if (!is.null(col_nms)) data$.column_names <- col_nms[data$.column_index]\n if (!is.null(lvls)) data$value <- factor(data$value, levels = lvls)\n data\n}\n\n#' @export\n#' @rdname fortify_data_frame.matrix\nfortify_data_frame.DelayedMatrix <- function(data, ...) {\n fortify_data_frame(as.matrix(data), ...)\n}\n\n#' @export\n#' @rdname fortify_data_frame.matrix\nfortify_data_frame.Matrix <- function(data, ...) {\n fortify_data_frame(as.matrix(data), ...)\n}\n"], ["/ggalign/R/grid-utils.R", "#' @importFrom grid gpar\n#' @export\ngrid::gpar\n\n#' @importFrom grid unit\n#' @export\ngrid::unit\n\nis.gList <- function(x) inherits(x, \"gList\")\n\nis.gTree <- function(x) inherits(x, \"gTree\")\n\n#' @importFrom grid unitType absolute.size\nis_absolute_unit <- function(x) unitType(absolute.size(x)) != \"null\"\n\n#' @importFrom grid unitType\nis_null_unit <- function(x) unitType(x) == \"null\"\n\nis_null_grob <- function(x) inherits(x, c(\"zeroGrob\", \"null\"))\n\n#' @importFrom grid is.grob nullGrob\nensure_grob <- function(x, default = nullGrob()) {\n if (is.gList(x)) x <- gTree(children = x)\n if (is.grob(x)) x else default\n}\n\n# `current.transform()` transforms from *inches* within the current viewport to\n# *inches* on the overall device.\ngrid_solve_loc <- function(loc, trans, valueOnly = FALSE) {\n x <- grid::convertX(loc$x, \"inches\", valueOnly = TRUE)\n y <- grid::convertY(loc$y, \"inches\", valueOnly = TRUE)\n out <- matrix(c(x, y, rep_len(1, length(x))), ncol = 3L) %*%\n trans\n out <- list(x = out[, 1L, drop = TRUE], y = out[, 2L, drop = TRUE])\n if (!valueOnly) out <- lapply(out, unit, \"inches\")\n out\n}\n\nloc_device2vp <- function(x, y, valueOnly = FALSE) {\n assert_s3_class(x, \"unit\")\n assert_s3_class(y, \"unit\")\n if (length(x) != length(y)) {\n cli_abort(\"{.arg x} and {.arg y} must have the same length\")\n }\n assert_bool(valueOnly)\n grid_solve_loc(\n list(x = x, y = y),\n solve(grid::current.transform()),\n valueOnly = valueOnly\n )\n}\n\nloc_vp2device <- function(x, y, valueOnly = FALSE) {\n assert_s3_class(x, \"unit\")\n assert_s3_class(y, \"unit\")\n if (length(x) != length(y)) {\n cli_abort(\"{.arg x} and {.arg y} must have the same length\")\n }\n assert_bool(valueOnly)\n grid::deviceLoc(x, y, valueOnly = valueOnly)\n}\n\n# # allow the missing value in the unit for `str` method\n# ggalign_unit <- function(x, ...) UseMethod(\"ggalign_unit\")\n# #' @export\n# ggalign_unit.default <- function(x, ...) ggalign_unit(as.numeric(x), ...)\n# #' @export\n# ggalign_unit.numeric <- function(x, units = \"null\", data = NULL, ...) {\n# add_class(unit(x, units, data = data), \"ggalign_unit\")\n# }\n# #' @export\n# ggalign_unit.unit <- function(x, ...) add_class(x, \"ggalign_unit\")\n# is_ggalign_unit <- function(x) inherits(x, \"ggalign_unit\")\n\n# # allow the missing value in the unit for `str` method\n#' @importFrom utils str\n#' @export\nstr.unit <- function(object, ...) obj_str(object, ...)\n\n#' @export\nvec_ptype_abbr.unit <- function(x, ...) fclass(x)\n\n#' @importFrom utils str\n#' @export\nobj_str_footer.unit <- function(x, ..., indent.str = \" \", nest.lev = 0,\n give.attr = TRUE) {\n if (!isTRUE(give.attr)) {\n return(invisible(x))\n }\n attr <- attributes(x)\n attr[[\"class\"]] <- NULL\n attr[[\"names\"]] <- NULL\n if (length(attr) == 0) {\n return(invisible(x))\n }\n indent.str <- paste0(\" \", indent.str)\n for (nm in names(attr)) {\n cat(indent.str, paste0(\"- attr(*, \\\"\", nm, \"\\\"):\"), sep = \"\")\n str(\n attr[[nm]],\n no.list = TRUE, ...,\n nest.lev = nest.lev + 1L,\n indent.str = indent.str\n )\n }\n invisible(x)\n}\n\n#' @importFrom gtable gtable_trim\nsubset_gt <- function(gt, index, trim = TRUE) {\n gt$layout <- vec_slice(.subset2(gt, \"layout\"), index)\n gt$grobs <- .subset(.subset2(gt, \"grobs\"), index)\n if (trim) gtable_trim(gt) else gt\n}\n\ngtable_trim_widths <- function(gt) {\n layout <- .subset2(gt, \"layout\")\n w <- range(.subset2(layout, \"l\"), .subset2(layout, \"r\"))\n gt$widths <- .subset2(gt, \"widths\")[seq.int(w[1L], w[2L])]\n if (is.matrix(respect <- .subset2(gt, \"respect\"))) {\n respect <- respect[, seq.int(w[1L], w[2L]), drop = FALSE]\n if (all(respect == 0L)) respect <- FALSE\n gt$respect <- respect\n }\n layout$l <- .subset2(layout, \"l\") - w[1L] + 1L\n layout$r <- .subset2(layout, \"r\") - w[1L] + 1L\n gt$layout <- layout\n gt\n}\n\ngtable_trim_heights <- function(gt) {\n layout <- .subset2(gt, \"layout\")\n h <- range(.subset2(layout, \"t\"), .subset2(layout, \"b\"))\n gt$heights <- .subset2(gt, \"heights\")[seq.int(h[1L], h[2L])]\n if (is.matrix(respect <- .subset2(gt, \"respect\"))) {\n respect <- respect[seq.int(h[1L], h[2L]), , drop = FALSE]\n if (all(respect == 0L)) respect <- FALSE\n gt$respect <- respect\n }\n layout$t <- .subset2(layout, \"t\") - h[1L] + 1L\n layout$b <- .subset2(layout, \"b\") - h[1L] + 1L\n gt$layout <- layout\n gt\n}\n\nliberate_area <- function(gt, top, left, bottom, right,\n clip = \"inherit\", name = NULL, vp = NULL) {\n if (any(remove <- grob_in_area(gt, top, right, bottom, left))) {\n liberated <- gt[top:bottom, left:right]\n if (is.function(vp <- allow_lambda(vp))) {\n liberated$vp <- vp(liberated)\n } else if (inherits(vp, \"viewport\")) {\n liberated$vp <- vp\n }\n liberated$respect <- FALSE\n name <- name %||%\n paste(\n .subset2(.subset2(liberated, \"layout\"), \"name\"),\n collapse = \"; \"\n )\n gt <- subset_gt(gt, !remove, trim = FALSE)\n gt <- gtable_add_grob(\n gt,\n list(liberated),\n top,\n left,\n bottom,\n right,\n z = max(.subset2(.subset2(liberated, \"layout\"), \"z\")),\n clip = clip,\n name = name\n )\n }\n gt\n}\n\ngrob_in_area <- function(gt, top, right, bottom, left) {\n .subset2(.subset2(gt, \"layout\"), \"l\") >= left &\n .subset2(.subset2(gt, \"layout\"), \"t\") >= top &\n .subset2(.subset2(gt, \"layout\"), \"r\") <= right &\n .subset2(.subset2(gt, \"layout\"), \"b\") <= bottom\n}\n\ncompute_null_width <- function(x, unitTo = \"mm\", valueOnly = FALSE) {\n compute_null_unit(x, \"width\", unitTo = unitTo, valueOnly = valueOnly)\n}\n\ncompute_null_height <- function(x, unitTo = \"mm\", valueOnly = FALSE) {\n compute_null_unit(x, \"height\", unitTo = unitTo, valueOnly = valueOnly)\n}\n\n#' @importFrom grid unit convertHeight convertWidth\ncompute_null_unit <- function(x, type = c(\"width\", \"height\"), unitTo = \"mm\",\n valueOnly = FALSE) {\n null <- is_null_unit(x) # null unit\n if (type == \"width\") {\n ans <- convertWidth(x, unitTo, valueOnly = TRUE)\n total <- convertWidth(unit(1, \"npc\"), unitTo = unitTo, valueOnly = TRUE)\n } else {\n ans <- convertHeight(x, unitTo, valueOnly = TRUE)\n total <- convertHeight(\n unit(1, \"npc\"),\n unitTo = unitTo,\n valueOnly = TRUE\n )\n }\n if (any(null)) {\n null_size <- total - sum(ans[!null])\n # other units in the same row/ column also have unit null\n coef <- as.numeric(x[null])\n ans[null] <- (null_size / sum(coef)) * coef\n }\n if (!valueOnly) ans <- unit(ans, unitTo)\n ans\n}\n"], ["/ggalign/R/ggplot-coord-circle.R", "#' Polar Coordinates with Enhanced Controls\n#'\n#' An extended version of [`coord_radial()`][ggplot2::coord_radial], providing\n#' additional customization options.\n#'\n#' @inheritParams ggplot2::coord_radial\n#' @param thetalim,rlim Limits for the `theta` and `r` axes.\n#' @param inner.radius A numeric in `[0, 1)` indicates the inner radius.\n#' @param outer.radius A numeric in `(0, 1]` indicates the outer radius.\n#' [`coord_radial()`][ggplot2::coord_radial] by default uses `0.8`.\n#' @examples\n#' ggplot(mtcars, aes(disp, mpg)) +\n#' geom_point() +\n#' coord_circle(\n#' start = -0.4 * pi, end = 0.4 * pi,\n#' inner.radius = 0.3, outer.radius = 1\n#' )\n#' ggplot(mtcars, aes(disp, mpg)) +\n#' geom_point() +\n#' coord_circle(\n#' start = -0.4 * pi, end = 0.4 * pi,\n#' inner.radius = 0.3, outer.radius = 0.5\n#' )\n#' @importFrom ggplot2 ggproto\n#' @importFrom rlang arg_match0\n#' @export\ncoord_circle <- function(theta = \"x\", start = 0, end = NULL,\n thetalim = NULL, rlim = NULL, expand = FALSE,\n direction = 1, clip = \"off\",\n r.axis.inside = NULL, rotate.angle = FALSE,\n inner.radius = 0, outer.radius = 0.95) {\n theta <- arg_match0(theta, c(\"x\", \"y\"))\n assert_number_decimal(start, allow_infinite = FALSE)\n assert_number_decimal(end, allow_infinite = FALSE, allow_null = TRUE)\n if (packageVersion(\"ggplot2\") <= \"3.5.2\") {\n assert_bool(expand)\n }\n clip <- arg_match0(clip, c(\"off\", \"on\"))\n\n valid_inside_axis <- .rlang_check_bool(r.axis.inside,\n allow_null = TRUE\n ) ||\n .rlang_check_number(r.axis.inside,\n allow_decimal = TRUE, allow_infinite = FALSE\n ) == 0L\n if (!valid_inside_axis) {\n cli_abort(\n \"{.arg r.axis.inside} must be a single boolean value or a number\"\n )\n }\n\n assert_bool(rotate.angle)\n assert_number_decimal(inner.radius,\n min = 0, max = 1,\n allow_infinite = FALSE\n )\n assert_number_decimal(outer.radius,\n min = 0, max = 1,\n allow_infinite = FALSE\n )\n if (inner.radius >= outer.radius) {\n cli_abort(\n \"{.arg outer.radius} must be larger than {.arg inner.radius}\"\n )\n }\n r <- if (theta == \"x\") \"y\" else \"x\"\n\n arc <- c(start, end %||% (start + 2 * pi))\n if (arc[1] > arc[2]) {\n n_rotate <- ((arc[1] - arc[2]) %/% (2 * pi)) + 1\n arc[1] <- arc[1] - n_rotate * 2 * pi\n }\n r.axis.inside <- r.axis.inside %||% !(abs(arc[2] - arc[1]) >= 1.999 * pi)\n inner_radius <- c(inner.radius, outer.radius) / 2\n\n ggproto(NULL, CoordCircle,\n limits = list(theta = thetalim, r = rlim),\n theta = theta,\n r = r,\n arc = arc,\n expand = expand,\n direction = sign(direction),\n r_axis_inside = r.axis.inside,\n rotate_angle = rotate.angle,\n inner_radius = inner_radius,\n clip = clip\n )\n}\n\n#' @importFrom ggplot2 ggproto_parent\ncircle_panel_params <- function(self, scale_x, scale_y, params = list()) {\n out <- ggproto_parent(ggplot2::CoordRadial, self)$setup_panel_params(\n scale_x, scale_y, params\n )\n if (packageVersion(\"ggplot2\") <= \"3.5.2\") {\n if (self$theta == \"x\") {\n xlimits <- self$limits$theta\n ylimits <- self$limits$r\n } else {\n xlimits <- self$limits$r\n ylimits <- self$limits$theta\n }\n new <- c(\n view_scales_polar(\n scale_x, self$theta, xlimits,\n expand = params$expand[c(4, 2)] %||% self$expand\n ),\n view_scales_polar(\n scale_y, self$theta, ylimits,\n expand = params$expand[c(3, 1)] %||% self$expand\n )\n )\n out[names(new)] <- new\n }\n out$bbox <- ggfun(\"polar_bbox\")(\n self$arc, margin = c(0, 0, 0, 0),\n inner_radius = self$inner_radius\n )\n out\n}\n\nview_scales_polar <- function(scale, theta, coord_limits, expand = TRUE) {\n aesthetic <- scale$aesthetics[1]\n is_theta <- theta == aesthetic\n name <- if (is_theta) \"theta\" else \"r\"\n expansion <- ggfun(\"default_expansion\")(scale, expand = expand)\n limits <- scale$get_limits()\n continuous_range <- ggfun(\"expand_limits_scale\")(\n scale, expansion, limits, coord_limits = coord_limits\n )\n primary <- ggfun(\"view_scale_primary\")(scale, limits, continuous_range)\n view_scales <- list(\n primary,\n sec = ggfun(\"view_scale_secondary\")(scale, limits, continuous_range),\n major = primary$map(primary$get_breaks()),\n minor = primary$map(primary$get_breaks_minor()),\n range = continuous_range\n )\n names(view_scales) <- c(name, paste0(name, \".\", names(view_scales)[-1]))\n view_scales\n}\n\n#' @importFrom ggplot2 ggproto\nCoordCircle <- ggproto(\n \"CoordCircle\", ggplot2::CoordRadial,\n setup_panel_params = circle_panel_params\n)\n"], ["/ggalign/R/alignpatch-build.R", "#' @importFrom grid grid.draw\n#' @importFrom rlang try_fetch cnd_signal\n#' @export\nprint.alignpatches <- function(x, newpage = is.null(vp), vp = NULL, ...) {\n ggplot2::set_last_plot(x)\n if (newpage) {\n grid::grid.newpage()\n if (is.character(vp)) {\n cli_abort(c(\n \"{.arg vp} cannot be a character string when {.arg newpage} is TRUE.\",\n i = \"Please provide a viewport object or set {.arg newpage} to FALSE.\"\n ))\n }\n }\n if (!is.null(vp)) {\n if (is.character(vp)) {\n cur <- grid::current.viewport()$name\n grid::seekViewport(vp)\n if (!identical(cur, \"ROOT\")) on.exit(grid::seekViewport(cur))\n } else {\n grid::pushViewport(vp)\n on.exit(grid::upViewport())\n }\n }\n\n # render the plot\n try_fetch(\n grid.draw(x, ...),\n error = function(e) {\n if (inherits(e, \"simpleError\") &&\n deparse(conditionCall(e)[[1L]]) == \"grid.Call\") {\n error_name <- obj_type_friendly(x)\n if (Sys.getenv(\"RSTUDIO\") == \"1\") {\n cli_abort(c(paste(\n \"The RStudio {.field Plots} window may be\",\n \"too small to show\", error_name\n ), i = \"Please make the window larger.\"), parent = e)\n } else {\n cli_abort(c(\n \"The viewport may be too small to show {error_name}.\",\n i = \"Please make the window larger.\"\n ), parent = e)\n }\n }\n cnd_signal(e)\n }\n )\n invisible(x)\n}\n\n#' @importFrom grid grid.draw\n#' @exportS3Method\ngrid.draw.alignpatches <- function(x, recording = TRUE) {\n grid.draw(ggalignGrob(x), recording = recording)\n}\n\n#' @export\nggalign_build.alignpatches <- function(x) x\n\n#' @importFrom ggplot2 find_panel element_render theme theme_get\n#' @importFrom gtable gtable_add_grob gtable_add_rows gtable_add_cols\n#' @importFrom rlang arg_match0\n#' @importFrom S7 prop\n#' @export\nggalign_gtable.alignpatches <- function(x) {\n titles <- prop(x, \"titles\")\n\n # ensure theme has no missing value\n theme <- prop(x, \"theme\") %||% theme_get()\n\n # `TO-DO`: use `complete_theme()` from ggplot2 release\n theme <- complete_theme(theme)\n attr(x, \"theme\") <- theme # bypass the setter function\n table <- alignpatch(x)$patch_gtable(top_level = TRUE)\n\n fix_respect <- is.matrix(.subset2(table, \"respect\"))\n\n # Add title, subtitle, and caption -------------------\n # https://github.com/tidyverse/ggplot2/blob/2e08bba0910c11a46b6de9e375fade78b75d10dc/R/plot-build.R#L219C3-L219C9\n title <- element_render(\n theme = theme, \"plot.title\", .subset2(titles, \"title\"),\n margin_y = TRUE, margin_x = TRUE\n )\n title_height <- grobHeight(title)\n\n # Subtitle\n subtitle <- element_render(\n theme, \"plot.subtitle\", .subset2(titles, \"subtitle\"),\n margin_y = TRUE, margin_x = TRUE\n )\n subtitle_height <- grobHeight(subtitle)\n\n # caption\n caption <- element_render(\n theme, \"plot.caption\", .subset2(titles, \"caption\"),\n margin_y = TRUE, margin_x = TRUE\n )\n caption_height <- grobHeight(caption)\n\n # positioning of title and subtitle is governed by plot.title.position\n # positioning of caption is governed by plot.caption.position\n # \"panel\" means align to the panel(s)\n # \"plot\" means align to the entire plot (except margins and tag)\n panel_pos <- find_panel(table)\n title_pos <- arg_match0(\n theme$plot.title.position %||% \"panel\",\n c(\"panel\", \"plot\"),\n arg_nm = \"plot.title.position\",\n error_call = quote(theme())\n )\n\n caption_pos <- arg_match0(\n theme$plot.caption.position %||% \"panel\",\n values = c(\"panel\", \"plot\"),\n arg_nm = \"plot.caption.position\",\n error_call = quote(theme())\n )\n if (title_pos == \"panel\") {\n title_l <- panel_pos$l\n title_r <- panel_pos$r\n } else {\n title_l <- 1L\n title_r <- ncol(table)\n }\n if (caption_pos == \"panel\") {\n caption_l <- panel_pos$l\n caption_r <- panel_pos$r\n } else {\n caption_l <- 1L\n caption_r <- ncol(table)\n }\n\n table <- gtable_add_rows(table, subtitle_height, pos = 0)\n table <- gtable_add_grob(table, subtitle,\n name = \"subtitle\",\n t = 1, b = 1, l = title_l, r = title_r, clip = \"off\"\n )\n\n table <- gtable_add_rows(table, title_height, pos = 0)\n table <- gtable_add_grob(table, title,\n name = \"title\",\n t = 1, b = 1, l = title_l, r = title_r, clip = \"off\"\n )\n\n table <- gtable_add_rows(table, caption_height, pos = -1)\n table <- gtable_add_grob(table, caption,\n name = \"caption\",\n t = -1, b = -1, l = caption_l, r = caption_r, clip = \"off\"\n )\n if (fix_respect) {\n table$respect <- rbind(0L, 0L, table$respect, 0L)\n }\n\n # add margins --------------------------------------\n plot_margin <- calc_element(\"plot.margin\", theme)\n\n table <- gtable_add_rows(table, plot_margin[1L], 0L)\n table <- gtable_add_rows(table, plot_margin[3L])\n if (fix_respect) table$respect <- rbind(0L, table$respect, 0L)\n table <- gtable_add_cols(table, plot_margin[2L], 0L)\n table <- gtable_add_cols(table, plot_margin[4L])\n if (fix_respect) table$respect <- cbind(0L, table$respect, 0L)\n\n # add background -----------------------------------\n if (inherits(theme$plot.background, \"element\")) {\n table <- gtable_add_grob(table,\n element_render(theme, \"plot.background\"),\n t = 1L, l = 1L, b = -1L, r = -1L, name = \"background\", z = -Inf\n )\n table$layout <- table$layout[\n c(nrow(table$layout), 1:(nrow(table$layout) - 1L)),\n ]\n table$grobs <- table$grobs[\n c(nrow(table$layout), 1:(nrow(table$layout) - 1L))\n ]\n }\n table\n}\n"], ["/ggalign/R/ggplot-geom-draw.R", "#' Layer with Grid or Function\n#'\n#' Draw a ggplot2 layer using a grob or a function.\n#'\n#' @param draw Either a [grob][grid::grob] object or a function (can be\n#' purrr-style) that accepts at least one argument (a data frame of\n#' transformed coordinates) and returns a [grob][grid::grob].\n#'\n#' @param type A single string of `r oxford_or(c(\"group\", \"panel\"))`, `\"group\"`\n#' draws geoms with `draw_group`, which displays multiple observations as one\n#' geometric object, and `\"panel\"` draws geoms with `draw_panel`, displaying\n#' individual graphical objects for each observation (row). Default:\n#' `\"group\"`.\n#'\n#' @inheritParams ggplot2::layer\n#' @inheritParams ggplot2::geom_point\n#' @details If you want to combine the functionality of multiple geoms, it can\n#' typically be achieved by preparing the data for each geom inside the\n#' `draw_*()` call and sending it off to the different geoms, collecting the\n#' output in a [`grid::gList`] (a list of grobs) for `draw_group()` or a\n#' [`grid::gTree`] (a grob containing multiple child grobs) for\n#' `draw_panel()`.\n#' @seealso \n#' @examples\n#' text <- grid::textGrob(\n#' \"ggdraw\",\n#' x = c(0, 0, 0.5, 1, 1),\n#' y = c(0, 1, 0.5, 0, 1),\n#' hjust = c(0, 0, 0.5, 1, 1),\n#' vjust = c(0, 1, 0.5, 0, 1)\n#' )\n#' ggplot(data.frame(x = 1, y = 2)) +\n#' geom_draw(text)\n#' @importFrom rlang list2 arg_match0\n#' @importFrom ggplot2 ggproto aes\n#' @export\ngeom_draw <- function(draw, mapping = NULL, data = NULL,\n type = \"group\", stat = \"identity\",\n position = \"identity\", ...,\n na.rm = FALSE, show.legend = FALSE, inherit.aes = TRUE) {\n type <- arg_match0(type, c(\"group\", \"panel\"))\n if (!is.grob(draw) && !is.gList(draw)) draw <- rlang::as_function(draw)\n dots <- list2(...)\n ggplot2::layer(\n data = data,\n mapping = mapping,\n stat = stat,\n geom = switch(type,\n panel = ggproto(\n \"GeomDraw\",\n ggplot2::Geom,\n default_aes = GeomGshape$default_aes,\n setup_data = draw_setup_data,\n draw_panel = draw_geom_draw,\n draw_key = ggplot2::draw_key_blank\n ),\n group = ggproto(\n \"GeomDraw\",\n ggplot2::Geom,\n default_aes = GeomGshape$default_aes,\n setup_data = draw_setup_data,\n draw_group = draw_geom_draw,\n draw_key = ggplot2::draw_key_blank\n )\n ),\n position = position,\n show.legend = show.legend,\n inherit.aes = inherit.aes,\n params = c(\n list(na.rm = na.rm, draw = draw, .__draw_dots__ = dots), dots\n )\n )\n}\n\n# GeomTile will respect width and height\ndraw_setup_data <- function(self, data, params) {\n data$x <- data$x %||% 0.5\n data$y <- data$y %||% 0.5\n ggplot2::GeomTile$setup_data(data, params)\n}\n\ndraw_geom_draw <- function(data, panel_params, coord, draw, .__draw_dots__) {\n if (is.function(draw)) {\n data <- coord$transform(data, panel_params)\n # restore colour\n if (!is.null(data$colour) && is.null(data$color)) {\n data$color <- data$colour\n }\n if (!is.null(data$color) && is.null(data$colour)) {\n data$colour <- data$color\n }\n\n # restore width and height\n if (!is.null(data$xmin) && !is.null(data$xmax)) {\n data$width <- data$xmax - data$xmin\n }\n if (!is.null(data$ymin) && !is.null(data$ymax)) {\n data$height <- data$ymax - data$ymin\n }\n }\n make_draw_grob(draw, data, .__draw_dots__)\n}\n\n#' @return A [grob][grid::grob] object.\n#' @importFrom rlang inject\n#' @importFrom methods formalArgs\n#' @importFrom ggplot2 zeroGrob\n#' @keywords internal\n#' @noRd\nmake_draw_grob <- function(draw, data, dots) {\n if (is.function(draw)) {\n args <- formalArgs(draw)\n if (any(args == \"...\")) {\n draw <- inject(draw(!!!data, !!!dots))\n } else {\n draw <- inject(draw(\n !!!.subset(data, intersect(names(data), args)),\n !!!.subset(dots, intersect(\n setdiff(names(dots), names(data)), args\n ))\n ))\n }\n }\n ensure_grob(draw, zeroGrob())\n}\n"], ["/ggalign/R/fortify-matrix-list.R", "#' Convert the shape of a list for fortify method\n#'\n#' @param data A list\n#' @param shape Not used currently.\n#' @seealso [`fortify_matrix.list_upset()`]\n#' @family tune\n#' @export\ntune.list <- function(data, shape = NULL) {\n if (!is.null(shape)) {\n cli_abort(\"{.arg shape} cannot be used currently for {.cls list} object\")\n }\n new_tune(data, class = \"list_upset\")\n}\n\n#' Build a Matrix for UpSet plot\n#'\n#' @description\n#' `r lifecycle::badge('experimental')`\n#'\n#' This function converts a list into a matrix format suitable for creating an\n#' UpSet plot. It always returns a matrix for a `horizontal` UpSet plot.\n#' @inheritParams rlang::args_dots_empty\n#' @param data A list of sets.\n#' @param mode A string of `r oxford_or(c(\"distinct\", \"intersect\", \"union\"))`\n#' indicates the mode to define the set intersections. Check\n#' \n#' for details.\n#' @inheritParams fortify_matrix\n#' @section ggalign attributes:\n#' - `intersection_sizes`: An integer vector indicating the size of each\n#' intersection.\n#' - `set_sizes`: An integer vector indicating the size of each set.\n#' @seealso [`tune.list()`]\n#' @family fortify_matrix\n#' @aliases fortify_matrix.list\n#' @export\nfortify_matrix.list_upset <- function(data, mode = \"distinct\", ...,\n data_arg = NULL, call = NULL) {\n call <- call %||% current_call()\n rlang::check_dots_empty(call = call)\n mode <- arg_match0(mode, c(\"distinct\", \"intersect\", \"union\"),\n error_call = call\n )\n data <- lapply(tune_data(data), function(x) {\n vec_unique(vec_slice(x, !vec_detect_missing(x)))\n })\n data <- list_drop_empty(data)\n if (length(data) == 0L) {\n cli::cli_abort(\n \"No valid data: All input lists are either empty or contain only missing values.\",\n call = call\n )\n }\n\n # Based on the explanation from\n # https://jokergoo.github.io/ComplexHeatmap-reference/book/upset-plot.html\n action <- switch(mode,\n distinct = function(data, intersection) {\n out <- NULL\n for (i in which(intersection)) {\n if (is.null(out)) {\n out <- .subset2(data, i)\n } else if (vec_size(out) == 0L) { # early exit for empty items\n return(out)\n } else {\n out <- vec_set_intersect(out, .subset2(data, i))\n }\n }\n for (i in which(!intersection)) {\n if (vec_size(out) == 0L) { # early exit for empty items\n return(out)\n }\n out <- vec_set_difference(out, .subset2(data, i))\n }\n return(out)\n },\n intersect = function(data, intersection) {\n out <- NULL\n for (i in which(intersection)) {\n if (is.null(out)) {\n out <- .subset2(data, i)\n } else if (vec_size(out) == 0L) { # early exit for empty items\n return(out)\n } else {\n out <- vec_set_intersect(out, .subset2(data, i))\n }\n }\n out\n },\n union = function(data, intersection) {\n Reduce(vec_set_union, .subset(data, intersection))\n }\n )\n\n intersection <- logical(vec_size(data)) # template\n intersection_and_size <- lapply(\n seq_len(vec_size(intersection)),\n function(n) {\n # generate all possible intersections\n utils::combn(vec_size(intersection), n, function(index) {\n intersection[index] <- TRUE\n list(\n intersection = intersection,\n # for each intersection, we define the size\n size = vec_size(action(data, intersection))\n )\n }, simplify = FALSE)\n }\n )\n\n # https://en.wikipedia.org/wiki/UpSet_plot\n # UpSets can be used horizontally and vertically.\n # In a vertical UpSet plot, the columns of the matrix correspond to the\n # sets, the rows correspond to the intersections.\n # we by default use `horizontal` upset, the rows of the matrix correspond\n # to the sets, the columns correspond to the intersections.\n ans <- list_transpose(unlist(intersection_and_size, FALSE, FALSE))\n intersections <- inject(cbind(!!!.subset2(ans, \"intersection\")))\n rownames(intersections) <- names(data)\n intersection_sizes <- unlist(.subset2(ans, \"size\"), FALSE, FALSE)\n keep <- intersection_sizes > 0L # remove intersection without items\n intersections <- intersections[, keep, drop = FALSE]\n intersection_sizes <- intersection_sizes[keep]\n ggalign_data_set(intersections,\n intersection_sizes = intersection_sizes,\n set_sizes = list_sizes(data),\n upset_mode = mode\n )\n}\n"], ["/ggalign/R/layout-quad-switch.R", "#' Determine the Active Context of Quad-Layout\n#'\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' - `quad_active`: Sets the active context to the `r rd_quad()` itself.\n#' - `quad_anno`: Sets the active context to the specified annotation stack\n#' based on the `position` argument.\n#' - `anno_top`: A special case of `quad_anno` with `position = \"top\"`.\n#' - `anno_left`: A special case of `quad_anno` with `position = \"left\"`.\n#' - `anno_bottom`: A special case of `quad_anno` with `position = \"bottom\"`.\n#' - `anno_right`: A special case of `quad_anno` with `position = \"right\"`.\n#'\n#' @inheritParams quad_layout\n#' @return An object that can be added to `r rd_quad()`.\n#' @export\n#' @rdname quad_active\nquad_active <- function(width = NULL, height = NULL) {\n if (!is.null(width)) width <- check_size(width)\n if (!is.null(height)) height <- check_size(height)\n structure(\n list(width = width, height = height),\n class = c(\"quad_active\", \"quad_switch\")\n )\n}\n\n#' @details\n#' By default, `quad_anno()` attempts to initialize the annotation stack layout\n#' using data from `r rd_quad()`. However, in situations where you want to use\n#' different data for the annotation stack, you can set `initialize = FALSE`\n#' and then provide a custom `stack_layout()`.\n#'\n#' @param position `r rd_quad_position(\"activated\")`.\n#' @param size A numeric value or an [`unit`][grid::unit] object to set the\n#' total `height`/`width` of the annotation stack.\n#' - If `position` is `\"top\"` or `\"bottom\"`, `size` sets the total height of\n#' the annotation.\n#' - If `position` is `\"left\"` or `\"right\"`, `size` sets the total width of the\n#' annotation.\n#' @param free_guides Override the `guides` collection behavior specified in the\n#' `r rd_quad()` for the annotation stack.\n#' @param initialize A boolean indicating whether the annotation stack should be\n#' initialized if it is not already. By default, the annotation stack layout\n#' will attempt to initialize when the data is compatible. If set to `TRUE`, and\n#' the data in `r rd_quad()` is incompatible with the annotation stack, no\n#' data will be used in the stack.\n#' @param what What should get activated in the annotation stack?\n#' `r rd_chain_what()`.\n#' @seealso [`quad_switch()`]\n#' @export\n#' @rdname quad_active\nquad_anno <- function(position, size = NULL, free_guides = waiver(),\n initialize = NULL, what = waiver()) {\n if (is.null(position)) {\n cli_abort(c(\n paste(\n \"{.arg position} must be a single string of\",\n \"{oxford_or(.TLBR)}, not `NULL`\"\n ),\n i = \"Do you want to set the active context to the `quad_layout()` with {.fn quad_active}?\"\n ))\n }\n position <- match.arg(position, .TLBR)\n quad_switch_anno(\n size = size, free_guides = free_guides,\n initialize = initialize, what = what,\n position = position\n )\n}\n\n#' @export\n#' @rdname quad_active\nanno_top <- function(size = NULL, free_guides = waiver(), initialize = NULL,\n what = waiver()) {\n quad_switch_anno(\n size = size, free_guides = free_guides,\n initialize = initialize, what = what,\n position = \"top\"\n )\n}\n\n#' @export\n#' @rdname quad_active\nanno_left <- function(size = NULL, free_guides = waiver(), initialize = NULL,\n what = waiver()) {\n quad_switch_anno(\n size = size, free_guides = free_guides,\n initialize = initialize, what = what,\n position = \"left\"\n )\n}\n\n#' @export\n#' @rdname quad_active\nanno_bottom <- function(size = NULL, free_guides = waiver(), initialize = NULL,\n what = waiver()) {\n quad_switch_anno(\n size = size, free_guides = free_guides,\n initialize = initialize, what = what,\n position = \"bottom\"\n )\n}\n\n#' @export\n#' @rdname quad_active\nanno_right <- function(size = NULL, free_guides = waiver(), initialize = NULL,\n what = waiver()) {\n quad_switch_anno(\n size = size, free_guides = free_guides,\n initialize = initialize, what = what,\n position = \"right\"\n )\n}\n\nquad_switch_anno <- function(position, size, free_guides, initialize, what,\n call = caller_call()) {\n if (!is.null(size)) size <- check_size(size, call = call)\n assert_layout_position(free_guides, call = call)\n if (!is.waive(what)) what <- check_stack_context(what, call = call)\n assert_bool(initialize, allow_null = TRUE)\n structure(\n list(\n position = position, size = size,\n free_guides = free_guides, what = what,\n initialize = initialize\n ),\n class = c(\"quad_anno\", \"quad_switch\")\n )\n}\n\n#' Initialize Quad-Layout Annotation\n#'\n#' @description\n#' `r lifecycle::badge(\"deprecated\")`\n#'\n#' This function was deprecated, you can add `stack_layout()` directly.\n#'\n#' @export\n#' @keywords internal\nquad_init <- function(position, data = waiver(), ...) {\n lifecycle::deprecate_stop(\"0.0.6\", \"quad_init()\", \"stack_layout()\")\n}\n\n#' @inherit quad_active title return\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' `quad_switch()` integrates [`quad_active()`] and [`quad_anno()`] into one\n#' function for ease of use. This function allows you to quickly change the\n#' active context of the [`quad_layout()`] and its annotations.\n#'\n#' `hmanno` is an alias for `quad_switch`, with additional arguments for\n#' backward compatibility\n#'\n#' @param position `r rd_quad_position(\"activated\")`. If `NULL`, it sets the\n#' active context to the `r rd_quad()` itself.\n#' @inheritParams rlang::args_dots_empty\n#' @inheritParams quad_active\n#' @examples\n#' ggheatmap(matrix(rnorm(81), nrow = 9)) +\n#' anno_top() +\n#' align_dendro()\n#' @importFrom ggplot2 waiver\n#' @seealso [`quad_active()`]/[`quad_anno()`]\n#' @export\nquad_switch <- function(position = NULL, size = NULL,\n width = NULL, height = NULL, free_guides = waiver(),\n initialize = NULL, what = waiver()) {\n if (is.null(position)) {\n quad_active(width = width, height = height)\n } else {\n position <- match.arg(position, .TLBR)\n quad_switch_anno(\n size = size,\n free_guides = free_guides, what = what,\n initialize = initialize,\n position = position\n )\n }\n}\n\n#' @inheritParams heatmap_layout\n#' @export\n#' @rdname quad_switch\nhmanno <- quad_switch\n"], ["/ggalign/R/craft-cross-none.R", "#' Reset layout ordering and panel group\n#'\n#' @param data The dataset to use for the layout. By default,\n#' [`fortify_matrix()`] will convert the data to a matrix. This argument\n#' allows you to change the layout data. If not specified, the original data\n#' will be used.\n#' @param ... <[dyn-dots][rlang::dyn-dots]> Additional arguments passed to\n#' [`fortify_matrix()`].\n#' @param inherit_index A boolean value indicating whether to inherit the\n#' ordering index. If `TRUE`, will match the layout ordering index with the\n#' data names.\n#' @param inherit_panel A boolean value indicating whether to inherit the\n#' panel group. If `TRUE`, will match the layout panel with the data names.\n#' @param inherit_nobs A boolean value indicating whether to inherit the\n#' number of observations (nobs). If `TRUE`, the `data` input must be\n#' compatible with the layout data.\n#' @export\ncross_none <- function(data = waiver(), ...,\n inherit_index = NULL,\n inherit_panel = NULL,\n inherit_nobs = NULL) {\n cross(CrossNone,\n data = data, data_params = list2(...), plot = NULL,\n active = new_active(use = FALSE),\n schemes = default_schemes(),\n inherit_index = inherit_index,\n inherit_panel = inherit_panel,\n inherit_nobs = inherit_nobs\n )\n}\n\n#' @importFrom ggplot2 ggproto ggproto_parent\n#' @include craft-cross-.R\nCrossNone <- ggproto(\"CrossNone\", CraftCross)\n"], ["/ggalign/R/import-standalone-obj-type.R", "# Standalone file: do not edit by hand\n# Source: https://github.com/Yunuuuu/standalone/blob/HEAD/R/standalone-obj-type.R\n# Generated by: usethis::use_standalone(\"Yunuuuu/standalone\", \"obj-type\")\n# ----------------------------------------------------------------------\n#\n# ---\n# repo: Yunuuuu/standalone\n# file: standalone-obj-type.R\n# last-updated: 2025-04-11\n# license: https://unlicense.org\n# imports: rlang (>= 1.1.0)\n# ---\n#\n# ## Changelog\n# 2025-04-11:\n# - new `allow_what_type`\n#\n# 2024-11-10:\n# - `obj_type_friendly()` gains a `length` argument to control whether to show\n# the length of the vector.\n# - `stop_input_type()` gains a `show_length` argument passed to\n# `obj_type_friendly`.\n#\n# 2024-02-14:\n# - `obj_type_friendly()` now works for S7 objects.\n#\n# 2023-05-01:\n# - `obj_type_friendly()` now only displays the first class of S3 objects.\n#\n# 2023-03-30:\n# - `stop_input_type()` now handles `I()` input literally in `arg`.\n#\n# 2022-10-04:\n# - `obj_type_friendly(value = TRUE)` now shows numeric scalars\n# literally.\n# - `stop_friendly_type()` now takes `show_value`, passed to\n# `obj_type_friendly()` as the `value` argument.\n#\n# 2022-10-03:\n# - Added `allow_na` and `allow_null` arguments.\n# - `NULL` is now backticked.\n# - Better friendly type for infinities and `NaN`.\n#\n# 2022-09-16:\n# - Unprefixed usage of rlang functions with `rlang::` to\n# avoid onLoad issues when called from rlang (#1482).\n#\n# 2022-08-11:\n# - Prefixed usage of rlang functions with `rlang::`.\n#\n# 2022-06-22:\n# - `friendly_type_of()` is now `obj_type_friendly()`.\n# - Added `obj_type_oo()`.\n#\n# 2021-12-20:\n# - Added support for scalar values and empty vectors.\n# - Added `stop_input_type()`\n#\n# 2021-06-30:\n# - Added support for missing arguments.\n#\n# 2021-04-19:\n# - Added support for matrices and arrays (#141).\n# - Added documentation.\n# - Added changelog.\n#\n# nocov start\n# Following codes were modified from `rlang` package\n\n#' @param x The object type which does not conform to `what`. Its\n#' `obj_type_friendly()` is taken and mentioned in the error message.\n#' @param show_value Passed to `value` argument of `obj_type_friendly()`.\n#' @param show_length Passed to `length` argument of `obj_type_friendly()`.\n#' @param ... Arguments passed to [abort()].\n#' @inheritParams args_error_context\n#' @importFrom rlang caller_arg caller_env abort\n#' @noRd\nstop_input_type <- function(x,\n what,\n ...,\n allow_na = FALSE,\n allow_null = FALSE,\n show_value = TRUE,\n show_length = FALSE,\n arg = caller_arg(x),\n call = caller_env()) {\n what <- allow_what_type(\n what,\n allow_na = allow_na,\n allow_null = allow_null\n )\n if (inherits(arg, \"AsIs\")) {\n format_arg <- identity\n } else {\n format_arg <- function(x) sprintf(\"`%s`\", x)\n }\n message <- sprintf(\n \"%s must be %s, not %s.\",\n format_arg(arg), what,\n obj_type_friendly(x, value = show_value, length = show_length)\n )\n abort(message, ..., call = call, arg = arg)\n}\n\n#' @param what The friendly expected type as a string. Can be a\n#' character vector of expected types, in which case the error\n#' message mentions all of them in an \"or\" enumeration.\n#' @noRd\nallow_what_type <- function(what, allow_na = FALSE, allow_null = FALSE) {\n if (allow_na) {\n what <- c(what, \"`NA`\")\n }\n if (allow_null) {\n what <- c(what, \"`NULL`\")\n }\n if (length(what)) {\n what <- .standalone_oxford_comma(what, final = \"or\")\n }\n what\n}\n\n#' Return English-friendly type\n#' @param x Any R object.\n#' @param value Whether to describe the value of `x`. Special values\n#' like `NA` or `\"\"` are always described.\n#' @param length Whether to mention the length of vectors and lists.\n#' @return A string describing the type. Starts with an indefinite\n#' article, e.g. \"an integer vector\".\n#' @importFrom rlang is_missing is_vector\n#' @noRd\nobj_type_friendly <- function(x, value = TRUE, length = FALSE) {\n if (is_missing(x)) {\n return(\"absent\")\n }\n\n if (is.object(x)) {\n if (inherits(x, \"quosure\")) {\n type <- \"quosure\"\n } else {\n type <- class(x)[[1L]]\n }\n return(sprintf(\"a <%s> object\", type))\n }\n\n if (!is_vector(x)) {\n return(.rlang_as_friendly_type(typeof(x)))\n }\n\n n_dim <- length(dim(x))\n\n if (!n_dim) {\n if (!is.list(x) && length(x) == 1) {\n if (is.na(x)) {\n return(switch(typeof(x),\n logical = \"`NA`\",\n integer = \"an integer `NA`\",\n double =\n if (is.nan(x)) {\n \"`NaN`\"\n } else {\n \"a numeric `NA`\"\n },\n complex = \"a complex `NA`\",\n character = \"a character `NA`\",\n .rlang_stop_unexpected_typeof(x)\n ))\n }\n\n show_infinites <- function(x) {\n if (x > 0) {\n \"`Inf`\"\n } else {\n \"`-Inf`\"\n }\n }\n str_encode <- function(x, width = 30, ...) {\n if (nchar(x) > width) {\n x <- substr(x, 1, width - 3)\n x <- paste0(x, \"...\")\n }\n encodeString(x, ...)\n }\n\n if (value) {\n if (is.numeric(x) && is.infinite(x)) {\n return(show_infinites(x))\n }\n\n if (is.numeric(x) || is.complex(x)) {\n number <- as.character(round(x, 2))\n what <- if (is.complex(x)) {\n \"the complex number\"\n } else {\n \"the number\"\n }\n return(paste(what, number))\n }\n\n return(switch(typeof(x),\n logical = if (x) \"`TRUE`\" else \"`FALSE`\",\n character = {\n what <- if (nzchar(x)) {\n \"the string\"\n } else {\n \"the empty string\"\n }\n paste(what, str_encode(x, quote = \"\\\"\"))\n },\n raw = paste(\"the raw value\", as.character(x)),\n .rlang_stop_unexpected_typeof(x)\n ))\n }\n\n return(switch(typeof(x),\n logical = \"a logical value\",\n integer = \"an integer\",\n double = if (is.infinite(x)) show_infinites(x) else \"a number\",\n complex = \"a complex number\",\n character = if (nzchar(x)) \"a string\" else \"\\\"\\\"\",\n raw = \"a raw value\",\n .rlang_stop_unexpected_typeof(x)\n ))\n }\n\n if (length(x) == 0) {\n return(switch(typeof(x),\n logical = \"an empty logical vector\",\n integer = \"an empty integer vector\",\n double = \"an empty numeric vector\",\n complex = \"an empty complex vector\",\n character = \"an empty character vector\",\n raw = \"an empty raw vector\",\n list = \"an empty list\",\n .rlang_stop_unexpected_typeof(x)\n ))\n }\n }\n\n vec_type_friendly(x, length = length)\n}\n\n#' @importFrom rlang is_vector abort\nvec_type_friendly <- function(x, length = FALSE) {\n if (!is_vector(x)) {\n abort(\"`x` must be a vector.\")\n }\n type <- typeof(x)\n n_dim <- length(dim(x))\n\n add_length <- function(type) {\n if (length && !n_dim) {\n paste0(type, sprintf(\" of length %s\", length(x)))\n } else {\n type\n }\n }\n\n if (type == \"list\") {\n if (n_dim < 2) {\n return(add_length(\"a list\"))\n } else if (is.data.frame(x)) {\n return(\"a data frame\")\n } else if (n_dim == 2) {\n return(\"a list matrix\")\n } else {\n return(\"a list array\")\n }\n }\n\n type <- switch(type,\n logical = \"a logical %s\",\n integer = \"an integer %s\",\n numeric = ,\n double = \"a double %s\",\n complex = \"a complex %s\",\n character = \"a character %s\",\n raw = \"a raw %s\",\n type = paste0(\"a \", type, \" %s\")\n )\n\n if (n_dim < 2) {\n kind <- \"vector\"\n } else if (n_dim == 2) {\n kind <- \"matrix\"\n } else {\n kind <- \"array\"\n }\n out <- sprintf(type, kind)\n\n if (n_dim >= 2) {\n out\n } else {\n add_length(out)\n }\n}\n\n.rlang_as_friendly_type <- function(type) {\n switch(type,\n list = \"a list\",\n NULL = \"`NULL`\",\n environment = \"an environment\",\n externalptr = \"a pointer\",\n weakref = \"a weak reference\",\n S4 = \"an S4 object\",\n name = ,\n symbol = \"a symbol\",\n language = \"a call\",\n pairlist = \"a pairlist node\",\n expression = \"an expression vector\",\n char = \"an internal string\",\n promise = \"an internal promise\",\n ... = \"an internal dots object\",\n any = \"an internal `any` object\",\n bytecode = \"an internal bytecode object\",\n primitive = ,\n builtin = ,\n special = \"a primitive function\",\n closure = \"a function\",\n type\n )\n}\n\n#' @importFrom rlang abort caller_env\n.rlang_stop_unexpected_typeof <- function(x, call = caller_env()) {\n abort(sprintf(\"Unexpected type <%s>.\", typeof(x)), call = call)\n}\n\n#' Return OO type\n#' @param x Any R object.\n#' @return One of `\"bare\"` (for non-OO objects), `\"S3\"`, `\"S4\"`,\n#' `\"R6\"`, or `\"S7\"`.\n#' @noRd\nobj_type_oo <- function(x) {\n if (!is.object(x)) {\n return(\"bare\")\n }\n\n class <- inherits(x, c(\"R6\", \"S7_object\"), which = TRUE)\n\n if (class[[1]]) {\n \"R6\"\n } else if (class[[2]]) {\n \"S7\"\n } else if (isS4(x)) {\n \"S4\"\n } else {\n \"S3\"\n }\n}\n\n.standalone_oxford_comma <- function(x, sep = \", \", final = \"and\") {\n n <- length(x)\n\n if (n < 2L) return(x) # styler: off\n\n head <- x[seq_len(n - 1L)]\n last <- x[n]\n\n head <- paste(head, collapse = sep)\n\n # Write a or b. But a, b, or c.\n if (n > 2L) {\n paste0(head, sep, final, \" \", last)\n } else {\n paste0(head, \" \", final, \" \", last)\n }\n}\n\n# nocov end\n"], ["/ggalign/R/alignpatch-patchwork.R", "########################################\n#' @importFrom utils modifyList getFromNamespace\n#' @export\nalignpatch.patchwork <- function(x) {\n rlang::check_installed(\"patchwork\", \"to align patchwork\")\n get_patches <- getFromNamespace(\"get_patches\", \"patchwork\")\n # patchwork will keep the class when extracting patches from it.\n # we removed the classes for patchwork, added behind patchwork\n # in this way, the last plot won't have class like `free_align`,\n # `free_border`, `free_lab`, et al. which is added for the patchwork\n sub_patchwork_cls <- which(class(x) == \"patchwork\") - 1L # nolint\n if (sub_patchwork_cls > 0L) {\n class(x) <- class(x)[-seq_len(sub_patchwork_cls)]\n }\n x <- get_patches(x)\n plots <- .subset2(x, \"plots\")\n layout <- .subset2(x, \"layout\")\n annotation <- .subset2(x, \"annotation\")\n default <- getFromNamespace(\"default_layout\", \"patchwork\")\n layout <- modifyList(default, layout[\n !vapply(layout, is.null, logical(1L), USE.NAMES = FALSE)\n ])\n if (identical(.subset2(layout, \"guides\"), \"collect\")) {\n layout$guides <- .TLBR\n } else {\n layout$guides <- NULL\n }\n alignpatch(AlignPatches(\n plots,\n layout = layout,\n titles = .subset(annotation, names(layout_title())),\n theme = .subset2(annotation, \"theme\")\n ))\n}\n\n#' @export\nalignpatch.free_plot <- function(x) {\n if (inherits(x, \"patchwork\")) {\n free_settings <- attr(x, \"patchwork_free_settings\")\n } else {\n free_settings <- attr(x, \"free_settings\")\n }\n free_settings <- split(\n names(free_settings),\n factor(free_settings, rev(unique(free_settings)))\n )\n class(x) <- vec_set_difference(class(x), \"free_plot\")\n for (type in names(free_settings)) {\n side <- paste(.subset2(free_settings, type), collapse = \"\")\n x <- switch(type,\n panel = free_align(x, side),\n label = free_lab(x, side),\n space = free_space(free_border(x, side), side),\n )\n }\n alignpatch(x)\n}\n\n######################################\n# `patch` from `patchwork`: patchwork::plot_spacer\n#' @importFrom ggplot2 ggproto\n#' @export\nalignpatch.patch <- function(x) {\n rlang::check_installed(\n \"patchwork\", sprintf(\"to align %s plot\", obj_type_friendly(x))\n )\n ggproto(NULL, PatchPatchworkPatch, plot = x)\n}\n\n#' @importFrom ggplot2 ggproto\nPatchPatchworkPatch <- ggproto(\n \"PatchPatchworkPatch\", Patch,\n # `patch` from `patchwork`: patchwork::plot_spacer\n #' @importFrom gtable gtable_add_rows gtable_add_cols\n #' @importFrom ggplot2 find_panel\n patch_gtable = function(self, theme, guides, plot = self$plot) {\n guides <- if (length(guides)) \"collect\" else \"keep\"\n ans <- patchwork::patchGrob(patch, guides = guides)\n for (border in .TLBR) {\n panel_pos <- find_panel(ans)\n if (border == \"top\") {\n h <- .subset2(panel_pos, \"t\") - 4L # above original xlab\n ans <- gtable_add_rows(ans, unit(0L, \"mm\"), pos = h)\n } else if (border == \"left\") {\n v <- .subset2(panel_pos, \"l\") - 4L # left of the ylab\n ans <- gtable_add_cols(ans, unit(0, \"mm\"), pos = v)\n } else if (border == \"bottom\") {\n h <- .subset2(panel_pos, \"b\") + 3L # below original xlab\n ans <- gtable_add_rows(ans, unit(0L, \"mm\"), pos = h)\n } else if (border == \"right\") {\n v <- .subset2(panel_pos, \"r\") + 3L # right of the ylab\n ans <- gtable_add_cols(ans, unit(0, \"mm\"), pos = v)\n }\n }\n ans\n }\n)\n\n#' @export\nalignpatch.spacer <- function(x) NULL\n\n#########################################\n# `patch` from `patchwork`: patchwork::wrap_elements\n#' @export\nalignpatch.wrapped_patch <- alignpatch.patch\n"], ["/ggalign/R/import-standalone-pkg.R", "# Standalone file: do not edit by hand\n# Source: https://github.com/Yunuuuu/standalone/blob/HEAD/R/standalone-pkg.R\n# Generated by: usethis::use_standalone(\"Yunuuuu/standalone\", \"pkg\")\n# ----------------------------------------------------------------------\n#\n# ---\n# repo: Yunuuuu/standalone\n# file: standalone-pkg.R\n# last-updated: 2025-04-10\n# license: https://unlicense.org\n# imports: [utils]\n# ---\n\n# This file contains various helper utilities, including common functions\n# used across multiple packages I have developed. Some functions depend on\n# other packages that are not listed in Imports, so use them with caution.\n\n# ## Changelog\n# 2025-04-10\n# - simplify `from_namespace`\n#\n# 2025-03-30\n# - Add `use_github_release`\n#\n# 2025-03-12\n# - Add `from_namespace`\n#\n# 2025-03-10:\n# - Add `on_exit`\n#\n# 2025-03-08:\n# - Add `pkg_extdata`\n# - Add `defer`\n#\n# 2025-03-04:\n# - Add `%||%`\n#\n# 2025-03-03:\n# - Add `rd_collect_family`\n# - Add `oxford_and`\n# - Add `oxford_or`\n# - Add `code_quote`\n# - Add `oxford_comma`\n#\n# 2025-02-26:\n# - Add `is_installed`\n# - Add `install_pkgs`\n# - Add `pkg_nm`\n# - Add `pkg_namespace`\n#\n# nocov start\n\n`%||%` <- function(x, y) if (is.null(x)) y else x\n\nis_installed <- local({\n cache <- new.env(parent = emptyenv())\n function(pkg, version = NULL) {\n id <- if (is.null(version)) pkg else paste(pkg, version, sep = \":\")\n out <- cache[[id]]\n if (is.null(out)) {\n if (is.null(version)) {\n out <- requireNamespace(pkg, quietly = TRUE)\n } else {\n out <- requireNamespace(pkg, quietly = TRUE) &&\n utils::packageVersion(pkg) >= version\n }\n assign(id, out, envir = cache, inherits = FALSE)\n }\n out\n }\n})\n\ninstall_pkgs <- function(pkgs) {\n if (is_installed(\"pak\")) {\n getExportedValue(\"pak\", \"pkg_install\")(pkgs, ask = FALSE)\n } else {\n utils::install.packages(pkgs)\n }\n}\n\npkg_nm <- function() utils::packageName(environment())\n\npkg_namespace <- function() topenv(environment())\n\npkg_extdata <- function(..., mustWork = TRUE) {\n system.file(\"extdata\", ..., package = pkg_nm(), mustWork = mustWork)\n}\n\n############################################################\n# I’m having trouble connecting to GitHub, and it seems that `gert` does not\n# respect the proxy settings in my Git config. To work around this, I modified\n# `usethis::use_github_release()` to skip the check that relies on the `gert`\n# package.\nuse_github_release <- function(publish = TRUE) {\n usethis_ns <- getNamespace(\"usethis\")\n usethis <- function(fun, ...) {\n get(x = fun, envir = usethis_ns, inherits = FALSE, ...)\n }\n usethis(\"check_is_package\")(\"use_github_release()\")\n tr <- usethis(\"target_repo\")(\n github_get = TRUE,\n ok_configs = c(\"ours\", \"fork\")\n )\n usethis(\"check_can_push\")(tr = tr, \"to create a release\")\n dat <- usethis(\"get_release_data\")(tr)\n release_name <- paste(dat$Package, dat$Version)\n tag_name <- sprintf(\"v%s\", dat$Version)\n usethis(\"kv_line\")(\"Release name\", release_name)\n usethis(\"kv_line\")(\"Tag name\", tag_name)\n usethis(\"kv_line\")(\"SHA\", dat$SHA)\n usethis(\"check_github_has_SHA\")(SHA = dat$SHA, tr = tr)\n on_cran <- !is.null(usethis(\"cran_version\")())\n news <- usethis(\"get_release_news\")(\n SHA = dat$SHA, tr = tr, on_cran = on_cran\n )\n gh <- usethis(\"gh_tr\")(tr)\n usethis(\"ui_bullets\")(\"Publishing {tag_name} release to GitHub\")\n release <- gh( # nolint\n \"POST /repos/{owner}/{repo}/releases\",\n name = release_name,\n tag_name = tag_name,\n target_commitish = dat$SHA,\n body = news,\n draft = !publish\n )\n usethis(\"ui_bullets\")(\"Release at {.url {release$html_url}}\")\n if (!is.null(dat$file)) {\n usethis(\"ui_bullets\")(\"Deleting {.path {dat$file}}\")\n getExportedValue(\"fs\", \"file_delete\")(dat$file)\n }\n invisible()\n}\n\n############################################################\nfrom_namespace <- local({\n namespace <- NULL\n function(package, name, mode = \"any\") {\n if (is.null(namespace)) namespace <<- getNamespace(package)\n get(x = name, envir = namespace, inherits = FALSE, mode = mode)\n }\n})\n\n# Need `rlang` package, can support `quosure`\non_exit <- function(expr, envir = parent.frame(), after = TRUE, add = TRUE) {\n expr <- getExportedValue(\"rlang\", \"enquo\")(expr)\n defer(\n getExportedValue(\"rlang\", \"eval_tidy\")(expr),\n envir = envir,\n after = after,\n add\n )\n}\n\n# Just like `withr::defer()`, don't depend on `rlang` package\ndefer <- function(expr, envir = parent.frame(), after = TRUE, add = TRUE) {\n thunk <- as.call(list(function() expr))\n do.call(base::on.exit, list(thunk, add = add, after = after), envir = envir)\n}\n\n# utils function to collapse characters ---------------------------\noxford_and <- function(x, code = TRUE, quote = TRUE, sep = \", \") {\n oxford_comma(code_quote(x, code, quote), sep = sep, final = \"and\")\n}\n\noxford_or <- function(x, code = TRUE, quote = TRUE, sep = \", \") {\n oxford_comma(code_quote(x, code, quote), sep = sep, final = \"or\")\n}\n\ncode_quote <- function(x, code = TRUE, quote = TRUE) {\n if (quote) x <- paste0(\"\\\"\", x, \"\\\"\")\n if (code) x <- paste0(\"`\", x, \"`\")\n x\n}\n\noxford_comma <- function(x, sep = \", \", final = \"and\") {\n n <- length(x)\n\n if (n < 2L) return(x) # styler: off\n\n head <- x[seq_len(n - 1L)]\n last <- x[n]\n\n head <- paste(head, collapse = sep)\n\n # Write a or b. But a, b, or c.\n if (n > 2L) {\n paste0(head, sep, final, \" \", last)\n } else {\n paste0(head, \" \", final, \" \", last)\n }\n}\n\n# Need `roxygen2` package\n#' @description add `@eval rd_collect_family(\"myfamily\")` to the functions in\n#' your package. This will automatically generate a section listing all\n#' functions tagged with `@family myfamily`.\n#' @param family A string specifying the family name.\n#' @param section_title A string specifying the section title.\n#' @param code_style A boolean indicating whether to apply code formatting\n#' to function names.\n#' @noRd\nrd_collect_family <- function(\n family,\n section_title = paste(family, \"family\"),\n code_style = TRUE) {\n # get blocks objects from the roxygenize function\n blocks <- NULL\n pos <- sys.nframe()\n while (pos > 0L) {\n if (!is.null(call <- sys.call(-pos))) {\n fn <- eval(.subset2(call, 1L), sys.frame(-(pos + 1L)))\n env <- sys.frame(-pos)\n if (\n identical(fn, getExportedValue(\"roxygen2\", \"roxygenize\")) &&\n exists(\"blocks\", envir = env, inherits = FALSE)\n ) {\n blocks <- get(\"blocks\", envir = env, inherits = FALSE)\n break\n }\n }\n pos <- pos - 1L\n }\n\n # identify the blocks with family of the same tag specified in `family`\n blocks <- blocks[\n vapply(\n blocks,\n function(block) {\n getExportedValue(\"roxygen2\", \"block_has_tags\")(\n block,\n \"family\"\n ) &&\n identical(\n getExportedValue(\"roxygen2\", \"block_get_tag_value\")(\n block,\n \"family\"\n ),\n family\n )\n },\n logical(1L),\n USE.NAMES = FALSE\n )\n ]\n if (length(blocks) == 0L) return(character()) # styler: off\n\n # extracted the function name\n funs <- vapply(\n blocks,\n function(block) {\n as.character(.subset2(block$call, 2L))\n },\n character(1L),\n USE.NAMES = FALSE\n )\n if (code_style) {\n items <- sprintf(\"\\\\code{\\\\link[=%s]{%s()}}\", funs, funs)\n } else {\n items <- sprintf(\"\\\\link[=%s]{%s()}\", funs, funs)\n }\n c(\n sprintf(\"@section %s:\", section_title),\n \"\\\\itemize{\",\n sprintf(\" \\\\item %s\", items),\n \"}\"\n )\n}\n\n# nocov end\n"], ["/ggalign/R/raster-magick.R", "#' Rasterize the ggplot layers\n#'\n#' The function rasterizes input graphical objects (e.g., grob, layer, ggplot)\n#' and optionally processes the resulting raster using magick, a powerful image\n#' manipulation library. This allows for advanced graphical transformations\n#' directly within the plotting pipeline.\n#'\n#' @param x An object to rasterize, can be a [`grob()`][grid::grob],\n#' [`layer()`][ggplot2::layer], [`ggplot()`][ggplot2::ggplot], or a list of such\n#' objects.\n#'\n#' @inheritParams rlang::args_dots_empty\n#' @inheritParams magickGrob\n#' @examples\n#' # Currently, `magick` package require R >= 4.1.0\n#' if (requireNamespace(\"magick\")) {\n#' # data generated code was copied from `ComplexHeatmap`\n#' set.seed(123)\n#' small_mat <- matrix(rnorm(56), nrow = 7)\n#' rownames(small_mat) <- paste0(\"row\", seq_len(nrow(small_mat)))\n#' colnames(small_mat) <- paste0(\"column\", seq_len(ncol(small_mat)))\n#' ggheatmap(small_mat, aes(.x, .y), filling = NULL) +\n#' raster_magick(geom_tile(aes(fill = value)), res = 20)\n#'\n#' ggheatmap(small_mat, aes(.x, .y), filling = NULL) +\n#' # Use `magick::filter_types()` to check available `filter` arguments\n#' raster_magick(\n#' geom_tile(aes(fill = value)),\n#' magick = function(image) {\n#' magick::image_resize(image,\n#' geometry = \"50%x\", filter = \"Lanczos\"\n#' )\n#' }\n#' )\n#' }\n#' @return An object with the same class of the input.\n#' @seealso [`magickGrob()`]\n#' @export\nraster_magick <- function(x, magick = NULL, ...,\n res = NULL, interpolate = FALSE,\n vp = NULL) {\n rlang::check_installed(\"magick\", \"to use `raster_magick()`\")\n if (!is.null(magick) && !is.function(magick <- allow_lambda(magick))) {\n cli_abort(\"{.arg magick} must be a function\")\n }\n assert_number_whole(res, min = 1, allow_null = TRUE)\n assert_bool(interpolate)\n raster_magick0(\n x = x, ..., magick = magick,\n res = res, interpolate = interpolate,\n vp = vp\n )\n}\n\n# Used to do the actual process, but won't check the arguments\n#' @keywords internal\nraster_magick0 <- function(x, ...) {\n UseMethod(\"raster_magick0\")\n}\n\n#' @importFrom ggplot2 ggproto ggproto_parent\n#' @export\nraster_magick0.Layer <- function(x, ...) {\n ggproto(\n NULL, x,\n draw_geom = function(self, data, layout) {\n grobs <- ggproto_parent(x, self)$draw_geom(data, layout)\n if (!inherits(layout$coord, \"CoordCartesian\")) {\n cli_warn(\n \"{.fn raster_magick} only works with {.fn coord_cartesian}.\"\n )\n return(grobs)\n }\n raster_magick0(grobs, ...)\n }\n )\n}\n\n#' @export\nraster_magick0.ggplot <- function(x, ...) {\n x$layers <- lapply(x$layers, raster_magick0, ...)\n x\n}\n\n#' @export\nraster_magick0.list <- function(x, ...) lapply(x, raster_magick0, ...)\n\n#' @export\nraster_magick0.grob <- function(x, magick = NULL, ...,\n res = NULL, interpolate = FALSE,\n vp = NULL) {\n rlang::check_dots_empty()\n magickGrob0(\n grob = x, magick = magick,\n res = res, interpolate = interpolate, vp = vp\n )\n}\n\n#' @export\nraster_magick0.gList <- raster_magick0.grob\n\n#' @export\nraster_magick0.default <- function(x, ...) {\n cli_abort(\"Cannot rasterize {.obj_type_friendly {x}}\")\n}\n"], ["/ggalign/R/fortify-matrix-matrix.R", "#' Build a matrix\n#'\n#' @param data A matrix object.\n#' @inheritParams rlang::args_dots_empty\n#' @inheritParams fortify_matrix\n#' @section shape:\n#' - `upset`: [`fortify_matrix.matrix_upset()`]\n#' - `oncoplot`: [`fortify_matrix.matrix_oncoplot()`]\n#' @family fortify_matrix\n#' @export\nfortify_matrix.matrix <- fortify_matrix.waiver\n\n#' Convert the shape of a matrix for fortify method\n#'\n#' @param data A matrix.\n#' @param shape A string of `r oxford_or(c(\"upset\", \"oncoplot\"))`.\n#' @seealso\n#' - [`fortify_matrix.matrix()`]\n#' - [`fortify_matrix.matrix_upset()`]\n#' - [`fortify_matrix.matrix_oncoplot()`]\n#' @family tune\n#' @importFrom rlang arg_match0\n#' @export\ntune.matrix <- function(data, shape) {\n shape <- arg_match0(shape, c(\"upset\", \"oncoplot\"))\n if (identical(shape, \"oncoplot\")) {\n if (!is.character(data)) {\n cli_abort(\n \"{.arg data} must be a character matrix to use {shape} shape\"\n )\n }\n }\n new_tune(data, class = sprintf(\"matrix_%s\", shape))\n}\n\n#' @inherit fortify_matrix.list_upset title\n#' @description\n#' Converts a matrix suitable for creating an UpSet plot. [`tune.matrix()`]\n#' helps convert `matrix` object to a `matrix_upset` object.\n#' @param data A matrix where each row represents an element, and each column\n#' defines a set. The values in the matrix indicate whether the element is part\n#' of the set. Any non-missing value signifies that the element exists in the\n#' set.\n#' @inheritParams fortify_matrix.list_upset\n#' @inheritDotParams fortify_matrix.list_upset\n#' @inheritSection fortify_matrix.list_upset ggalign attributes\n#' @seealso [`tune.matrix()`]\n#' @family fortify_matrix\n#' @export\nfortify_matrix.matrix_upset <- function(data, ..., data_arg = NULL,\n call = NULL) {\n call <- call %||% current_call()\n data <- !is.na(tune_data(data))\n elements <- vec_seq_along(data)\n fortify_matrix.list_upset(\n lapply(seq_len(ncol(data)), function(i) {\n .subset(elements, data[, i, drop = TRUE])\n }),\n ...,\n data_arg = data_arg,\n call = call\n )\n}\n\n#' Build a Matrix for OncoPrint\n#'\n#' @description\n#' Converts a matrix suitable for creating an OncoPrint. [`tune.matrix()`]\n#' helps convert `matrix` object to a `matrix_oncoplot` object.\n#'\n#' @param data A matrix where each row represents an genes, and each column\n#' represents samples. The values in the matrix indicate whether the element is\n#' part of the set.\n#' @inheritParams fortify_matrix.MAF\n#' @section ggalign attributes:\n#' - `gene_summary`: An integer vector of the altered samples for each gene.\n#' - `sample_summary`: An integer vector of the altered genes for each sample.\n#' - `n_genes`: Total number of genes.\n#' - `n_samples`: Total number of samples.\n#'\n#' @seealso [`tune.matrix()`]\n#' @family fortify_matrix\n#' @export\nfortify_matrix.matrix_oncoplot <- function(data, ...,\n genes = NULL, n_top = NULL,\n remove_empty_genes = TRUE,\n remove_empty_samples = TRUE,\n missing_genes = \"error\",\n data_arg = NULL,\n call = NULL) {\n call <- call %||% current_call()\n rlang::check_dots_empty(call = call)\n\n # check arguments\n missing_genes <- arg_match0(\n missing_genes, c(\"error\", \"remove\"),\n error_call = call\n )\n\n data <- tune_data(data)\n alt <- !is.na(data)\n storage.mode(alt) <- \"integer\"\n gene_summary <- rowSums(alt)\n sample_summary <- colSums(alt)\n n_genes <- nrow(data)\n n_samples <- ncol(data)\n\n # filter by genes --------------------------------------\n if (!is.null(genes)) {\n genes <- vec_cast(genes, character())\n if (vec_any_missing(genes)) {\n cli_abort(\n \"{.arg genes} cannot contain missing values\",\n call = call\n )\n }\n if (vec_duplicate_any(genes)) {\n cli_abort(\n \"{.arg genes} cannot contain duplicated values\",\n call = call\n )\n }\n if (identical(missing_genes, \"remove\")) {\n genes <- genes[genes %in% rownames(data)]\n }\n if (is_empty(genes)) {\n cli_abort(\n \"No {.arg genes} remain after removing missing genes\",\n call = call\n )\n }\n index <- vec_as_location(\n genes,\n n = vec_size(data),\n names = rownames(data),\n missing = \"error\"\n )\n data <- vec_slice(data, index)\n alt <- vec_slice(alt, index)\n gene_summary <- vec_slice(gene_summary, index)\n }\n\n if (!is.null(n_top)) {\n n_top <- min(n_top, vec_size(alt))\n index <- vec_slice(\n order(rowSums(alt), decreasing = TRUE),\n seq_len(n_top)\n )\n data <- vec_slice(data, index)\n alt <- vec_slice(alt, index)\n gene_summary <- vec_slice(gene_summary, index)\n }\n\n # filter empty genes\n if (remove_empty_genes) {\n keep <- rowSums(alt) > 0L\n data <- vec_slice(data, keep)\n gene_summary <- vec_slice(gene_summary, keep)\n }\n\n # filter empty samples\n if (remove_empty_samples) {\n keep <- colSums(alt) > 0L\n data <- data[, keep, drop = FALSE]\n sample_summary <- vec_slice(sample_summary, keep)\n }\n\n ggalign_data_set(data,\n sample_summary = sample_summary,\n gene_summary = gene_summary,\n n_samples = n_samples,\n n_genes = n_genes\n )\n}\n"], ["/ggalign/R/scheme-theme.R", "#' Plot default theme\n#'\n#' @description\n#' `r lifecycle::badge('experimental')`\n#'\n#' `scheme_theme()` serves as the default theme and will always be overridden by\n#' any `theme()` settings applied directly to the plot. The default theme\n#' (`scheme_theme()`) is applied first, followed by any specific `theme()`\n#' settings, even if `theme()` is added before `scheme_theme()`.\n#'\n#' @inherit ggplot2::theme\n#' @param ... A [`theme()`][ggplot2::theme] object or additional element\n#' specifications not part of base ggplot2. In general, these should also be\n#' defined in the `element tree` argument. [`Splicing`][rlang::splice] a list\n#' is also supported.\n#' @examples\n#' set.seed(123)\n#' small_mat <- matrix(rnorm(56), nrow = 8)\n#' ggheatmap(small_mat) +\n#' scheme_theme(plot.background = element_rect(fill = \"red\"))\n#'\n#' # `scheme_theme()` serves as the default theme and will always be\n#' # overridden by any `theme()` settings applied directly to the plot\n#' ggheatmap(small_mat) +\n#' theme(plot.background = element_rect(fill = \"blue\")) +\n#' scheme_theme(plot.background = element_rect(fill = \"red\"))\n#'\n#' @importFrom ggplot2 theme\n#' @importFrom rlang inject\n#' @export\nscheme_theme <- rlang::new_function(\n # We utilize editor completion by listing all `theme()` arguments here.\n # By placing `...` at the beginning, we can check if the first\n # following argument is a `theme()` object rather than individual theme\n # elements.\n c(\n rlang::exprs(... = ),\n .subset(\n rlang::fn_fmls(theme),\n vec_set_difference(names(rlang::fn_fmls(theme)), \"...\")\n )\n ),\n quote({\n elements <- ggfun(\"find_args\")(..., complete = NULL, validate = NULL)\n ans <- theme(!!!elements)\n th <- NULL\n for (i in seq_len(...length())) {\n if (inherits(t <- ...elt(i), \"theme\")) {\n th <- ggfun(\"add_theme\")(th, t)\n }\n }\n new_scheme_theme(ggfun(\"add_theme\")(th, ans))\n })\n)\n\n#' @importFrom ggplot2 theme\nnew_scheme_theme <- function(th = theme()) {\n # I don't know why, if I omit the `object = th` argument, it won't work\n UseMethod(\"new_scheme_theme\", th)\n}\n\n#' @importFrom rlang inject\n#' @export\nnew_scheme_theme.theme <- function(th = theme()) {\n attrs <- attributes(th)\n attrs <- vec_slice(\n attrs, vec_set_difference(names(attrs), c(\"names\", \"class\"))\n )\n inject(new_scheme(\n name = \"scheme_theme\", th, !!!attrs,\n class = c(\"scheme_theme\", class(th))\n ))\n}\n\n#' @export\nnew_scheme_theme.scheme_theme <- function(th = theme()) th\n\n###############################################################\n#' @export\nupdate_scheme.scheme_theme <- function(new, old, object_name) {\n ggfun(\"add_theme\")(old, new, object_name)\n}\n\n#' @export\ninherit_scheme.scheme_theme <- function(scheme, pscheme) {\n pscheme + scheme\n}\n\n#' @export\nplot_add_scheme.scheme_theme <- function(plot, scheme) {\n # setup plot theme\n plot$theme <- scheme + plot$theme\n plot\n}\n"], ["/ggalign/R/craft-align-kmeans.R", "#' Split observations by k-means clustering groups.\n#'\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' Aligns and groups observations based on k-means clustering, enabling\n#' observation splits by cluster groups.\n#'\n#' @inheritDotParams stats::kmeans -x -centers\n#' @param data A numeric matrix to be used by k-means. By default, it will\n#' inherit from the layout matrix.\n#' @inheritParams align\n#' @inheritSection align Discrete Axis Alignment\n#' @examples\n#' ggheatmap(matrix(rnorm(81), nrow = 9)) +\n#' anno_top() +\n#' align_kmeans(3L)\n#' @importFrom rlang list2\n#' @export\nalign_kmeans <- function(..., data = NULL, active = NULL) {\n assert_active(active)\n active <- update_active(active, new_active(use = FALSE))\n align(\n align = AlignKmeans,\n params = list2(...),\n active = active,\n data = data\n )\n}\n\n#' @importFrom ggplot2 ggproto\n#' @importFrom rlang inject\nAlignKmeans <- ggproto(\"AlignKmeans\", CraftAlign,\n interact_layout = function(self, layout) {\n ggproto_parent(AlignOrder2, self)$interact_layout(layout)\n },\n compute = function(self, panel, index) {\n inject(stats::kmeans(x = self$data, !!!self$params))\n },\n align = function(self, panel, index) {\n list(.subset2(self$statistics, \"cluster\"), index)\n },\n summary_align = function(self) c(FALSE, TRUE)\n)\n"], ["/ggalign/R/scheme-align.R", "#' Align Specifications in the Layout\n#'\n#' @description\n#' `r lifecycle::badge('experimental')`\n#'\n#' The `scheme_align()` function defines the align Specifications for plots.\n#'\n#' @param guides A string with one or more of `r oxford_and(c(.tlbr, \"i\"))`\n#' indicating which side of guide legends should be collected. Defaults to\n#' [`waiver()`][ggplot2::waiver()], which inherits from the parent layout. If no\n#' parent layout, all guides will be collected. If `NULL`, no guides will be\n#' collected.\n#'\n#' @param free_spaces A string with one or more of `r oxford_and(.tlbr)`\n#' indicating which border spaces should be removed. Defaults to\n#' [`waiver()`][ggplot2::waiver()], which inherits from the parent layout. If no\n#' parent, the default is `NULL`, meaning no spaces are removed.\n#'\n#' Usually you want to apply this with the whole layout, instead of individual\n#' plots.\n#'\n#' @param free_labs A string with one or more of `r oxford_and(.tlbr)`\n#' indicating which axis titles should be free from alignment. Defaults to\n#' [`waiver()`][ggplot2::waiver()], which inherits from the parent layout. If no\n#' parent layout, no axis titles will be aligned. If `NULL`, all axis titles\n#' will be aligned.\n#'\n#' @return A `scheme_align` object.\n#' @examples\n#' set.seed(123)\n#' mat <- matrix(rnorm(72), nrow = 8)\n#' # used in the layout, define the default action for all plots in the layout\n#' ggheatmap(mat) -\n#' scheme_align(guides = NULL) +\n#' anno_right() +\n#' align_dendro(aes(color = branch), k = 3)\n#'\n#' # You can also add it for a single plot\n#' ggheatmap(mat) -\n#' # for all plots in the layout, we default won't collect any guide legends\n#' scheme_align(guides = NULL) +\n#' # for the heatmap body, we collect guide legends in the right\n#' # note, the guide legends will be collected to the right side of the\n#' # layout which will overlap the legends in the right annotation\n#' scheme_align(guides = \"r\") +\n#' anno_right() +\n#' align_dendro(aes(color = branch), k = 3)\n#'\n#' # to avoid overlapping, we can also collect the guide legends in the\n#' # right annotation\n#' ggheatmap(mat) -\n#' scheme_align(guides = NULL) +\n#' scheme_align(guides = \"r\") +\n#' anno_right() +\n#' align_dendro(aes(color = branch), k = 3) +\n#' scheme_align(guides = \"r\")\n#' @export\nscheme_align <- function(guides = NA, free_spaces = NA, free_labs = NA) {\n if (!identical(guides, NA)) assert_layout_guides(guides)\n if (!identical(free_spaces, NA)) assert_layout_position(free_spaces)\n if (!identical(free_labs, NA)) assert_layout_position(free_labs)\n new_scheme_align(\n free_spaces = free_spaces,\n free_labs = free_labs,\n guides = guides\n )\n}\n\nnew_scheme_align <- function(guides = waiver(), free_spaces = waiver(),\n free_labs = waiver()) {\n new_scheme(\n name = \"scheme_align\",\n list(free_spaces = free_spaces, free_labs = free_labs, guides = guides),\n class = \"scheme_align\"\n )\n}\n\n#' @importFrom utils modifyList\n#' @export\nupdate_scheme.scheme_align <- function(new, old, object_name) {\n modifyList(old,\n new[!vapply(new, identical, logical(1L), y = NA, USE.NAMES = FALSE)],\n keep.null = TRUE\n )\n}\n\n#' @export\ninherit_scheme.scheme_align <- function(scheme, pscheme) {\n # `align_plots` control how to inherit `guides` from the layout\n # we don't need to inherit it here\n scheme[\"free_spaces\"] <- list(.subset2(scheme, \"free_spaces\") %|w|%\n .subset2(pscheme, \"free_spaces\"))\n scheme[\"free_labs\"] <- list(.subset2(scheme, \"free_labs\") %|w|%\n .subset2(pscheme, \"free_labs\"))\n scheme\n}\n\n#' @param theme Additional default theme elements to be added for the plot\n#' @noRd\nplot_add_scheme.scheme_align <- function(plot, scheme) {\n if (!is.waive(free_guides <- .subset2(scheme, \"guides\"))) {\n plot <- free_guide(plot, free_guides)\n }\n # by default, we'll attach all labs to the axis\n if (!is.null(free_labs <- .subset2(scheme, \"free_labs\") %|w|% \"tlbr\")) {\n plot <- free_lab(plot, free_labs)\n }\n # by default, we won't remove any spaces\n if (!is.null(free_spaces <- .subset2(scheme, \"free_spaces\") %|w|% NULL)) {\n plot <- free_space(free_border(plot, free_spaces), free_spaces)\n }\n plot\n}\n"], ["/ggalign/R/scheme-.R", "new_schemes <- function(...) {\n default <- list(\n new_scheme_data(),\n new_scheme_align(),\n new_scheme_theme()\n )\n names(default) <- vapply(default, ggalign_scheme_name,\n character(1L),\n USE.NAMES = FALSE\n )\n for (i in seq_len(...length())) {\n scheme <- ...elt(i)\n default[[ggalign_scheme_name(scheme)]] <- scheme\n }\n default\n}\n\nnew_scheme <- function(name, data, ..., class = character()) {\n structure(data,\n `__ggalign.scheme_name__` = name, ...,\n class = c(class, \"ggalign_scheme\")\n )\n}\n\nggalign_scheme_name <- function(x) {\n attr(x, \"__ggalign.scheme_name__\", exact = TRUE)\n}\n\n#' @importFrom ggplot2 theme\ndefault_schemes <- function(data = NULL, th = theme()) {\n if (!is.waive(data)) data <- NULL\n new_schemes(\n new_scheme_data(data),\n new_scheme_theme(th)\n )\n}\n\n###############################################################\n#' Used to update global data\n#' @noRd\nupdate_scheme <- function(new, old, object_name) {\n UseMethod(\"update_scheme\", old)\n}\n\n#' @export\nupdate_scheme.default <- function(new, old, object_name) new\n\nupdate_layout_scheme <- function(object, layout, object_name) {\n name <- ggalign_scheme_name(object)\n layout@schemes[name] <- list(update_scheme(\n object, .subset2(layout@schemes, name), object_name\n ))\n layout\n}\n\n###############################################################\ninherit_scheme <- function(scheme, pscheme) {\n UseMethod(\"inherit_scheme\", pscheme)\n}\n\n# If no parent scheme, use child scheme directly\n#' @export\ninherit_scheme.NULL <- function(scheme, pscheme) scheme\n\ninherit_schemes <- function(schemes, pschemes) {\n nms <- vapply(pschemes,\n ggalign_scheme_name, character(1L),\n USE.NAMES = FALSE\n )\n ans <- lapply(nms, function(opt) {\n inherit_scheme(.subset2(schemes, opt), .subset2(pschemes, opt))\n })\n names(ans) <- nms\n ans\n}\n\n###############################################################\nplot_add_scheme <- function(plot, scheme) UseMethod(\"plot_add_scheme\", scheme)\n\n#' @export\nplot_add_scheme.NULL <- function(plot, scheme) plot\n\nplot_add_schemes <- function(plot, schemes) {\n for (i in seq_along(schemes)) {\n plot <- plot_add_scheme(plot, scheme = .subset2(schemes, i))\n }\n plot\n}\n"], ["/ggalign/R/scheme-data.R", "#' Plot data Specifications\n#'\n#' @description\n#' `r lifecycle::badge('experimental')`\n#'\n#' Transforms the plot data. Many functions in this package require a specific\n#' data format to align observations, `scheme_data()` helps reformat data frames\n#' as needed.\n#'\n#' @param data A function to transform the plot data before rendering.\n#' Acceptable values include:\n#'\n#' - `NULL`: No action taken.\n#' - [`waiver()`][ggplot2::waiver()]: Inherits from the parent layout.\n#' - A `function` or purrr-style `formula`: Used to transform the plot data,\n#' which should accept a data frame and return a data frame. You can apply\n#' this after the parent layout `scheme_data` function, using the `inherit`\n#' argument.\n#'\n#' Use this hook to modify the data for all `geoms` after the layout is created\n#' (for matrix data, it has been melted to a long format data frame) but before\n#' rendering by `ggplot2`. The returned data must be a data frame for ggplot.\n#'\n#' @param inherit A single boolean value indicates whether to apply the parent\n#' `scheme_data` first and then apply the specified `scheme_data` for the plot.\n#' Defaults to `FALSE`.\n#'\n#' @details\n#' Defaults will attempt to inherit from the parent layout if the actual data is\n#' inherited from the parent layout, with one exception: `align_dendro()`, which\n#' will not inherit the `scheme_data` by default.\n#'\n#' @export\nscheme_data <- function(data, inherit = FALSE) {\n data <- check_scheme_data(data)\n assert_bool(inherit)\n new_scheme_data(data, inherit)\n}\n\nnew_scheme_data <- function(data = NULL, inherit = FALSE) {\n new_scheme(\n name = \"scheme_data\",\n list(data = data, inherit = inherit),\n class = \"scheme_data\"\n )\n}\n\n#' @export\ninherit_scheme.scheme_data <- function(scheme, pscheme) {\n if (is.null(o <- .subset2(scheme, \"data\"))) return(scheme) # styler: off\n if (is.waive(o)) return(pscheme) # inherit from parent; styler: off\n if (!is.function(p_function <- .subset2(pscheme, \"data\"))) {\n return(scheme)\n }\n # if both are function, we check if we should call parent first then call\n # itself\n if (.subset2(scheme, \"inherit\")) {\n user_scheme_data <- o # current action data function\n scheme$data <- function(data) {\n # we always restore the attached attribute\n ans <- ggalign_data_restore(p_function(data), data)\n user_scheme_data(ans)\n }\n }\n scheme\n}\n\n#' @export\nplot_add_scheme.scheme_data <- function(plot, scheme) {\n # by default, we won't change the data\n if (!is.null(scheme_data <- .subset2(scheme, \"data\") %|w|% NULL) &&\n !is.null(raw_data <- plot$data)) {\n # To be compatible with ggplot2, it must be a data frame\n if (!is.null(data <- scheme_data(raw_data)) &&\n !is.waive(data) &&\n !is.data.frame(data)) {\n cli_abort(\"{.fn scheme_data} must return a {.cls data.frame}\")\n }\n plot <- gguse_data(plot, data)\n }\n plot\n}\n"], ["/ggalign/R/attributes.R", "#' Get Data from the Attribute Attached by ggalign\n#'\n#' @description\n#' `ggalign_attr` retrieves supplementary information stored as attributes\n#' during the layout rendering process. These attributes—typically added during\n#' data transformation by functions such as [`fortify_matrix()`] or\n#' [`fortify_data_frame()`]—may contain filtered data, auxiliary metadata, or\n#' other context essential for downstream operations.\n#'\n#' Factor level information, stored as a separate attribute, can be accessed via\n#' `ggalign_lvls`.\n#'\n#' @details\n#' Attributes attached to the data are especially useful when the input data is\n#' transformed in ways that limit access to the complete dataset. For example,\n#' [`fortify_matrix.MAF()`] might filter mutation data while adding attributes\n#' that retain important context, such as the total number of observations, for\n#' detailed or aggregated analyses. Additionally, it stores the levels of\n#' `Variant_Classification` for further usage.\n#'\n#' @param x Data used, typically inherited from the layout `r rd_layout()`.\n#' @param field A string specifying the particular data to retrieve from the\n#' attached attribute. If `NULL`, the entire attached attribute list will be\n#' returned.\n#' @param check A boolean indicating whether to check if the `field` exists. If\n#' `TRUE`, an error will be raised if the specified `field` does not exist.\n#' @return\n#' - `ggalign_attr`: The specified data from the attached supplementary data or\n#' `NULL` if it is unavailable.\n#' - `ggalign_lvls`: The attached supplementary levels or `NULL` if it is\n#' unavailable.\n#'\n#' @export\nggalign_attr <- function(x, field = NULL, check = TRUE) {\n assert_string(field, allow_empty = FALSE, allow_null = TRUE)\n if (is.null(x <- ggalign_attr_get(x)) || is.null(field)) {\n return(x)\n }\n if (isTRUE(check) && !rlang::has_name(x, field)) {\n cli_abort(\"Cannot find {field} in {.arg x}\")\n }\n .subset2(x, field)\n}\n\n#' @export\n#' @rdname ggalign_attr\nggalign_lvls <- function(x) ggalign_lvls_get(x)\n\n#' Attach supplementary data and levels for ggalign\n#'\n#' @param .data Input data for the layout.\n#' @param ... <[dyn-dots][rlang::dyn-dots]> A list of data to be attached.\n#' @param .lvls A character vector representing the attached levels.\n#' @note Used by developers in [`fortify_matrix()`], [`fortify_data_frame()`],\n#' and other related methods.\n#' @seealso [`ggalign_attr()`]/[`ggalign_lvls()`]\n#' @importFrom rlang list2\n#' @export\nggalign_data_set <- function(.data, ..., .lvls = NULL) {\n if (...length() > 0L) {\n .data <- ggalign_attr_set(.data, list2(...))\n }\n if (!is.null(.lvls)) {\n .data <- ggalign_lvls_set(.data, .lvls)\n }\n # to prevent the print of attributes\n if (!is.null(ggalign_attr_get(.data)) ||\n !is.null(ggalign_lvls_get(.data))) {\n .data <- add_class(.data, \"ggalign_data\")\n }\n .data\n}\n\n#' @export\nprint.ggalign_data <- function(x, ...) {\n print(\n remove_class(\n ggalign_lvls_remove(ggalign_attr_remove(x)),\n \"ggalign_data\"\n )\n )\n invisible(x)\n}\n\nggalign_attr_set <- function(x, values) {\n attr(x, \".__ggalign_attr__\") <- values\n x\n}\n\nggalign_attr_get <- function(x) attr(x, \".__ggalign_attr__\", exact = TRUE)\n\nggalign_attr_remove <- function(x) ggalign_attr_set(x, NULL)\n\nggalign_lvls_set <- function(x, lvls) {\n attr(x, \".__ggalign_levels__\") <- lvls\n x\n}\n\nggalign_lvls_get <- function(x) attr(x, \".__ggalign_levels__\", exact = TRUE)\n\nggalign_lvls_remove <- function(x) ggalign_lvls_set(x, NULL)\n\n# we keep a special attribute across all data\n# this is used to pass additional annotation informations\nggalign_data_restore <- function(data, original) {\n if (is.null(data) || is.waive(data)) return(data) # styler: off\n if (is.null(ggalign_attr_get(data)) && # no attached attribute\n # the original has attached attribute\n !is.null(value <- ggalign_attr_get(original))) {\n data <- ggalign_attr_set(data, value)\n }\n\n if (is.null(ggalign_lvls_get(data)) && # no attached levels\n # the original has attached levels\n !is.null(value <- ggalign_lvls_get(original))) {\n data <- ggalign_lvls_set(data, value)\n }\n # to prevent the print of attributes\n if (!is.null(ggalign_attr_get(data)) ||\n !is.null(ggalign_lvls_get(data))) {\n data <- add_class(data, \"ggalign_data\")\n }\n data\n}\n"], ["/ggalign/R/import-standalone-assert.R", "# Standalone file: do not edit by hand\n# Source: https://github.com/Yunuuuu/standalone/blob/HEAD/R/standalone-assert.R\n# Generated by: usethis::use_standalone(\"Yunuuuu/standalone\", \"assert\")\n# ----------------------------------------------------------------------\n#\n# ---\n# repo: Yunuuuu/standalone\n# file: standalone-assert.R\n# last-updated: 2025-04-16\n# license: https://unlicense.org\n# dependencies: [standalone-obj-type.R]\n# imports: rlang\n# ---\n\n# ## Changelog\n# 2025-04-16:\n# - `assert_number_whole` gains `allow_infinite` argument\n#\n# 2025-04-11:\n# - new `.rlang_allow_number`\n# - new `.rlang_check_number`\n# - new `.rlang_check_bool`\n# - new `.rlang_check_string`\n#\n# 2024-11-10:\n# - Added support for S3 object\n#\n# nocov start\n# Following codes were modified from `rlang` package\n\n#' Report if an argument is a specific class\n#'\n#' @param x The object type which does not conform to `what`. Its\n#' `obj_type_friendly()` is taken and mentioned in the error message.\n#' @param what The friendly expected type as a string. Can be a\n#' character vector of expected types, in which case the error\n#' message mentions all of them in an \"or\" enumeration.\n#' @param show_value Passed to `value` argument of `obj_type_friendly()`.\n#' @param show_length Passed to `length` argument of `obj_type_friendly()`.\n#' @param ... Arguments passed to [rlang::abort()].\n#' @importFrom rlang is_missing\n#' @noRd\nassert_ <- function(x, check, what,\n allow_null = FALSE,\n allow_na = FALSE,\n show_value = TRUE,\n show_length = FALSE,\n ...,\n arg = caller_arg(x),\n call = caller_env()) {\n if (!is_missing(x) && (\n (allow_null && is.null(x)) || check(x)\n )) {\n return(invisible(NULL))\n }\n stop_input_type(x, what,\n allow_na = allow_na,\n allow_null = allow_null,\n show_value = show_value,\n show_length = show_length,\n ...,\n arg = arg, call = call\n )\n}\n\nIS_NUMBER_true <- 0\nIS_NUMBER_false <- 1\nIS_NUMBER_oob <- 2\n\n.standalone_types_check_assert_call <- .Call\n\n#' @importFrom rlang ffi_standalone_check_number_1.0.7\n.rlang_check_number <- function(x, allow_decimal,\n min = NULL,\n max = NULL,\n allow_infinite = allow_decimal,\n allow_na = FALSE,\n allow_null = FALSE) {\n .standalone_types_check_assert_call(\n ffi_standalone_check_number_1.0.7,\n x,\n allow_decimal,\n min,\n max,\n allow_infinite,\n allow_na,\n allow_null\n )\n}\n\n#' @importFrom rlang ffi_standalone_is_bool_1.0.7\n.rlang_check_bool <- function(x, allow_na = FALSE, allow_null = FALSE) {\n .standalone_types_check_assert_call(\n ffi_standalone_is_bool_1.0.7,\n x,\n allow_na,\n allow_null\n )\n}\n\n#' @importFrom rlang is_string\n.rlang_check_string <- function(x, allow_empty = TRUE,\n allow_na = FALSE, allow_null = FALSE) {\n if (is_string(x) && !is.na(x)) {\n if (allow_empty || x != \"\") {\n return(TRUE)\n }\n }\n\n if (allow_null && is.null(x)) {\n return(TRUE)\n }\n\n if (allow_na && (identical(x, NA) || identical(x, NA_character_))) {\n return(TRUE)\n }\n\n FALSE\n}\n\n#' @importFrom rlang abort\n.rlang_allow_number <- function(x, exit_code, allow_decimal,\n min = NULL,\n max = NULL,\n allow_na = FALSE,\n allow_null = FALSE) {\n if (allow_decimal) {\n what <- \"a number\"\n } else {\n what <- \"a whole number\"\n }\n if (exit_code == IS_NUMBER_oob) {\n min <- min %||% -Inf\n max <- max %||% Inf\n\n if (min > -Inf && max < Inf) {\n what <- sprintf(\"%s between %s and %s\", what, min, max)\n } else if (x < min) {\n what <- sprintf(\"%s larger than or equal to %s\", what, min)\n } else if (x > max) {\n what <- sprintf(\"%s smaller than or equal to %s\", what, max)\n } else {\n abort(\"Unexpected state in OOB check\", .internal = TRUE)\n }\n }\n allow_what_type(what, allow_na = allow_na, allow_null = allow_null)\n}\n\n# scalar object ----------------------------------\nassert_string <- function(x,\n ...,\n allow_empty = TRUE,\n allow_na = FALSE,\n allow_null = FALSE,\n arg = caller_arg(x),\n call = caller_env()) {\n assert_(\n x = x,\n check = function(x) {\n .rlang_check_string(\n x,\n allow_empty = allow_empty,\n allow_na = allow_na,\n allow_null = allow_null\n )\n },\n what = \"a single string\",\n ...,\n allow_na = allow_na,\n allow_null = allow_null,\n arg = arg,\n call = call\n )\n}\n\n#' @importFrom rlang abort\n.stop_not_number <- function(x,\n exit_code,\n allow_decimal,\n ...,\n min = NULL,\n max = NULL,\n allow_na = FALSE,\n allow_null = FALSE,\n show_value = TRUE,\n show_length = FALSE,\n arg = caller_arg(x),\n call = caller_env()) {\n what <- .rlang_allow_number(\n x = x,\n exit_code = exit_code,\n allow_decimal = allow_decimal,\n min = min, max = max,\n allow_na = allow_na,\n allow_null = allow_null\n )\n if (inherits(arg, \"AsIs\")) {\n format_arg <- identity\n } else {\n format_arg <- function(x) sprintf(\"`%s`\", x)\n }\n message <- sprintf(\n \"%s must be %s, not %s.\",\n format_arg(arg), what,\n obj_type_friendly(x, value = show_value, length = show_length)\n )\n abort(message, ..., call = call, arg = arg)\n}\n\n#' @importFrom rlang is_missing\nassert_number_decimal <- function(x,\n ...,\n min = NULL,\n max = NULL,\n allow_infinite = TRUE,\n allow_na = FALSE,\n allow_null = FALSE,\n arg = caller_arg(x),\n call = caller_env()) {\n if (is_missing(x)) {\n exit_code <- IS_NUMBER_false\n } else if (0 == (exit_code <- .rlang_check_number(\n x,\n allow_decimal = TRUE,\n min = min,\n max = max,\n allow_infinite = allow_infinite,\n allow_na = allow_na,\n allow_null = allow_null\n ))) {\n return(invisible(NULL))\n }\n\n .stop_not_number(\n x,\n ...,\n exit_code = exit_code,\n allow_decimal = TRUE,\n min = min,\n max = max,\n allow_na = allow_na,\n allow_null = allow_null,\n arg = arg,\n call = call\n )\n}\n\n#' @importFrom rlang is_missing\nassert_number_whole <- function(x,\n ...,\n min = NULL,\n max = NULL,\n allow_infinite = FALSE,\n allow_na = FALSE,\n allow_null = FALSE,\n arg = caller_arg(x),\n call = caller_env()) {\n if (is_missing(x)) {\n exit_code <- IS_NUMBER_false\n } else if (0 == (exit_code <- .rlang_check_number(\n x,\n allow_decimal = FALSE,\n min = min,\n max = max,\n allow_infinite = allow_infinite,\n allow_na = allow_na,\n allow_null = allow_null\n ))) {\n return(invisible(NULL))\n }\n\n .stop_not_number(\n x,\n ...,\n exit_code = exit_code,\n allow_decimal = FALSE,\n min = min,\n max = max,\n allow_na = allow_na,\n allow_null = allow_null,\n arg = arg,\n call = call\n )\n}\n\n#' @importFrom rlang ffi_standalone_is_bool_1.0.7\nassert_bool <- function(x,\n ...,\n allow_na = FALSE,\n allow_null = FALSE,\n arg = caller_arg(x),\n call = caller_env()) {\n if (!missing(x) && .rlang_check_bool(x, allow_na, allow_null)) {\n return(invisible(NULL))\n }\n\n stop_input_type(\n x,\n c(\"`TRUE`\", \"`FALSE`\"),\n ...,\n allow_na = allow_na,\n allow_null = allow_null,\n arg = arg,\n call = call\n )\n}\n\n# atomic vector ------------------------------------\n#' @importFrom rlang abort\nassert_character <- function(x,\n ...,\n allow_na = TRUE,\n allow_null = FALSE,\n arg = caller_arg(x),\n call = caller_env()) {\n if (!missing(x)) {\n if (is.character(x)) {\n if (!allow_na && anyNA(x)) {\n abort(\n sprintf(\"`%s` can't contain NA values.\", arg),\n arg = arg, call = call\n )\n }\n return(invisible(NULL))\n }\n\n if (allow_null && is.null(x)) {\n return(invisible(NULL))\n }\n }\n stop_input_type(\n x,\n \"a character vector\",\n ...,\n allow_na = FALSE,\n allow_null = allow_null,\n arg = arg,\n call = call\n )\n}\n\n#' @importFrom rlang abort\nassert_logical <- function(x,\n ...,\n allow_na = TRUE,\n allow_null = FALSE,\n arg = caller_arg(x),\n call = caller_env()) {\n if (!missing(x)) {\n if (is.logical(x)) {\n if (!allow_na && anyNA(x)) {\n abort(\n sprintf(\"`%s` can't contain NA values.\", arg),\n arg = arg, call = call\n )\n }\n return(invisible(NULL))\n }\n if (allow_null && is.null(x)) {\n return(invisible(NULL))\n }\n }\n\n stop_input_type(\n x,\n \"a logical vector\",\n ...,\n allow_na = FALSE,\n allow_null = allow_null,\n arg = arg,\n call = call\n )\n}\n\n# S3 object ----------------------------------------\n#' @importFrom rlang is_string is_missing\nassert_s3_class <- function(x, is_class, what, ...,\n arg = caller_arg(x),\n call = caller_env()) {\n if (is.character(is_class)) {\n class <- is_class\n is_class <- function(x) inherits(x, what = class)\n if (is_missing(what)) what <- sprintf(\"a <%s>\", class)\n }\n assert_(\n x = x, check = is_class,\n what = what,\n ...,\n arg = arg, call = call\n )\n}\n\n# nocov end\n"], ["/ggalign/R/active.R", "#' Plot Adding Context Settings\n#'\n#' @description\n#' `r lifecycle::badge('experimental')`\n#'\n#' These settings control the behavior of the plot when added to a layout, as\n#' well as the arrangement of individual plot areas within the layout.\n#'\n#' @details\n#' By default, the active context is set only for functions that add plot areas.\n#' This allows other `ggplot2` elements-such as `geoms`, `stats`, `scales`, or\n#' `themes`- to be seamlessly added to the current plot area.\n#'\n#' The default ordering of the plot areas is from top to bottom or from left to\n#' right, depending on the layout orientation. However, users can customize this\n#' order using the `order` argument.\n#'\n#' @param order An integer specifying the order of the plot area within the\n#' layout.\n#' @param use A logical (`TRUE`/`FALSE`) indicating whether to set the\n#' active context to the current plot when added to a layout. If `TRUE`,\n#' any subsequent `ggplot` elements will be applied to this plot.\n#' @param name A string specifying the plot's name, useful for switching active\n#' contexts through the `what` argument in functions like\n#' [`quad_anno()`]/[`stack_switch()`].\n#' @export\nactive <- function(order = waiver(), use = waiver(), name = waiver()) {\n if (!is.waive(order)) order <- check_order(order)\n if (!is.waive(use)) assert_bool(use)\n if (!is.waive(name)) {\n assert_string(name,\n empty_ok = FALSE, allow_na = TRUE,\n allow_null = FALSE\n )\n }\n new_active(order = order, use = use, name = name)\n}\n\n# for internal function, we only adjust to the `use` argument\n# here, we put it in the first\nnew_active <- function(use, order = NA_integer_, name = NA_character_) {\n structure(\n list(order = order, use = use, name = name),\n class = \"ggalign_active\"\n )\n}\n\n#' @importFrom utils modifyList\nupdate_active <- function(active, default) {\n if (is.null(active)) return(default) # styler: off\n modifyList(default,\n active[!vapply(active, is.waive, logical(1L), USE.NAMES = FALSE)],\n keep.null = TRUE\n )\n}\n"], ["/ggalign/R/alignpatch-free-vp.R", "#' @inheritParams grid::viewport\n#' @inheritDotParams grid::viewport -x -y -width -height\n#' @return\n#' - `free_vp`: A modified version of `plot` with a `free_vp` class.\n#' @importFrom grid viewport\n#' @export\n#' @rdname free\nfree_vp <- function(plot, x = 0.5, y = 0.5, width = NA, height = NA, ...) {\n UseMethod(\"free_vp\")\n}\n\n#' @export\nfree_vp.default <- function(plot, x = 0.5, y = 0.5,\n width = NA, height = NA, ...) {\n cli_abort(\"Cannot use with {.obj_type_friendly {plot}}\")\n}\n\n#' @export\nfree_vp.ggplot <- function(plot, x = 0.5, y = 0.5,\n width = NA, height = NA, ...) {\n attr(plot, \"vp\") <- viewport(\n x = x, y = y, width = width, height = height, ...,\n )\n add_class(plot, \"free_vp\")\n}\n\n#' @export\nfree_vp.alignpatches <- free_vp.ggplot\n\n####################################################\n#' @importFrom gtable gtable_width gtable_height\n#' @importFrom ggplot2 ggproto ggproto_parent\n#' @export\nalignpatch.free_vp <- function(x) {\n Parent <- NextMethod()\n ggproto(\n \"PatchFreeViewport\", Parent,\n vp = attr(x, \"vp\"),\n align_border = function(self, t = NULL, l = NULL, b = NULL, r = NULL,\n gt = self$gt) {\n ans <- ggproto_parent(Parent, self)$align_border(\n t = t, l = l, b = b, r = r, gt = gt\n )\n vp <- self$vp\n\n if (!any(is_null_unit(widths <- .subset2(ans, \"widths\")))) {\n horizontal_just <- TRUE\n vp$width <- sum(widths)\n } else if (!is.na(as.numeric(vp$width))) {\n # we guess the width from the gtable\n horizontal_just <- TRUE\n vp$width <- max(vp$width, sum(widths))\n } else {\n vp$width <- unit(1, \"npc\")\n horizontal_just <- FALSE\n }\n if (!any(is_null_unit(heights <- .subset2(ans, \"heights\")))) {\n vertical_just <- TRUE\n vp$height <- sum(heights)\n } else if (!is.na(as.numeric(vp$height))) {\n # we guess the height from the gtable\n vertical_just <- TRUE\n vp$height <- max(vp$height, sum(heights))\n } else {\n vp$height <- unit(1, \"npc\")\n vertical_just <- FALSE\n }\n if (horizontal_just || vertical_just) ans$vp <- vp\n ans\n }\n )\n}\n"], ["/ggalign/R/alignpatch-free-border.R", "#' @param borders Which border shouldn't be aligned? A string containing one or\n#' more of `r oxford_and(.tlbr)`.\n#' @return\n#' - `free_border`: A modified version of `plot` with a `free_border` class.\n#' @export\n#' @rdname free\nfree_border <- function(plot, borders = \"tlbr\") {\n UseMethod(\"free_border\")\n}\n\n#' @export\nfree_border.ggplot <- function(plot, borders = \"tlbr\") {\n assert_position(borders)\n attr(plot, \"free_borders\") <- borders\n add_class(plot, \"free_border\")\n}\n\n#' @export\nfree_border.alignpatches <- free_border.ggplot\n\n#' @export\nfree_border.free_align <- function(plot, borders = \"tlbr\") {\n assert_position(borders)\n borders <- setdiff_position(borders, attr(plot, \"free_axes\"))\n if (!nzchar(borders)) {\n return(plot)\n }\n NextMethod()\n}\n\n#' @export\nfree_border.free_lab <- function(plot, borders = \"tlbr\") {\n assert_position(borders)\n free_labs <- setdiff_position(attr(plot, \"free_labs\"), borders)\n if (nzchar(free_labs)) {\n attr(plot, \"free_labs\") <- free_labs\n } else {\n attr(plot, \"free_labs\") <- NULL\n plot <- remove_class(plot, \"free_lab\")\n }\n NextMethod()\n}\n\n#' @export\nfree_border.free_border <- function(plot, borders = \"tlbr\") {\n assert_position(borders)\n attr(plot, \"free_borders\") <- union_position(\n attr(plot, \"free_borders\"), borders\n )\n plot\n}\n\n#' @export\nfree_border.default <- function(plot, borders = \"tlbr\") {\n cli_abort(\"Cannot use with {.obj_type_friendly {plot}}\")\n}\n\n################################################################\n#' @importFrom ggplot2 ggproto ggproto_parent\n#' @export\nalignpatch.free_border <- function(x) {\n Parent <- NextMethod()\n ggproto(\n \"PatchFreeBorder\", Parent,\n free_borders = setup_pos(attr(x, \"free_borders\")),\n collect_guides = function(self, guides, gt = self$gt) {\n ans <- ggproto_parent(Parent, self)$collect_guides(\n guides = guides, gt = gt\n )\n self$gt <- ggproto_parent(Parent, self)$free_border(\n borders = self$free_borders, gt = self$gt\n )\n ans\n },\n align_border = function(self, t = NULL, l = NULL, b = NULL, r = NULL,\n gt = self$gt) {\n gt <- ggproto_parent(Parent, self)$align_border(\n t = t, l = l, b = b, r = r, gt = gt\n )\n ggproto_parent(Parent, self)$align_free_border(\n borders = self$free_borders,\n t = t, l = l, b = b, r = r, gt = gt\n )\n },\n free_border = function(self, borders, gt = self$gt) {\n borders <- vec_set_difference(borders, self$free_borders)\n if (length(borders)) {\n gt <- ggproto_parent(Parent, self)$free_border(\n borders = borders, gt = gt\n )\n }\n gt\n },\n align_free_border = function(self, borders,\n t = NULL, l = NULL, b = NULL, r = NULL,\n gt = self$gt) {\n borders <- vec_set_difference(borders, self$free_borders)\n if (length(borders)) {\n gt <- ggproto_parent(Parent, self)$align_free_border(\n borders = borders,\n t = t, l = l, b = b, r = r, gt = gt\n )\n }\n gt\n }\n )\n}\n"], ["/ggalign/R/alignpatch-free-lab.R", "#' @param labs Which axis labs to be free? A string containing one or more of\n#' `r oxford_and(.tlbr)`.\n#' @return\n#' - `free_lab`: A modified version of `plot` with a `free_lab` class.\n#' @export\n#' @rdname free\nfree_lab <- function(plot, labs = \"tlbr\") {\n UseMethod(\"free_lab\")\n}\n\n#' @export\nfree_lab.ggplot <- function(plot, labs = \"tlbr\") {\n assert_position(labs)\n attr(plot, \"free_labs\") <- labs\n add_class(plot, \"free_lab\")\n}\n\n#' @export\nfree_lab.alignpatches <- free_lab.ggplot\n\n#' @export\nfree_lab.free_align <- function(plot, labs = \"tlbr\") {\n assert_position(labs)\n labs <- setdiff_position(labs, attr(plot, \"free_axes\"))\n if (!nzchar(labs)) return(plot) # styler: off\n NextMethod()\n}\n\n#' @export\nfree_lab.free_borders <- function(plot, labs = \"tlbr\") {\n assert_position(labs)\n labs <- setdiff_position(labs, attr(plot, \"free_borders\"))\n if (!nzchar(labs)) return(plot) # styler: off\n NextMethod()\n}\n\n#' @export\nfree_lab.free_lab <- function(plot, labs = \"tlbr\") {\n assert_position(labs)\n attr(plot, \"free_labs\") <- union_position(attr(plot, \"free_labs\"), labs)\n plot\n}\n\n#' @export\nfree_lab.default <- function(plot, labs = \"tlbr\") {\n cli_abort(\"Cannot use with {.obj_type_friendly {plot}}\")\n}\n\n####################################################\n#' @importFrom ggplot2 ggproto ggproto_parent\n#' @export\nalignpatch.free_lab <- function(x) {\n Parent <- NextMethod()\n ggproto(\n \"PatchFreeLab\", Parent,\n free_labs = setup_pos(attr(x, \"free_labs\")),\n collect_guides = function(self, guides, gt = self$gt) {\n ans <- ggproto_parent(Parent, self)$collect_guides(\n guides = guides, gt = gt\n )\n self$gt <- ggproto_parent(Parent, self)$free_lab(\n labs = self$free_labs, gt = self$gt\n )\n ans\n },\n free_lab = function(self, labs, gt = self$gt) {\n if (length(labs <- vec_set_difference(labs, self$free_labs))) {\n gt <- ggproto_parent(Parent, self)$free_lab(\n labs = labs, gt = gt\n )\n }\n gt\n }\n )\n}\n"], ["/ggalign/R/layer-order.R", "#' Change the layer adding order\n#'\n#' @description\n#' This function allows you to change the order in which layers are added to a\n#' ggplot.\n#'\n#' @param layer A [`layer geometry`][ggplot2::layer_geoms] object to be added.\n#' @param order An integer indicating the position at which the layer should be\n#' added. If `<= 0`, the layer will be added at the beginning. If greater than\n#' the number of plot layers, it will be added at the end.\n#' @return A `layer_order` object.\n#' @examples\n#' ggplot(faithfuld, aes(waiting, eruptions)) +\n#' geom_raster(aes(fill = density)) +\n#' geom_point(color = \"red\", size = 1)\n#' ggplot(faithfuld, aes(waiting, eruptions)) +\n#' geom_raster(aes(fill = density)) +\n#' layer_order(geom_point(color = \"red\", size = 1))\n#' @export\nlayer_order <- function(layer, order = 0) {\n assert_number_decimal(order)\n UseMethod(\"layer_order\")\n}\n\n#' @export\nlayer_order.default <- function(layer, order = 0) {\n cli_abort(\"{.arg layer} must be a {.fn geom_*} object\")\n}\n\n#' @export\nlayer_order.Layer <- function(layer, order = 0) {\n if (!is.infinite(order)) order <- vec_cast(order, integer())\n structure(\n list(\n object = layer,\n order = order,\n # used for `ggplot_add`\n object_name = paste(deparse(substitute(layer)), collapse = \" \")\n ),\n class = \"ggalign_layer_order\"\n )\n}\n\n#' @export\nlayer_order.ggalign_layer_order <- function(layer, order = 0) {\n if (!is.infinite(order)) order <- vec_cast(order, integer())\n layer$order <- order\n layer\n}\n\n#' @importFrom ggplot2 ggplot_add\n#' @export\nggplot_add.ggalign_layer_order <- function(object, plot, object_name, ...) {\n # ggplot2 will do something special for the layer\n # add layer_name, we re-call the method for the layer\n ans <- ggplot_add(\n .subset2(object, \"object\"),\n plot, .subset2(object, \"object_name\")\n )\n if ((cur <- length(layers <- ans$layers)) == 1L) {\n return(ans)\n }\n order <- .subset2(object, \"order\")\n layer <- .subset2(layers, cur)\n if (order >= length(layers)) return(ans) # styler: off\n if (order <= 0L) {\n layers <- append(vec_slice(layers, -cur), layer, 0L)\n } else {\n layers <- append(vec_slice(layers, -cur), layer, order)\n }\n ans$layers <- layers\n ans\n}\n"], ["/ggalign/R/layout-quad-operator.R", "# `subtract` operates at layout-level\n#' @keywords internal\nquad_layout_subtract <- function(object, quad, object_name) {\n UseMethod(\"quad_layout_subtract\")\n}\n\n#' @export\nquad_layout_subtract.default <- function(object, quad, object_name) {\n if (is.null(context <- quad@active)) context <- c(.TLBR, list(NULL))\n for (active in context) {\n if (is.null(active)) {\n quad <- quad_body_add(object, quad, object_name)\n } else if (!is.null(slot(quad, active))) {\n slot(quad, active) <- chain_layout_subtract(\n object, slot(quad, active), object_name\n )\n }\n }\n quad\n}\n\n# for object can set at layout level\n#' @export\nquad_layout_subtract.ggalign_scheme <- function(object, quad, object_name) {\n if (is.null(context <- quad@active)) {\n quad <- update_layout_scheme(object, quad, object_name)\n } else {\n slot(quad, context) <- update_layout_scheme(\n object, slot(quad, context), object_name\n )\n }\n quad\n}\n\n#' @export\nquad_layout_subtract.ggalign_with_quad <- function(object, quad, object_name) {\n old <- quad@active\n context <- quad_operated_context(object, old, \"-\")\n object <- .subset2(object, \"object\")\n object_name <- .subset2(object, \"object_name\")\n # `subtract` operates at layout-level\n if (is.null(context)) {\n quad@active <- context\n quad <- quad_layout_subtract(object, quad, object_name)\n } else {\n for (active in context) {\n if (is.null(active)) {\n quad <- quad_body_add(object, quad, object_name)\n } else if (!is.null(slot(quad, active))) {\n slot(quad, active) <- chain_layout_subtract(\n object, slot(quad, active), object_name\n )\n }\n }\n }\n quad@active <- old\n quad\n}\n\n###############################################################\n#' @keywords internal\nquad_layout_and_add <- function(object, quad, object_name) {\n UseMethod(\"quad_layout_and_add\")\n}\n\n#' @export\nquad_layout_and_add.default <- function(object, quad, object_name) {\n quad <- quad_body_add(object, quad, object_name)\n for (position in .TLBR) {\n stack <- slot(quad, position)\n if (is.null(stack)) next\n slot(quad, position) <- chain_layout_and_add(\n object, stack, object_name\n )\n }\n quad\n}\n\n#' @export\nquad_layout_and_add.ggalign_with_quad <- function(object, quad, object_name) {\n object <- .subset2(object, \"object\")\n object_name <- .subset2(object, \"object_name\")\n NextMethod()\n}\n\n#' @export\nquad_layout_and_add.theme <- function(object, quad, object_name) {\n ans <- NextMethod()\n # to align with `patchwork`, we also modify the layout theme\n # when using `&` to add the theme object.\n ans@theme <- ggfun(\"add_theme\")(ans@theme, object)\n ans\n}\n"], ["/ggalign/R/grid-grob-magick.R", "#' Rasterize a grob object with magick\n#'\n#' @param grob A [`grob()`][grid::grob]. Use [`patch()`] to convert any objects\n#' into a `grob`.\n#' @param magick A function (purrr-style formula is accepted) that takes an\n#' [`image_read()`][magick::image_read] object as input and returns an object\n#' compatible with [`as.raster()`][grDevices::as.raster]. You can use any of\n#' the `image_*()` functions from the **magick** package to process the raster\n#' image.\n#' @param res An integer sets the desired resolution in pixels.\n#' @inheritParams rlang::args_dots_empty\n#' @inheritParams grid::rasterGrob\n#' @return A `magickGrob` object.\n#' @export\nmagickGrob <- function(grob, magick = NULL, ...,\n res = NULL, interpolate = FALSE,\n name = NULL, vp = NULL) {\n rlang::check_installed(\"magick\", \"to use `magickGrob()`\")\n if (!is.null(magick) && !is.function(magick <- allow_lambda(magick))) {\n cli_abort(\"{.arg magick} must be a function\")\n }\n assert_number_whole(res, min = 1, allow_null = TRUE)\n assert_bool(interpolate)\n magickGrob0(\n grob = grob, magick = magick, ..., res = res,\n interpolate = interpolate, name = name, vp = vp\n )\n}\n\nmagickGrob0 <- function(grob, ...) UseMethod(\"magickGrob0\")\n\n#' @importFrom grid gTree\n#' @export\nmagickGrob0.grob <- function(grob, magick = NULL, ...,\n res = NULL, interpolate = FALSE,\n name = NULL, vp = NULL) {\n rlang::check_dots_empty()\n gTree(\n grob = grob, magick = magick, res = res,\n interpolate = interpolate, name = name, vp = vp,\n cl = \"magickGrob\"\n )\n}\n\n#' @importFrom grid gTree\n#' @export\nmagickGrob0.gList <- function(grob, ...) {\n magickGrob0(grob = gTree(children = grob), ...)\n}\n\n#' @importFrom grid editGrob\n#' @importFrom rlang inject\n#' @export\nmagickGrob0.magickGrob <- function(grob, magick = waiver(), ...,\n res = waiver(), interpolate = waiver(),\n name = waiver(), vp = waiver()) {\n rlang::check_dots_empty()\n params <- list(\n magick = magick, res = res,\n interpolate = interpolate, name = name, vp = vp\n )\n params <- params[!vapply(params, is.waive, logical(1L), USE.NAMES = FALSE)]\n inject(editGrob(grob, !!!params))\n}\n\n#' @export\nmagickGrob0.default <- function(grob, ...) {\n cli_abort(\"{.arg grob} must be a {.cls grob} object\")\n}\n\n# preDraw:\n# - makeContext\n# - pushvpgp\n# - preDrawDetails: by default, do noting\n# makeContent:\n# drawDetails:\n# postDraw:\n# - postDrawDetails: by default, do noting\n# - popgrobvp\n#' @importFrom grid makeContent unit convertHeight convertWidth viewport gList\n#' @export\nmakeContent.magickGrob <- function(x) {\n # Grab viewport information\n width <- convertWidth(unit(1, \"npc\"), \"pt\", valueOnly = TRUE)\n height <- convertHeight(unit(1, \"npc\"), \"pt\", valueOnly = TRUE)\n\n # Grab grob metadata\n plot_res <- convertWidth(unit(1, \"inch\"), \"pt\", valueOnly = TRUE)\n res <- .subset2(x, \"res\") %||% plot_res\n\n magick <- .subset2(x, \"magick\")\n interpolate <- .subset2(x, \"interpolate\")\n\n # Track current device\n old_dev <- grDevices::dev.cur()\n\n # Reset current device upon function exit\n on.exit(grDevices::dev.set(old_dev), add = TRUE)\n\n # open the magick raster device\n image <- magick::image_graph(\n width = width * res / plot_res,\n height = height * res / plot_res,\n bg = NA_character_, res = res,\n clip = FALSE, antialias = FALSE\n )\n\n # Render the grob\n grid::pushViewport(viewport())\n\n # Clean up the grob for rendering\n grid::grid.draw(.subset2(x, \"grob\")) # should respect the viewport of `x`\n grid::popViewport()\n grDevices::dev.off()\n on.exit(magick::image_destroy(image), add = TRUE)\n\n # run `magick` when necessary\n if (!is.null(magick)) image <- magick(image)\n\n # Use native raster instead\n raster <- grDevices::as.raster(image, native = TRUE)\n\n # Forward raster grob\n setChildren(x, children = gList(\n grid::rasterGrob(\n raster, # should contain current area of full viewport\n x = 0.5, y = 0.5,\n height = unit(height, \"pt\"),\n width = unit(width, \"pt\"),\n default.units = \"npc\",\n just = \"center\",\n interpolate = interpolate\n )\n ))\n}\n"], ["/ggalign/R/layout-chain-circle-switch.R", "#########################################################\n#' Determine the active context of circle layout\n#'\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' @inheritParams rlang::args_dots_empty\n#' @inheritParams circle_discrete\n#' @param what What should get activated for the [`circle_layout()`]?\n#' `r rd_chain_what()`.\n#' @return A `circle_switch` object which can be added to [`circle_layout()`].\n#' @examples\n#' set.seed(123)\n#' small_mat <- matrix(rnorm(56), nrow = 7)\n#' rownames(small_mat) <- paste0(\"row\", seq_len(nrow(small_mat)))\n#' colnames(small_mat) <- paste0(\"column\", seq_len(ncol(small_mat)))\n#' circle_discrete(small_mat) +\n#' ggalign() +\n#' geom_tile(aes(y = .column_index, fill = value)) +\n#' scale_fill_viridis_c() +\n#' align_dendro(aes(color = branch), k = 3L) +\n#' scale_color_brewer(palette = \"Dark2\")\n#' @export\ncircle_switch <- function(radial = waiver(), direction = NULL,\n what = waiver(), ...) {\n rlang::check_dots_empty()\n if (!is.waive(radial) && !is.null(radial)) {\n assert_s3_class(radial, \"CoordRadial\")\n if (abs(diff(radial$arc)) < pi / 2L) {\n cli_abort(\"Cannot use circle of acute angle < 90 in {.arg radial}\")\n }\n }\n if (!is.null(direction)) {\n direction <- arg_match0(direction, c(\"inward\", \"outward\"))\n }\n if (!is.waive(what)) what <- check_stack_context(what)\n structure(list(what = what, radial = radial, direction = direction),\n class = \"circle_switch\"\n )\n}\n"], ["/ggalign/R/alignpatch-patch.R", "#' Convert Object into a Grob\n#'\n#' The `patch()` function is used by [`ggwrap()`] and [inset()] to convert\n#' objects into a [`grob`][grid::grob].\n#'\n#' @param x An object to be converted into a [`grob`][grid::grob].\n#' @param ... Additional arguments passed to specific methods.\n#' @return A [`grob`][grid::grob] object.\n#' @eval rd_collect_family(\"patch\", \"`patch` method collections\")\n#' @export\n#' @keywords internal\npatch <- function(x, ...) {\n UseMethod(\"patch\")\n}\n\n# Following methods much are copied from `cowplot` or `ggplotify`\n#' @export\npatch.default <- function(x, ...) {\n cli_abort(\"Cannot make grob from {.obj_type_friendly {x}}\")\n}\n\n#' @inherit patch title description return\n#' @inheritParams patch\n#' @param ... Not used currently.\n#' @family patch\n#' @export\npatch.grob <- function(x, ...) {\n rlang::check_dots_empty()\n x\n}\n\n#' @importFrom grid gTree\n#' @export\n#' @rdname patch.grob\npatch.gList <- function(x, ...) {\n rlang::check_dots_empty()\n # gLists need to be wrapped in a gTree\n gTree(children = x)\n}\n\n#' @importFrom ggplot2 ggplotGrob\n#' @inherit patch.grob\n#' @seealso [ggplot][ggplot2::ggplot]\n#' @family patch\n#' @export\npatch.ggplot <- function(x, ...) {\n ggplotGrob(x, ...)\n}\n\n#' @inherit patch.grob\n#' @seealso\n#' - [`patch_titles()`]\n#' - [`inset()`]\n#' - [`ggwrap()`]\n#' @family patch\n#' @export\npatch.patch_ggplot <- function(x, ...) {\n ggalignGrob(x, ...)\n}\n\n#' @inherit patch.grob\n#' @seealso [`alignpatches`][align_plots]\n#' @family patch\n#' @export\npatch.alignpatches <- function(x, ...) {\n ggalignGrob(x, ...)\n}\n\n#' @inherit patch.grob\n#' @seealso [`patchwork`][patchwork::patchworkGrob]\n#' @family patch\n#' @export\npatch.patchwork <- function(x, ...) {\n rlang::check_installed(\"patchwork\", \"to make grob from patchwork\")\n patchwork::patchworkGrob(x, ...)\n}\n\n#' @inherit patch.grob\n#' @seealso [`patch`][patchwork::patchGrob]\n#' @family patch\n#' @export\npatch.patch <- function(x, ...) {\n rlang::check_installed(\"patchwork\", \"to make grob from patch\")\n patchwork::patchGrob(x, ...)\n}\n\n#' @inherit patch.grob\n#' @param ... Graphical Parameters passed on to [par()][graphics::par].\n#' @inheritParams gridGraphics::echoGrob\n#' @seealso [`plot()`]\n#' @family patch\n#' @export\npatch.formula <- function(x, ..., device = NULL, name = NULL) {\n rlang::check_installed(\"gridGraphics\", \"to make grob from base plot\")\n gp <- graphics::par(..., no.readonly = TRUE)\n gridGraphics::echoGrob(\n function() {\n old_gp <- graphics::par(no.readonly = TRUE)\n graphics::par(gp)\n on.exit(try(graphics::par(old_gp)))\n suppressMessages(eval(x[[2]], attr(x, \".Environment\")))\n invisible(NULL)\n },\n name = name,\n device = device %||% offscreen\n )\n}\n\n#' @export\n#' @rdname patch.formula\npatch.function <- function(x, ..., device = NULL, name = NULL) {\n rlang::check_installed(\"gridGraphics\", \"to make grob from base plot\")\n gp <- graphics::par(..., no.readonly = TRUE)\n gridGraphics::echoGrob(\n function() {\n old_gp <- graphics::par(no.readonly = TRUE)\n graphics::par(gp)\n on.exit(try(graphics::par(old_gp)))\n suppressMessages(x())\n invisible(NULL)\n },\n name = name,\n device = device %||% offscreen\n )\n}\n\n#' @inherit patch.grob\n#' @inheritParams gridGraphics::echoGrob\n#' @seealso [`recordPlot()`][grDevices::recordPlot]\n#' @family patch\n#' @export\npatch.recordedplot <- function(x, ..., device = NULL) {\n rlang::check_installed(\"gridGraphics\", \"to make grob from recordedplot\")\n rlang::check_dots_empty()\n gridGraphics::echoGrob(x, device = device %||% offscreen)\n}\n\noffscreen <- function(width, height) {\n if (requireNamespace(\"ragg\", quietly = TRUE)) {\n ragg::agg_capture(width = width, height = height, units = \"in\")\n grDevices::dev.control(\"enable\")\n } else {\n grDevices::pdf(NULL, width = width, height = height)\n grDevices::dev.control(\"enable\")\n }\n}\n\n#' @inherit patch.grob\n#' @inheritDotParams grid::grid.grabExpr -expr -device\n#' @inheritParams grid::grid.grabExpr\n#' @seealso [`trellis`][lattice::trellis.object]\n#' @family patch\n#' @export\npatch.trellis <- function(x, ..., device = NULL) {\n grid::grid.grabExpr(expr = print(x), ..., device = device %||% offscreen)\n}\n\n#' @inherit patch.grob\n#' @param ... Additional arguments passed to [draw()][ComplexHeatmap::draw].\n#' @inheritParams grid::grid.grabExpr\n#' @seealso\n#' - [`Heatmap()`][ComplexHeatmap::Heatmap]\n#' - [`HeatmapAnnotation()`][ComplexHeatmap::HeatmapAnnotation]\n#' @family patch\n#' @export\npatch.Heatmap <- function(x, ..., device = NULL) {\n rlang::check_installed(\n \"ComplexHeatmap\",\n sprintf(\"to make grob from %s plot\", obj_type_friendly(x))\n )\n draw <- getExportedValue(\"ComplexHeatmap\", \"draw\")\n grid::grid.grabExpr(\n expr = draw(object = x, ...),\n device = device %||% offscreen\n )\n}\n\n#' @export\n#' @rdname patch.Heatmap\npatch.HeatmapList <- patch.Heatmap\n\n#' @export\n#' @rdname patch.Heatmap\npatch.HeatmapAnnotation <- patch.HeatmapList\n\n#' @inherit patch.grob\n#' @seealso [`pheatmap()`][pheatmap::pheatmap]\n#' @family patch\n#' @export\npatch.pheatmap <- function(x, ...) {\n rlang::check_dots_empty()\n .subset2(x, \"gtable\")\n}\n"], ["/ggalign/R/layout-chain-stack-switch.R", "#########################################################\n#' Determine the active context of stack layout\n#'\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' `stack_active` is an alias for `stack_switch()`, which sets `what = NULL` by\n#' default.\n#'\n#' @inheritParams rlang::args_dots_empty\n#' @inheritParams quad_switch\n#' @inheritParams stack_discrete\n#' @param what What should get activated for the stack layout?\n#' `r rd_chain_what()`, this is useful when the active context is a\n#' [`quad_layout()`] object, where any `align_*()` will be added to the\n#' [`quad_layout()`]. By removing the active context, we can add `align_*()`\n#' into the [`stack_layout()`].\n#' @return A `stack_switch` object which can be added to [stack_layout()].\n#' @examples\n#' stack_discrete(\"h\", matrix(1:9, nrow = 3L)) +\n#' ggheatmap() +\n#' # ggheamtap will set the active context, directing following addition\n#' # into the heatmap plot area. To remove the heatmap active context,\n#' # we can use `stack_active()` which will direct subsequent addition into\n#' # the stack\n#' stack_active() +\n#' # here we add a dendrogram to the stack.\n#' align_dendro()\n#' @export\nstack_switch <- function(sizes = NULL, what = waiver(), ...) {\n rlang::check_dots_empty()\n if (!is.waive(what)) what <- check_stack_context(what)\n if (!is.null(sizes)) sizes <- check_stack_sizes(sizes)\n structure(list(what = what, sizes = sizes), class = \"stack_switch\")\n}\n\n#' @export\n#' @rdname stack_switch\nstack_active <- function(sizes = NULL, ...) {\n rlang::check_dots_empty()\n stack_switch(sizes, what = NULL)\n}\n"], ["/ggalign/R/fortify-matrix-.R", "#' Build a Matrix\n#'\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' This function converts various objects into a matrix format. By default, it\n#' calls [`as.matrix()`] to build a matrix.\n#'\n#' @param data An object to be converted into a matrix.\n#' @param ... Additional arguments passed to methods.\n#' @param data_arg The argument name for `data`. Developers can use it to\n#' improve messages. Not used by the user.\n#' @param call The execution environment where `data` and other arguments for\n#' the method are collected. Developers can use it to improve messages. Not\n#' used by the user.\n#' @return A matrix.\n#' @eval\n#' rd_collect_family(\"fortify_matrix\", \"`fortify_matrix` method collections\")\n#' @export\nfortify_matrix <- function(data, ..., data_arg = NULL,\n call = NULL) {\n UseMethod(\"fortify_matrix\")\n}\n\n#' @inheritParams rlang::args_dots_empty\n#' @inherit fortify_matrix title return\n#' @description\n#' By default, it calls [`as.matrix()`] to build a matrix.\n#' @inheritParams fortify_matrix\n#' @family fortify_matrix\n#' @importFrom rlang try_fetch\n#' @export\nfortify_matrix.default <- function(data, ..., data_arg = NULL,\n call = NULL) {\n call <- call %||% current_call()\n data_arg <- data_arg %||% \"data\"\n rlang::check_dots_empty(call = call)\n try_fetch(\n as.matrix(data),\n error = function(cnd) {\n cli_abort(\n paste0(\n \"{.arg {data_arg}} must be a {.cls matrix}, \",\n \"or an object coercible by {.fn fortify_matrix}, or a valid \",\n \"{.cls matrix}-like object coercible by {.fn as.matrix}\"\n ),\n call = call\n )\n }\n )\n}\n\n#' @export\nfortify_matrix.waiver <- function(data, ..., data_arg = NULL,\n call = NULL) {\n call <- call %||% current_call()\n rlang::check_dots_empty(call = call)\n data\n}\n\n#' @export\nfortify_matrix.NULL <- fortify_matrix.waiver\n\n#' @export\nfortify_matrix.function <- fortify_matrix.waiver\n\n#' @export\nfortify_matrix.formula <- function(data, ..., data_arg = NULL,\n call = NULL) {\n call <- call %||% current_call()\n rlang::check_dots_empty(call = call)\n rlang::as_function(data)\n}\n"], ["/ggalign/R/alignpatch-free-space.R", "#' @param spaces Which border spaces should be removed? A string containing one\n#' or more of `r oxford_and(.tlbr)`.\n#' @return\n#' - `free_space`: A modified version of `plot` with a `free_space` class.\n#' @export\n#' @rdname free\nfree_space <- function(plot, spaces = \"tlbr\") {\n UseMethod(\"free_space\")\n}\n\n#' @export\nfree_space.default <- function(plot, spaces = \"tlbr\") {\n cli_abort(\"Cannot use with {.obj_type_friendly {plot}}\")\n}\n\n#' @export\nfree_space.ggplot <- function(plot, spaces = \"tlbr\") {\n assert_position(spaces)\n attr(plot, \"free_spaces\") <- spaces\n add_class(plot, \"free_space\")\n}\n\n#' @export\nfree_space.alignpatches <- free_space.ggplot\n\n#' @export\nfree_space.free_align <- function(plot, spaces = \"tlbr\") {\n assert_position(spaces)\n spaces <- setdiff_position(spaces, attr(plot, \"free_axes\"))\n if (!nzchar(spaces)) {\n return(plot)\n }\n NextMethod()\n}\n\n#' @export\nfree_space.free_space <- function(plot, spaces = \"tlbr\") {\n assert_position(spaces)\n attr(plot, \"free_spaces\") <- union_position(\n attr(plot, \"free_spaces\"), spaces\n )\n plot\n}\n\n##########################################################\n#' @importFrom ggplot2 ggproto ggproto_parent\n#' @importFrom grid unit\n#' @export\nalignpatch.free_space <- function(x) {\n Parent <- NextMethod()\n ggproto(\n \"PatchFreeSpace\", Parent,\n free_spaces = split_position(attr(x, \"free_spaces\")),\n get_sizes = function(self, free = NULL, gt = self$gt) {\n ggproto_parent(Parent, self)$get_sizes(\n union(free, self$free_spaces),\n gt = gt\n )\n }\n )\n}\n"], ["/ggalign/R/utils-rd.R", "rd_layout <- function() {\n sprintf(\"%s or [`stack_layout()`] object\", rd_quad())\n}\n\nrd_quad <- function() \"[`quad_layout()`]/[`ggheatmap()`]\"\n\nrd_chain_what <- function() {\n paste(\n \"A single number or string of the plot elements in the layout.\",\n \"If `NULL`, will remove any active context\"\n )\n}\n\nrd_quad_position <- function(action) {\n sprintf(\n \"A string of %s indicates which annotation stack should be %s\",\n oxford_or(.TLBR),\n action\n )\n}\n\nrd_layout_data <- function() {\n paste(\n \"Default dataset to use for the layout. If not specified, it must be\",\n \"supplied in each plot added to the layout\"\n )\n}\n\nrd_gg_aesthetics <- function(...) {\n ans <- ggfun(\"rd_aesthetics\")(...)\n ans <- sub(\"link[=\", \"link[ggplot2:\", ans, fixed = TRUE)\n sub(\"(vignette\\\\([^)]+)\\\\)\", \"\\\\1, package = \\\"ggplot2\\\")\", ans)\n}\n"], ["/ggalign/R/alignpatch-inset.R", "#' Create a ggplot inset\n#'\n#' @inheritParams ggwrap\n#' @return A `patch_inset` object, which can be added in ggplot.\n#' @inherit patch seealso\n#' @examples\n#' library(grid)\n#' p1 <- ggplot(mtcars) +\n#' geom_point(aes(mpg, disp))\n#' p2 <- ggplot(mtcars) +\n#' geom_boxplot(aes(gear, disp, group = gear))\n#' p1 + inset(p2, vp = viewport(0.6, 0.6,\n#' just = c(0, 0), width = 0.4, height = 0.4\n#' ))\n#' @export\ninset <- function(\n plot,\n ...,\n align = \"panel\",\n on_top = TRUE,\n clip = TRUE,\n vp = NULL) {\n make_inset(\n plot = plot,\n ...,\n align = align,\n on_top = on_top,\n clip = clip,\n vp = vp\n )\n}\n\n#' @importFrom grid editGrob\n#' @importFrom rlang arg_match0\nmake_inset <- function(\n plot,\n ...,\n align,\n on_top,\n clip,\n vp,\n call = caller_call()) {\n assert_bool(on_top, call = call)\n align <- arg_match0(align, c(\"panel\", \"plot\", \"full\"), error_call = call)\n assert_bool(clip, call = call)\n assert_s3_class(vp, \"viewport\", allow_null = TRUE, call = call)\n if (!is.grob(grob <- patch(x = plot, ...))) {\n cli_abort(\"{.fn patch} must return a {.cls grob}\", call = call)\n }\n if (!is.null(vp)) grob <- editGrob(grob, vp = vp)\n structure(\n list(\n grob = grob,\n align = align,\n clip = if (clip) \"on\" else \"off\",\n on_top = on_top\n ),\n class = \"patch_inset\"\n )\n}\n\n#' @importFrom grid grid.draw\n#' @export\ngrid.draw.patch_inset <- function(x, recording = TRUE) {\n grid.draw(.subset2(x, \"grob\"))\n}\n\n#' @importFrom ggplot2 ggplot_add\n#' @export\nggplot_add.patch_inset <- function(object, plot, object_name, ...) {\n make_wrap(plot, object)\n}\n"], ["/ggalign/R/tune.R", "#' Change the shape of the input object\n#'\n#' @param data An R object.\n#' @param shape Usually `NULL` or a string, specifying the new shape for the\n#' object. Refer to the detailed method for allowed values.\n#' @details\n#' In most cases, [`fortify_matrix()`] or [`fortify_data_frame()`] provide full\n#' support for transforming objects. However, some objects may require two\n#' completely different approaches to be fortified. The `tune` function acts as\n#' a helper to create a new class tailored for these objects.\n#' @eval rd_collect_family(\"tune\", \"`tune` method collections\")\n#' @export\ntune <- function(data, shape = NULL) UseMethod(\"tune\")\n\n#' @inherit tune title\n#' @description\n#' - `new_tune`: Creates a new object by wrapping it in a scalar list with\n#' the specified attributes and class.\n#' - `tune_data`: Retrieves the original input data.\n#'\n#' @param x An R object.\n#' @param ... Additional attributes passed to [`structure()`].\n#' @param class A character vector specifying the class name to be added.\n#' @export\nnew_tune <- function(x, ..., class = character()) {\n structure(list(x), ..., class = c(class, \"ggalign_tune\"))\n}\n\n#' @export\n#' @rdname new_tune\ntune_data <- function(x) .subset2(x, 1L)\n\n#' @export\nprint.ggalign_tune <- function(x, ...) {\n print(tune_data(x))\n invisible(x)\n}\n\n#' @export\nfortify_matrix.ggalign_tune <- function(data, ...) {\n cli_abort(\"No {.fn fortify_matrix} method for {.obj_type_friendly {data}}\")\n}\n\n#' @export\nfortify_data_frame.ggalign_tune <- function(data, ...) {\n cli_abort(\n \"No {.fn fortify_data_frame} method for {.obj_type_friendly {data}}\"\n )\n}\n"], ["/ggalign/R/object-name.R", "format_object_name <- function(name, format = NULL) {\n if (is.null(format)) {\n name\n } else {\n sprintf(\"{.%s %s}\", format, name)\n }\n}\n\nobject_name <- function(object, format) UseMethod(\"object_name\")\n\n#' @export\nobject_name.StackLayout <- function(object, format = \"fn\") {\n ans <- format_object_name(object@name, format)\n if (!is.null(position <- .subset2(object@heatmap, \"position\"))) {\n ans <- sprintf(\"the %s annotation %s\", position, ans)\n } else {\n ans <- sprintf(\"the %s %s\", object@direction, ans)\n }\n ans\n}\n\n#' @export\nobject_name.CircleLayout <- function(object, format = \"fn\") {\n format_object_name(object@name, format)\n}\n\n#' @export\nobject_name.QuadLayout <- function(object, format = \"fn\") {\n format_object_name(object@name, format)\n}\n\n#' @export\nobject_name.CraftBox <- function(object, format = \"fn\") {\n object_name(object@craftsman, format)\n}\n\n#' @export\nobject_name.Craftsman <- function(object, format = \"fn\") {\n format_object_name(snake_class(object), format)\n}\n\n#' @export\nobject_name.AlignGg <- function(object, format = \"fn\") {\n format_object_name(\"ggalign\", format)\n}\n\n#' @export\nobject_name.CrossGg <- function(object, format = \"fn\") {\n format_object_name(\"ggcross\", format)\n}\n\n#' @export\nobject_name.FreeGg <- function(object, format = \"fn\") {\n format_object_name(\"ggfree\", format)\n}\n\n#' @export\nobject_name.MarkGg <- function(object, format = \"fn\") {\n format_object_name(\"ggmark\", format)\n}\n"], ["/ggalign/R/import-standalone-purrr.R", "# Standalone file: do not edit by hand\n# Source: \n# ----------------------------------------------------------------------\n#\n# ---\n# repo: Yunuuuu/standalone\n# file: standalone-purrr.R\n# last-updated: 2024-11-13\n# license: https://unlicense.org\n# ---\n\n# This file provides a minimal shim to provide a purrr-like API on top of\n# base R functions. They are not drop-in replacements but allow a similar style\n# of programming.\n#\n# Note: these functions won't support lambda syntax.\n\n# ## Changelog\n# 2024-11-13:\n# rename `transpose()` to `list_transpose()`\n#\n# 2024-11-12:\n# First release\n#\n# nocov start\n\nmap <- function(.x, .f, ...) lapply(.x, .f, ...)\n\nwalk <- function(.x, .f, ...) {\n lapply(.x, .f, ...)\n invisible(.x)\n}\n\nmap_lgl <- function(.x, .f, ...) {\n vapply(X = .x, FUN = .f, logical(1L), ...)\n}\n\nmap_int <- function(.x, .f, ...) {\n vapply(X = .x, FUN = .f, integer(1L), ...)\n}\n\nmap_dbl <- function(.x, .f, ...) {\n vapply(X = .x, FUN = .f, double(1L), ...)\n}\n\nmap_chr <- function(.x, .f, ...) {\n vapply(X = .x, FUN = .f, character(1L), ...)\n}\n\npmap <- function(.l, .f, ...) {\n out <- .mapply(.f, .l, list(...))\n if (!is.null(nms <- names(.subset2(.l, 1L)))) names(out) <- nms\n out\n}\n\npmap_lgl <- function(.l, .f, ...) {\n .purrr_pmap_mold(.l, .f, ..., mold = logical(1L))\n}\n\npmap_int <- function(.l, .f, ...) {\n .purrr_pmap_mold(.l, .f, ..., mold = integer(1L))\n}\n\npmap_dbl <- function(.l, .f, ...) {\n .purrr_pmap_mold(.l, .f, ..., mold = double(1L))\n}\n\npmap_chr <- function(.l, .f, ...) {\n .purrr_pmap_mold(.l, .f, ..., mold = character(1L))\n}\n\n.purrr_pmap_mold <- function(.l, .f, ..., mold) {\n nms <- names(.subset2(.l, 1L))\n dots <- list(...)\n out <- vapply(seq_along(nms), function(i) {\n do.call(.f, args = c(lapply(.l, .subset2, i), dots))\n }, mold, USE.NAMES = FALSE)\n if (!is.null(nms)) names(out) <- nms\n out\n}\n\nmap2 <- function(.x, .y, .f, ...) pmap(list(.x, .y), .f, ...)\n\nmap2_lgl <- function(.x, .y, .f, ...) {\n .purrr_pmap_mold(list(.x, .y), .f, ..., mold = logical(1L))\n}\n\nmap2_int <- function(.x, .y, .f, ...) {\n .purrr_pmap_mold(list(.x, .y), .f, ..., mold = integer(1L))\n}\n\nmap2_dbl <- function(.x, .y, .f, ...) {\n .purrr_pmap_mold(list(.x, .y), .f, ..., mold = double(1L))\n}\n\nmap2_chr <- function(.x, .y, .f, ...) {\n .purrr_pmap_mold(list(.x, .y), .f, ..., mold = character(1L))\n}\n\nimap <- function(.x, .f, ...) {\n nms <- names(.x)\n if (is.null(nms)) {\n .l <- list(.x, seq_along(.x))\n } else {\n .l <- list(.x, nms)\n }\n pmap(.l, .f, ...)\n}\n\n.purrr_imap_mold <- function(.x, .f, ..., mold) {\n if (is.null(nms <- names(.x))) {\n .l <- list(.x, seq_along(.x))\n } else {\n .l <- list(.x, nms)\n }\n .purrr_pmap_mold(.l, .f, ..., mold = mold)\n}\n\nimap_lgl <- function(.l, .f, ...) {\n .purrr_imap_mold(.l, .f, ..., mold = logical(1L))\n}\n\nimap_int <- function(.l, .f, ...) {\n .purrr_imap_mold(.l, .f, ..., mold = integer(1L))\n}\n\nimap_dbl <- function(.l, .f, ...) {\n .purrr_imap_mold(.l, .f, ..., mold = double(1L))\n}\n\nimap_chr <- function(.l, .f, ...) {\n .purrr_imap_mold(.l, .f, ..., mold = character(1L))\n}\n\nlist_transpose <- function(.l) {\n if (!length(.l)) return(.l) # styler: off\n inner_names <- names(.subset2(.l, 1L))\n if (is.null(inner_names)) {\n fields <- seq_along(.subset2(.l, 1L))\n } else {\n fields <- inner_names\n names(fields) <- fields\n .l <- lapply(.l, function(x) {\n if (is.null(names(x))) names(x) <- inner_names # styler: off\n x\n })\n }\n\n # This way missing fields are subsetted as `NULL` instead of causing\n # an error\n .l <- lapply(.l, as.list)\n\n lapply(fields, function(i) lapply(.l, .subset2, i))\n}\n\n# nocov end\n"], ["/ggalign/R/alignpatch-free-guide.R", "#' @param guides A string containing one or more of\n#' `r oxford_and(c(.tlbr, \"i\"))` indicates which side of guide legends should be\n#' collected for the plot. If `NULL`, no guide legends will be collected.\n#' @return\n#' - `free_guide`: A modified version of `plot` with a `free_guide` class.\n#' @export\n#' @rdname free\nfree_guide <- function(plot, guides = \"tlbr\") {\n UseMethod(\"free_guide\")\n}\n\n#' @export\nfree_guide.ggplot <- function(plot, guides = \"tlbr\") {\n if (!is.null(guides)) assert_guides(guides)\n attr(plot, \"free_guides\") <- guides\n add_class(plot, \"free_guide\")\n}\n\n#' @export\nfree_guide.alignpatches <- free_guide.ggplot\n\n#' @export\nfree_guide.free_guide <- function(plot, guides = \"tlbr\") {\n if (is.null(guides)) {\n attr(plot, \"free_guides\") <- NULL\n } else {\n assert_guides(guides)\n if (is.null(old <- attr(plot, \"free_guides\", exact = TRUE))) {\n attr(plot, \"free_guides\") <- guides\n } else {\n attr(plot, \"free_guides\") <- union_position(old, guides)\n }\n }\n plot\n}\n\n################################################################\n#' @importFrom ggplot2 ggproto ggproto_parent\n#' @export\nalignpatch.free_guide <- function(x) {\n Parent <- NextMethod()\n if (!is.null(free_guides <- attr(x, \"free_guides\", exact = TRUE))) {\n free_guides <- setup_guides(free_guides)\n }\n ggproto(\"PatchFreeGuide\", Parent,\n set_guides = function(self, guides) free_guides\n )\n}\n"], ["/ggalign/R/rasterise.R", "rasterise.QuadLayout <- function(input, ...) {\n input@plot <- ggrastr::rasterise(input = input@plot, ...)\n for (position in .TLBR) {\n stack <- slot(input, position)\n if (is.null(stack)) next\n slot(input, position) <- ggrastr::rasterise(input = stack, ...)\n }\n input\n}\n\nrasterise.ChainLayout <- function(input, ...) {\n input@plot_list <- lapply(input@plot_list, ggrastr::rasterise, ...)\n input\n}\n\nrasterise.CraftBox <- function(input, ...) {\n if (!is.null(plot <- input@plot)) {\n input@plot <- ggrastr::rasterise(input = plot, ...)\n }\n input\n}\n\n##########################################################\n#' @export\nraster_magick0.QuadLayout <- function(x, ...) {\n x@plot <- raster_magick0(x = x@plot, ...)\n for (position in .TLBR) {\n stack <- slot(x, position)\n if (is.null(stack)) next\n slot(x, position) <- raster_magick0(x = stack, ...)\n }\n x\n}\n\n#' @export\nraster_magick0.ChainLayout <- function(x, ...) {\n x@plot_list <- lapply(x@plot_list, raster_magick0, ...)\n x\n}\n\n\n#' @export\nraster_magick0.CraftBox <- function(x, ...) {\n if (!is.null(plot <- input@plot)) {\n input@plot <- raster_magick0(x = plot, ...)\n }\n input\n}\n"], ["/ggalign/R/ggalign-package.R", "#' @keywords internal\n\"_PACKAGE\"\n\n## usethis namespace: start\n#' @import vctrs\n#' @importFrom lifecycle deprecated\n#' @importFrom rlang .data .env\n#' @importFrom cli cli_abort cli_warn cli_inform\n## usethis namespace: end\nNULL\n\n# enable usage of @name in package code\n#' @rawNamespace if (getRversion() < \"4.3.0\") importFrom(\"S7\", \"@\")\nNULL\n"], ["/ggalign/R/zzz.R", "#' @importFrom S7 methods_register\n.onLoad <- function(libname, pkgname) {\n # register ggplot2 theme elements\n theme_elements()\n\n # register method for\n s3_register(\"ggrastr::rasterise\", \"CraftBox\")\n s3_register(\"ggrastr::rasterise\", \"QuadLayout\")\n s3_register(\"ggrastr::rasterise\", \"ChainLayout\")\n\n methods_register()\n invisible()\n}\n"]], "task_instance_info": {"created_time": "2025-08-21 01:14:14", "created_task_model": "DeepSeek-R1", "function_skeleton": "function(self, plot, schemes, theme) {}", "code_description": "This code segment functions to: Modify the visual presentation of plot components by adjusting spacing parameters and applying theme customizations while conditionally removing axis elements based on layout orientation."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```r\n[TASK_BEGIN]\n finish_plot = function(self, plot, schemes, theme) {\n plot <- ggproto_parent(CraftCross, self)$finish_plot(plot, schemes, theme)\n plot <- use_scheme(plot, schemes)\n plot + theme\n }\n[TASK_END]\n```", "inference_time": "2025-08-21 01-14-29"}, "editdistance_info": {"edit_distance": 16.5563, "calculate_time": "2025-08-21 01:14:29", "true_code_clean": "function(self, plot, schemes, theme) {\n direction <- self$direction\n if (isTRUE(self$no_axes)) {\n schemes$scheme_theme <- .subset2(schemes, \"scheme_theme\") +\n theme_no_axes(switch_direction(direction, \"y\", \"x\"))\n }\n plot <- plot_add_schemes(plot, schemes)\n if (is_horizontal(direction)) {\n theme <- theme(\n panel.spacing.y = calc_element(\"panel.spacing.y\", theme)\n )\n } else {\n theme <- theme(\n panel.spacing.x = calc_element(\"panel.spacing.x\", theme)\n )\n }\n plot <- plot + theme\n ggremove_margin(plot, direction) + theme_recycle()\n }", "predict_code_clean": "finish_plot = function(self, plot, schemes, theme) {\n plot <- ggproto_parent(CraftCross, self)$finish_plot(plot, schemes, theme)\n plot <- use_scheme(plot, schemes)\n plot + theme\n }"}} {"repo_name": "ggalign", "file_name": "/ggalign/R/utils-assert.R", "inference_info": {"prefix_code": "# `assert_*()` functions will do the side effects\n# `check_*()` functions will return the arguments\n#' @importFrom rlang caller_arg caller_call\nassert_gp <- function(gp, arg = caller_arg(gp), call = caller_call()) {\n assert_s3_class(gp, \"gpar\", arg = arg, call = call)\n}\n\n#' @importFrom rlang caller_arg caller_call\nassert_mapping <- function(mapping, arg = caller_arg(mapping),\n call = caller_call()) {\n if (!inherits(mapping, \"uneval\")) {\n cli_abort(c(\"{.arg {arg}} must be created with {.fn aes}.\",\n x = \"You've supplied {.obj_type_friendly {mapping}}.\"\n ), call = call)\n }\n}\n\nassert_mismatch_nobs <- function(align, n, nobs, arg) {\n if (n != nobs) {\n cli_abort(sprintf(\n \"{.arg %s} (nobs: %d) of %s is not compatible with the %s (nobs: %d)\",\n arg, nobs, object_name(align), align$layout_name, n\n ))\n }\n}\n\nassert_sub_split <- function(align, panel) {\n if (!is.null(panel)) {\n cli_abort(c(\n sprintf(\"%s cannot do sub-split\", object_name(align)),\n i = sprintf(\n \"Group of layout %s-axis already exists\",\n to_coord_axis(align$direction)\n )\n ), call = align$call)\n }\n}\n\nassert_reorder <- function(align, panel, index, strict) {\n if (!is.null(panel) && nlevels(panel) > 1L && strict &&\n !all(index == reorder_index(panel, index))) {\n layout_name <- align$layout_name\n object_name <- object_name(align)\n cli_abort(c(\n sprintf(\"Cannot add %s to %s\", object_name, layout_name),\n i = sprintf(\n \"Group of %s will disrupt the ordering index of %s\", layout_name, object_name\n ),\n i = \"try to set {.code strict = FALSE} to reorder within each group\"\n ), call = align$call)\n }\n}\n\nassert_position <- function(position, arg = caller_arg(position),\n call = caller_call()) {\n assert_string(position, empty_ok = FALSE, arg = arg, call = call)\n if (grepl(\"[^tlbr]\", position)) {\n cli_abort(sprintf(\n \"{.arg {arg}} can only contain the %s characters\",\n oxford_and(.tlbr)\n ), call = call)\n }\n}\n\nassert_guides <- function(guides, arg = caller_arg(guides),\n call = caller_call()) {\n assert_string(guides, empty_ok = FALSE, arg = arg, call = call)\n if (grepl(\"[^tlbri]\", guides)) {\n cli_abort(sprintf(\n \"{.arg {arg}} can only contain the %s characters\",\n oxford_and(c(.tlbr, \"i\"))\n ), call = call)\n }\n}\n\nassert_layout_position <- function(position, arg = caller_arg(position),\n call = caller_call()) {\n if (!is.waive(position) && !is.null(position)) {\n assert_position(position, arg = arg, call = call)\n }\n}\n\nassert_layout_guides <- function(guides, arg = caller_arg(guides),\n call = caller_call()) {\n if (!is.waive(guides) && !is.null(guides)) {\n assert_guides(guides, arg = arg, call = call)\n }\n}\n\n#' @importFrom grid is.unit\ncheck_stack_sizes <- function(sizes, arg = caller_arg(sizes),\n call = caller_call()) {\n if (!(all(is.na(sizes)) || is.numeric(sizes) || is.unit(sizes))) {\n cli_abort(\n \"{.arg {arg}} must be a numeric or {.cls unit} object\",\n call = call\n )\n }\n l <- length(sizes)\n if (l != 1L && l != 3L) {\n cli_abort(\n \"{.arg {arg}} must have size `1` or `3`, not size {l}\",\n call = call\n )\n }\n if (!is.unit(sizes)) sizes <- unit(sizes, \"null\")\n sizes\n}\n\n#' @importFrom rlang arg_match0\ncheck_direction <- function(direction, arg = caller_arg(direction),\n call = caller_call()) {\n direction <- arg_match0(direction, c(\"h\", \"v\"),\n arg_nm = arg, error_call = call\n )\n switch(direction, h = \"horizontal\", v = \"vertical\") # styler: off\n}\n\nassert_limits <- function(limits, allow_null = TRUE, arg = caller_arg(limits),\n call = caller_call()) {\n if (is.null(limits) && allow_null) {\n return(invisible(NULL))\n }\n if (!inherits(limits, \"continuous_limits\")) {\n cli_abort(\n \"{.arg {arg}} must be specified with {.fn continuous_limits}\",\n call = call\n )\n }\n if (rlang::is_named(limits)) {\n cli_abort(\n \"{.arg {arg}} shouldn't be created with {.arg x}/{.arg y} argument in {.fn continuous_limits}\",\n call = call\n )\n }\n}\n\n#' @importFrom grid is.unit\ncheck_size <- function(size, arg = caller_arg(size), call = caller_call()) {\n if (!is_scalar(size) &&\n !(is.na(size) || is.numeric(size) || is.unit(size))) {\n cli_abort(\n \"{.arg {arg}} must be a single numeric or unit object\",\n call = call\n )\n }\n if (!is.unit(size)) size <- unit(size, \"null\")\n size\n}\n\ncheck_scheme_data <- ", "suffix_code": "\n\ncheck_stack_context <- function(what, arg = caller_arg(what),\n call = caller_call()) {\n if (is.null(what)) return(what) # styler: off\n if (.rlang_check_number(what, allow_decimal = FALSE, min = 1) != 0L &&\n !is_string(what)) {\n cli_abort(\n \"{.arg {arg}} must be a single positive integer number or string\",\n call = call\n )\n }\n what\n}\n\ncheck_order <- function(order, arg = caller_arg(order), call = caller_call()) {\n if (is.null(order)) {\n NA_integer_\n } else if (.rlang_check_number(order, allow_decimal = FALSE) == 0L) {\n as.integer(order)\n } else {\n cli_abort(\"{.arg {arg}} must be single integer number\", call = call)\n }\n}\n\nassert_align <- function(x, arg = caller_arg(x), call = caller_call()) {\n if (!inherits(x, \"scheme_align\")) {\n cli_abort(\n \"{.arg {arg}} must be created by {.fn scheme_align}\",\n call = call\n )\n }\n}\n\nassert_active <- function(x, allow_null = TRUE,\n arg = caller_arg(x), call = caller_call()) {\n if (is.null(x) && allow_null) {\n return(invisible(NULL))\n }\n if (!inherits(x, \"ggalign_active\")) {\n cli_abort(\n \"{.arg {arg}} must be created by {.fn active}\",\n call = call\n )\n }\n}\n\nassert_obs_size <- function(obs_size, arg = caller_arg(obs_size),\n call = caller_call()) {\n if (.rlang_check_number(obs_size, allow_decimal = TRUE, # styler: off\n .Machine$double.eps, 1) != 0L) { # styler: off\n cli_abort(\n \"{.arg {arg}} must be a single number in `(0, 1]`\",\n call = call\n )\n }\n}\n", "middle_code": "function(data, arg = caller_arg(data),\n call = caller_call()) {\n if (!is.waive(data) && !is.null(data) &&\n !is.function(data <- allow_lambda(data))) {\n cli_abort(paste(\n \"{.arg {arg}} must be a function,\",\n \"{.code NULL} or {.fn waiver}\"\n ), call = call)\n }\n data\n}", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "r", "sub_task_type": null}, "context_code": [["/ggalign/R/import-standalone-assert.R", "# Standalone file: do not edit by hand\n# Source: https://github.com/Yunuuuu/standalone/blob/HEAD/R/standalone-assert.R\n# Generated by: usethis::use_standalone(\"Yunuuuu/standalone\", \"assert\")\n# ----------------------------------------------------------------------\n#\n# ---\n# repo: Yunuuuu/standalone\n# file: standalone-assert.R\n# last-updated: 2025-04-16\n# license: https://unlicense.org\n# dependencies: [standalone-obj-type.R]\n# imports: rlang\n# ---\n\n# ## Changelog\n# 2025-04-16:\n# - `assert_number_whole` gains `allow_infinite` argument\n#\n# 2025-04-11:\n# - new `.rlang_allow_number`\n# - new `.rlang_check_number`\n# - new `.rlang_check_bool`\n# - new `.rlang_check_string`\n#\n# 2024-11-10:\n# - Added support for S3 object\n#\n# nocov start\n# Following codes were modified from `rlang` package\n\n#' Report if an argument is a specific class\n#'\n#' @param x The object type which does not conform to `what`. Its\n#' `obj_type_friendly()` is taken and mentioned in the error message.\n#' @param what The friendly expected type as a string. Can be a\n#' character vector of expected types, in which case the error\n#' message mentions all of them in an \"or\" enumeration.\n#' @param show_value Passed to `value` argument of `obj_type_friendly()`.\n#' @param show_length Passed to `length` argument of `obj_type_friendly()`.\n#' @param ... Arguments passed to [rlang::abort()].\n#' @importFrom rlang is_missing\n#' @noRd\nassert_ <- function(x, check, what,\n allow_null = FALSE,\n allow_na = FALSE,\n show_value = TRUE,\n show_length = FALSE,\n ...,\n arg = caller_arg(x),\n call = caller_env()) {\n if (!is_missing(x) && (\n (allow_null && is.null(x)) || check(x)\n )) {\n return(invisible(NULL))\n }\n stop_input_type(x, what,\n allow_na = allow_na,\n allow_null = allow_null,\n show_value = show_value,\n show_length = show_length,\n ...,\n arg = arg, call = call\n )\n}\n\nIS_NUMBER_true <- 0\nIS_NUMBER_false <- 1\nIS_NUMBER_oob <- 2\n\n.standalone_types_check_assert_call <- .Call\n\n#' @importFrom rlang ffi_standalone_check_number_1.0.7\n.rlang_check_number <- function(x, allow_decimal,\n min = NULL,\n max = NULL,\n allow_infinite = allow_decimal,\n allow_na = FALSE,\n allow_null = FALSE) {\n .standalone_types_check_assert_call(\n ffi_standalone_check_number_1.0.7,\n x,\n allow_decimal,\n min,\n max,\n allow_infinite,\n allow_na,\n allow_null\n )\n}\n\n#' @importFrom rlang ffi_standalone_is_bool_1.0.7\n.rlang_check_bool <- function(x, allow_na = FALSE, allow_null = FALSE) {\n .standalone_types_check_assert_call(\n ffi_standalone_is_bool_1.0.7,\n x,\n allow_na,\n allow_null\n )\n}\n\n#' @importFrom rlang is_string\n.rlang_check_string <- function(x, allow_empty = TRUE,\n allow_na = FALSE, allow_null = FALSE) {\n if (is_string(x) && !is.na(x)) {\n if (allow_empty || x != \"\") {\n return(TRUE)\n }\n }\n\n if (allow_null && is.null(x)) {\n return(TRUE)\n }\n\n if (allow_na && (identical(x, NA) || identical(x, NA_character_))) {\n return(TRUE)\n }\n\n FALSE\n}\n\n#' @importFrom rlang abort\n.rlang_allow_number <- function(x, exit_code, allow_decimal,\n min = NULL,\n max = NULL,\n allow_na = FALSE,\n allow_null = FALSE) {\n if (allow_decimal) {\n what <- \"a number\"\n } else {\n what <- \"a whole number\"\n }\n if (exit_code == IS_NUMBER_oob) {\n min <- min %||% -Inf\n max <- max %||% Inf\n\n if (min > -Inf && max < Inf) {\n what <- sprintf(\"%s between %s and %s\", what, min, max)\n } else if (x < min) {\n what <- sprintf(\"%s larger than or equal to %s\", what, min)\n } else if (x > max) {\n what <- sprintf(\"%s smaller than or equal to %s\", what, max)\n } else {\n abort(\"Unexpected state in OOB check\", .internal = TRUE)\n }\n }\n allow_what_type(what, allow_na = allow_na, allow_null = allow_null)\n}\n\n# scalar object ----------------------------------\nassert_string <- function(x,\n ...,\n allow_empty = TRUE,\n allow_na = FALSE,\n allow_null = FALSE,\n arg = caller_arg(x),\n call = caller_env()) {\n assert_(\n x = x,\n check = function(x) {\n .rlang_check_string(\n x,\n allow_empty = allow_empty,\n allow_na = allow_na,\n allow_null = allow_null\n )\n },\n what = \"a single string\",\n ...,\n allow_na = allow_na,\n allow_null = allow_null,\n arg = arg,\n call = call\n )\n}\n\n#' @importFrom rlang abort\n.stop_not_number <- function(x,\n exit_code,\n allow_decimal,\n ...,\n min = NULL,\n max = NULL,\n allow_na = FALSE,\n allow_null = FALSE,\n show_value = TRUE,\n show_length = FALSE,\n arg = caller_arg(x),\n call = caller_env()) {\n what <- .rlang_allow_number(\n x = x,\n exit_code = exit_code,\n allow_decimal = allow_decimal,\n min = min, max = max,\n allow_na = allow_na,\n allow_null = allow_null\n )\n if (inherits(arg, \"AsIs\")) {\n format_arg <- identity\n } else {\n format_arg <- function(x) sprintf(\"`%s`\", x)\n }\n message <- sprintf(\n \"%s must be %s, not %s.\",\n format_arg(arg), what,\n obj_type_friendly(x, value = show_value, length = show_length)\n )\n abort(message, ..., call = call, arg = arg)\n}\n\n#' @importFrom rlang is_missing\nassert_number_decimal <- function(x,\n ...,\n min = NULL,\n max = NULL,\n allow_infinite = TRUE,\n allow_na = FALSE,\n allow_null = FALSE,\n arg = caller_arg(x),\n call = caller_env()) {\n if (is_missing(x)) {\n exit_code <- IS_NUMBER_false\n } else if (0 == (exit_code <- .rlang_check_number(\n x,\n allow_decimal = TRUE,\n min = min,\n max = max,\n allow_infinite = allow_infinite,\n allow_na = allow_na,\n allow_null = allow_null\n ))) {\n return(invisible(NULL))\n }\n\n .stop_not_number(\n x,\n ...,\n exit_code = exit_code,\n allow_decimal = TRUE,\n min = min,\n max = max,\n allow_na = allow_na,\n allow_null = allow_null,\n arg = arg,\n call = call\n )\n}\n\n#' @importFrom rlang is_missing\nassert_number_whole <- function(x,\n ...,\n min = NULL,\n max = NULL,\n allow_infinite = FALSE,\n allow_na = FALSE,\n allow_null = FALSE,\n arg = caller_arg(x),\n call = caller_env()) {\n if (is_missing(x)) {\n exit_code <- IS_NUMBER_false\n } else if (0 == (exit_code <- .rlang_check_number(\n x,\n allow_decimal = FALSE,\n min = min,\n max = max,\n allow_infinite = allow_infinite,\n allow_na = allow_na,\n allow_null = allow_null\n ))) {\n return(invisible(NULL))\n }\n\n .stop_not_number(\n x,\n ...,\n exit_code = exit_code,\n allow_decimal = FALSE,\n min = min,\n max = max,\n allow_na = allow_na,\n allow_null = allow_null,\n arg = arg,\n call = call\n )\n}\n\n#' @importFrom rlang ffi_standalone_is_bool_1.0.7\nassert_bool <- function(x,\n ...,\n allow_na = FALSE,\n allow_null = FALSE,\n arg = caller_arg(x),\n call = caller_env()) {\n if (!missing(x) && .rlang_check_bool(x, allow_na, allow_null)) {\n return(invisible(NULL))\n }\n\n stop_input_type(\n x,\n c(\"`TRUE`\", \"`FALSE`\"),\n ...,\n allow_na = allow_na,\n allow_null = allow_null,\n arg = arg,\n call = call\n )\n}\n\n# atomic vector ------------------------------------\n#' @importFrom rlang abort\nassert_character <- function(x,\n ...,\n allow_na = TRUE,\n allow_null = FALSE,\n arg = caller_arg(x),\n call = caller_env()) {\n if (!missing(x)) {\n if (is.character(x)) {\n if (!allow_na && anyNA(x)) {\n abort(\n sprintf(\"`%s` can't contain NA values.\", arg),\n arg = arg, call = call\n )\n }\n return(invisible(NULL))\n }\n\n if (allow_null && is.null(x)) {\n return(invisible(NULL))\n }\n }\n stop_input_type(\n x,\n \"a character vector\",\n ...,\n allow_na = FALSE,\n allow_null = allow_null,\n arg = arg,\n call = call\n )\n}\n\n#' @importFrom rlang abort\nassert_logical <- function(x,\n ...,\n allow_na = TRUE,\n allow_null = FALSE,\n arg = caller_arg(x),\n call = caller_env()) {\n if (!missing(x)) {\n if (is.logical(x)) {\n if (!allow_na && anyNA(x)) {\n abort(\n sprintf(\"`%s` can't contain NA values.\", arg),\n arg = arg, call = call\n )\n }\n return(invisible(NULL))\n }\n if (allow_null && is.null(x)) {\n return(invisible(NULL))\n }\n }\n\n stop_input_type(\n x,\n \"a logical vector\",\n ...,\n allow_na = FALSE,\n allow_null = allow_null,\n arg = arg,\n call = call\n )\n}\n\n# S3 object ----------------------------------------\n#' @importFrom rlang is_string is_missing\nassert_s3_class <- function(x, is_class, what, ...,\n arg = caller_arg(x),\n call = caller_env()) {\n if (is.character(is_class)) {\n class <- is_class\n is_class <- function(x) inherits(x, what = class)\n if (is_missing(what)) what <- sprintf(\"a <%s>\", class)\n }\n assert_(\n x = x, check = is_class,\n what = what,\n ...,\n arg = arg, call = call\n )\n}\n\n# nocov end\n"], ["/ggalign/R/craft-align-hclust.R", "#' Reorder or Group observations based on hierarchical clustering\n#'\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' This function aligns observations within the layout according to a\n#' hierarchical clustering tree, enabling reordering or grouping of elements\n#' based on clustering results.\n#'\n#' @param data A matrix-like object. By default, it inherits from the layout\n#' `matrix`.\n#' @inheritParams align\n#' @inheritParams hclust2\n#' @param reorder_dendrogram A single boolean value indicating whether to\n#' reorder the dendrogram based on the means. Alternatively, you can provide a\n#' custom function that accepts an [`hclust`][stats::hclust] object and the data\n#' used to generate the tree, returning either an [`hclust`][stats::hclust] or\n#' [`dendrogram`][stats::as.dendrogram] object. Default is `FALSE`.\n#' @param reorder_group A single boolean value, indicates whether we should do\n#' Hierarchical Clustering between groups, only used when previous groups have\n#' been established. Default: `FALSE`.\n#' @param k An integer scalar indicates the desired number of groups.\n#' @param h A numeric scalar indicates heights where the tree should be cut.\n#' @param cutree A function used to cut the [`hclust`][stats::hclust] tree. It\n#' should accept four arguments: the [`hclust`][stats::hclust] tree object,\n#' `distance` (only applicable when `method` is a string or a function for\n#' performing hierarchical clustering), `k` (the number of clusters), and `h`\n#' (the height at which to cut the tree). By default,\n#' [`cutree()`][stats::cutree()] is used.\n#' @inheritSection align Discrete Axis Alignment\n#' @seealso [`hclust2()`]\n#' @examples\n#' # align_hclust won't add a dendrogram\n#' ggheatmap(matrix(rnorm(81), nrow = 9)) +\n#' anno_top() +\n#' align_hclust(k = 3L)\n#' @export\nalign_hclust <- function(distance = \"euclidean\",\n method = \"complete\",\n use_missing = \"pairwise.complete.obs\",\n reorder_dendrogram = FALSE,\n reorder_group = FALSE,\n k = NULL, h = NULL, cutree = NULL,\n data = NULL, active = NULL) {\n assert_active(active)\n active <- update_active(active, new_active(use = FALSE))\n .align_hclust(\n align = AlignHclust,\n distance = distance,\n method = method,\n use_missing = use_missing,\n reorder_dendrogram = reorder_dendrogram,\n reorder_group = reorder_group,\n k = k, h = h, cutree = cutree, data = data, active = active\n )\n}\n\n.align_hclust <- function(align, ..., plot = NULL,\n distance = \"euclidean\",\n method = \"complete\",\n use_missing = \"pairwise.complete.obs\",\n reorder_dendrogram = FALSE,\n reorder_group = FALSE,\n k = NULL, h = NULL, cutree = NULL,\n data = NULL, schemes = NULL, active = NULL,\n call = caller_call()) {\n reorder_dendrogram <- allow_lambda(reorder_dendrogram)\n if (!rlang::is_bool(reorder_dendrogram) &&\n !is.null(reorder_dendrogram) &&\n !is.function(reorder_dendrogram)) {\n cli_abort(\n \"{.arg reorder_dendrogram} must be a single boolean value or a function\",\n call = call\n )\n }\n assert_number_whole(k, allow_null = TRUE, call = call)\n assert_number_decimal(h, allow_null = TRUE, call = call)\n assert_bool(reorder_group, call = call)\n cutree <- allow_lambda(cutree)\n assert_(cutree, is.function, \"a function\", allow_null = TRUE, call = call)\n if (inherits(method, \"hclust\")) {\n if (vec_size(.subset2(method, \"order\")) == 0L) {\n cli_abort(\"{.cls hclust} defined in {.arg method} cannot be empty\",\n call = call\n )\n }\n } else if (inherits(method, \"dendrogram\")) {\n if (stats::nobs(method) == 0L) {\n cli_abort(\n \"{.cls dendrogram} defined in {.arg method} cannot be empty\",\n call = call\n )\n }\n }\n\n if (isTRUE(reorder_dendrogram)) {\n reorder_dendrogram <- function(tree, data) {\n if (!inherits(tree, \"dendrogram\")) {\n tree <- stats::as.dendrogram(tree)\n }\n reorder(x = tree, wts = rowMeans(data), agglo.FUN = mean)\n }\n } else if (is.function(reorder_dendrogram)) {\n user_reorder <- reorder_dendrogram\n reorder_dendrogram <- function(tree, data) {\n # we ensure, what we input for user is a `hclust` object.\n if (!inherits(tree, \"hclust\")) tree <- stats::as.hclust(tree)\n ans <- user_reorder(tree, data)\n if (!inherits(ans, \"hclust\") &&\n !inherits(ans, \"dendrogram\")) {\n cli_abort(\n \"{.fn reorder_dendrogram} must return a {.cls hclust} or {.cls dendrogram} object\",\n call = call\n )\n }\n ans\n }\n }\n\n align(\n align = align,\n distance = distance, method = method,\n use_missing = use_missing,\n reorder_dendrogram = reorder_dendrogram,\n reorder_group = reorder_group,\n k = k, h = h, cutree = cutree,\n active = active,\n ..., # additional fields to be added, used by align_dendro\n schemes = schemes %||% default_schemes(),\n data = data,\n plot = plot,\n call = call\n )\n}\n\n#' @importFrom ggplot2 ggproto aes\nAlignHclust <- ggproto(\"AlignHclust\", CraftAlign,\n interact_layout = function(self, layout) {\n if (inherits(self$method, \"hclust\") ||\n inherits(self$method, \"dendrogram\")) {\n layout <- ggproto_parent(CraftAlign, self)$interact_layout(layout)\n if (inherits(self$method, \"hclust\")) {\n nobs <- vec_size(.subset2(self$method, \"order\"))\n } else {\n nobs <- stats::nobs(self$method)\n }\n\n if (is.null(layout_nobs <- .subset2(layout@design, \"nobs\"))) {\n layout@design[\"nobs\"] <- list(nobs)\n } else {\n assert_mismatch_nobs(self, layout_nobs, nobs, arg = \"method\")\n }\n } else {\n layout <- ggproto_parent(AlignOrder2, self)$interact_layout(layout)\n }\n\n # initialize the internal parameters\n self$multiple_tree <- FALSE\n self$height <- NULL\n self$panel <- NULL\n layout\n },\n compute = function(self, panel, index) {\n if (!is.null(self$data) && vec_size(self$data) < 2L) {\n cli_abort(c(\n \"Cannot do Hierarchical Clustering\",\n i = \"must have >= 2 observations to cluster\"\n ), call = self$call)\n }\n\n # if the old panel exist, we do sub-clustering\n if (!is.null(panel) && is.null(self$k) && is.null(self$h) &&\n is.null(self$cutree)) {\n # in this way, we prevent sub-clustering\n if (inherits(self$method, \"hclust\") ||\n inherits(self$method, \"dendrogram\")) {\n cli_abort(\n \"{.arg method} cannot be a {.cls hclust} or {.cls dendrogram} when previous layout panel groups exist\",\n call = self$call\n )\n }\n children <- vector(\"list\", nlevels(panel))\n names(children) <- levels(panel)\n labels <- vec_names(self$data)\n\n # we do clustering within each group ---------------\n for (g in levels(panel)) {\n idx <- which(panel == g)\n gdata <- vec_slice(self$data, idx)\n if (vec_size(gdata) == 1L) {\n children[[g]] <- tree_one_node(idx, .subset(labels, idx))\n } else {\n child <- stats::as.dendrogram(hclust2(\n gdata,\n distance = self$distance,\n method = self$method,\n use_missing = self$use_missing\n ))\n # we restore the actual index of the original matrix\n child <- stats::dendrapply(child, function(x) {\n if (stats::is.leaf(x)) {\n ans <- .subset(idx, x)\n attributes(ans) <- attributes(x)\n ans\n } else {\n x\n }\n })\n if (is.function(self$reorder_dendrogram)) {\n child <- self$reorder_dendrogram(child, gdata)\n }\n children[[g]] <- child\n }\n }\n return(children) # can be a list of `dendrogram` or `hclust` or mix\n }\n hclust2(self$data, self$distance, self$method, self$use_missing)\n },\n #' @importFrom stats order.dendrogram\n align = function(self, panel, index) {\n statistics <- self$statistics\n if (!is.null(panel) && is.null(self$k) && is.null(self$h) &&\n is.null(self$cutree)) {\n # reordering the dendrogram ------------------------\n if (nlevels(panel) > 1L && self$reorder_group) {\n parent_levels <- levels(panel)\n parent_data <- t(sapply(parent_levels, function(g) {\n colMeans(vec_slice(self$data, panel == g), na.rm = TRUE)\n }))\n rownames(parent_data) <- parent_levels\n parent <- hclust2(\n parent_data,\n distance = self$distance,\n method = self$method,\n use_missing = self$use_missing\n )\n # reorder parent based on the parent tree\n if (is.function(self$reorder_dendrogram)) {\n parent <- self$reorder_dendrogram(parent, parent_data)\n }\n # we always ensure the parent is a dendrogram\n # since we'll call `merge_dendrogram()` which requires a\n # dendrogram\n parent <- stats::as.dendrogram(parent)\n panel <- factor(panel, parent_levels[order.dendrogram(parent)])\n # we don't cutree, so we won't draw the height line\n # self$draw_params$height <- attr(ans, \"cutoff_height\")\n } else {\n parent <- NULL\n }\n\n # merge children tree ------------------------------\n if (nlevels(panel) == 1L) {\n statistics <- .subset2(statistics, 1L)\n } else if (isTRUE(self$merge_dendro)) {\n # we have a function named merge_dendrogram(), so we use\n # `merge_dendro` as the argument name\n # `merge_dendrogram` will follow the order of the parent\n statistics <- lapply(statistics, stats::as.dendrogram)\n statistics <- merge_dendrogram(parent, statistics)\n } else {\n # if no parent tree, and we havn't merged the tree\n # we must manually reorder the dendrogram\n if (!is.null(parent)) {\n statistics <- .subset(statistics, levels(panel))\n }\n self$multiple_tree <- TRUE\n }\n } else {\n # hclust2() will attach the distance used\n distance <- attr(statistics, \"distance\")\n if (is.function(self$reorder_dendrogram)) {\n statistics <- self$reorder_dendrogram(statistics, self$data)\n }\n if (!is.null(self$k) || !is.null(self$h) || !is.null(self$cutree)) {\n if (is.null(cutree <- self$cutree)) {\n cutree <- function(tree, dist, k, h) {\n if (!is.null(k)) {\n stats::cutree(tree, k = k)\n } else {\n stats::cutree(tree, h = h)\n }\n }\n }\n # we need `hclust` object to cutree\n statistics <- stats::as.hclust(statistics)\n panel <- cutree(statistics, distance, self$k, self$h)\n # For `cutree`, we always respect the height user specified\n # For user defined function, we always calculate\n # height from the number of `panels`\n if (isTRUE(self$plot_cut_height)) {\n self$height <- self$h %||% cutree_k_to_h(\n statistics, vec_unique_count(panel)\n )\n }\n }\n }\n # save the modified `statistics`\n self$statistics <- statistics\n if (self$multiple_tree) {\n index <- unlist(lapply(statistics, order2), FALSE, FALSE)\n } else {\n index <- order2(statistics)\n }\n # reorder panel factor levels to following the dendrogram order\n if (!is.null(panel)) {\n panel <- factor(panel, unique(panel[index]))\n # save panel information, in case of user change it\n self$panel <- panel\n }\n list(panel, index)\n },\n summary_align = function(self, ...) {\n c(TRUE, !is.null(self$k) || !is.null(self$h) || !is.null(self$cutree))\n }\n)\n\n#' Generate Tree Structures with Hierarchical Clustering\n#'\n#' @param matrix A numeric matrix, or data frame.\n#' @param distance A string of distance measure to be used. This must be one of\n#' `\"euclidean\"`, `\"maximum\"`, `\"manhattan\"`, `\"canberra\"`, `\"binary\"` or\n#' `\"minkowski\"`. Correlation coefficient can be also used, including\n#' `\"pearson\"`, `\"spearman\"` or `\"kendall\"`. In this way, `1 - cor` will be used\n#' as the distance. In addition, you can also provide a [`dist`][stats::dist]\n#' object directly or a function return a [`dist`][stats::dist] object. Use\n#' `NULL`, if you don't want to calculate the distance.\n#' @param method A string of the agglomeration method to be used. This should be\n#' (an unambiguous abbreviation of) one of `\"ward.D\"`, `\"ward.D2\"`, `\"single\"`,\n#' `\"complete\"`, `\"average\"` (= UPGMA), `\"mcquitty\"` (= WPGMA), `\"median\"` (=\n#' WPGMC) or `\"centroid\"` (= UPGMC). You can also provide a function which\n#' accepts the calculated distance (or the input matrix if `distance` is `NULL`)\n#' and returns a [`hclust`][stats::hclust] object. Alternative, you can supply\n#' an object which can be coerced to [`hclust`][stats::hclust].\n#' @param use_missing An optional character string giving a method for computing\n#' covariances in the presence of missing values. This must be (an abbreviation\n#' of) one of the strings `\"everything\"`, `\"all.obs\"`, `\"complete.obs\"`,\n#' `\"na.or.complete\"`, or `\"pairwise.complete.obs\"`. Only used when `distance`\n#' is a correlation coefficient string.\n#' @seealso\n#' - [cor()][stats::cor]\n#' - [dist()][stats::dist]\n#' - [hclust()][stats::hclust]\n#' @examples\n#' hclust2(dist(USArrests), method = \"ward.D\")\n#' @return A [hclust][stats::hclust] object.\n#' @importFrom rlang is_string try_fetch\n#' @export\nhclust2 <- function(matrix, distance = \"euclidean\", method = \"complete\",\n use_missing = \"pairwise.complete.obs\") {\n method <- allow_lambda(method)\n if (!is_string(method) && !is.function(method)) {\n ans <- try_fetch(\n stats::as.hclust(method),\n error = function(cnd) {\n cli_abort(paste(\n \"{.arg method} can only be a {.cls string},\",\n \"{.cls function} or an object which can be coerced to\",\n \"{.cls hclust}.\"\n ), parent = cnd)\n }\n )\n return(ans)\n }\n if (is.null(distance)) {\n d <- matrix\n } else {\n d <- make_dist(matrix, distance, use_missing)\n }\n if (is_string(method)) {\n ans <- stats::hclust(d, method = method)\n } else if (is.function(method)) {\n ans <- method(d)\n ans <- try_fetch(\n stats::as.hclust(ans),\n error = function(cnd) {\n cli_abort(paste(\n \"{.arg method} must return an object which\",\n \"can be coerced to {.cls hclust}\"\n ), parent = cnd)\n }\n )\n }\n if (!is.null(distance)) attr(ans, \"distance\") <- d\n ans\n}\n\n#' @importFrom rlang arg_match0\nmake_dist <- function(matrix, distance, use_missing,\n arg = caller_arg(distance), call = caller_call()) {\n distance <- allow_lambda(distance)\n if (is_string(distance)) {\n distance <- arg_match0(distance, c(\n \"euclidean\", \"maximum\", \"manhattan\", \"canberra\",\n \"binary\", \"minkowski\", \"pearson\", \"spearman\", \"kendall\"\n ), arg_nm = arg, error_call = call)\n d <- switch(distance,\n euclidean = ,\n maximum = ,\n manhattan = ,\n canberra = ,\n binary = ,\n minkowski = stats::dist(matrix, method = distance),\n pearson = ,\n spearman = ,\n kendall = stats::as.dist(\n 1 - stats::cor(t(matrix), use = use_missing, method = distance)\n ),\n cli_abort(\"Unsupported {.arg {arg}} specified\", call = call)\n )\n } else if (is.function(distance)) {\n if (!inherits(d <- distance(matrix), \"dist\")) {\n cli_abort(\n \"{.arg {arg}} must return a {.cls dist} object\",\n call = call\n )\n }\n } else if (inherits(distance, \"dist\")) {\n d <- distance\n } else {\n cli_abort(paste(\n \"{.arg {arg}} can only be a {.cls string}, {.cls dist}\",\n \"object, or a {.cls function} return {.cls dist}\"\n ), call = call)\n }\n d\n}\n\ncutree_k_to_h <- function(tree, k) {\n if (is.null(n1 <- nrow(tree$merge)) || n1 < 1) {\n cli_abort(\"invalid {.arg tree} ({.field merge} component)\")\n }\n n <- n1 + 1\n if (is.unsorted(tree$height)) {\n cli_abort(\n \"the 'height' component of 'tree' is not sorted (increasingly)\"\n )\n }\n mean(tree$height[c(n - k, n - k + 1L)])\n}\n"], ["/ggalign/R/craft-align-phylo.R", "#' Plot Phylogenetics tree\n#'\n#' @param phylo A [`phylo`][ape::as.phylo] object.\n#' @param ... <[dyn-dots][rlang::dyn-dots]> Additional arguments passed to\n#' [`geom_segment()`][ggplot2::geom_segment].\n#' @param ladderize A single string of `r oxford_or(c(\"left\", \"right\"))`,\n#' indicating whether to ladderize the tree. Ladderizing arranges the tree so\n#' that the smallest clade is positioned on the `\"right\"` or the `\"left\"`. By\n#' default, `NULL` means the tree will not be ladderized.\n#' @inheritParams fortify_data_frame.phylo\n#' @inheritParams ggalign\n#' @export\nalign_phylo <- function(phylo, ..., ladderize = NULL, type = \"rectangle\",\n center = FALSE, tree_type = NULL,\n no_axes = NULL, active = NULL,\n size = NULL) {\n if (!is.null(ladderize)) {\n ladderize <- arg_match0(ladderize, c(\"left\", \"right\"))\n rlang::check_installed(\"ape\", \"to ladderize phylogenetics tree\")\n }\n assert_s3_class(phylo, \"phylo\")\n assert_active(active)\n active <- update_active(active, new_active(use = TRUE))\n align(\n align = AlignPhylo,\n phylo = phylo,\n ladderize = ladderize,\n no_axes = no_axes,\n plot = ggplot() +\n ggplot2::geom_segment(\n mapping = aes(\n x = .data$x, y = .data$y,\n xend = .data$xend, yend = .data$yend\n ),\n ...,\n stat = \"identity\",\n data = function(data) ggalign_attr(data, \"edge\")\n ),\n data_params = list(type = type, center = center, tree_type = tree_type),\n active = active,\n size = size\n )\n}\n\nAlignPhylo <- ggproto(\"AlignPhylo\", CraftAlign,\n interact_layout = function(self, layout) {\n layout <- ggproto_parent(CraftAlign, self)$interact_layout(layout)\n\n # we keep the names from the layout data for usage\n tip_labels <- self$phylo$tip.label\n if (is.null(tip_labels)) {\n cli_abort(\n \"{.arg phylo} must have tip labels to match the layout data\",\n call = self$call\n )\n } else if (vec_duplicate_any(tip_labels)) {\n cli_abort(\n \"{.arg phylo} cannot have duplicated tip labels\",\n call = self$call\n )\n }\n\n # we ensure the layout data has names to match the phylo tree\n if (is.null(layout_labels <- vec_names(layout@data))) {\n cli_abort(c(\n sprintf(\n \"Cannot add %s to %s\", object_name(self),\n self$layout_name\n ),\n i = sprintf(\n \"%s has no labels (rownames) to match {.arg phylo}\",\n self$layout_name\n )\n ))\n } else if (vec_duplicate_any(layout_labels)) {\n cli_abort(c(\n sprintf(\n \"Cannot add %s to %s\", object_name(self),\n self$layout_name\n ),\n i = sprintf(\"%s has duplicated labels\", self$layout_name)\n ))\n }\n assert_mismatch_nobs(\n self, .subset2(layout@design, \"nobs\"), vec_size(tip_labels),\n arg = \"phylo\"\n )\n\n # we keep the names from the layout data for usage\n self$labels <- layout_labels\n layout\n },\n compute = function(self, panel, index) {\n phylo <- self$phylo\n # R CMD check won't give error even we don't add `ape` to the dependency\n if (!is.null(self$ladderize)) {\n phylo <- ape::ladderize(phylo,\n right = identical(self$ladderize, \"right\")\n )\n }\n inject(fortify_data_frame.phylo(\n data = phylo, !!!self$data_params,\n data_arg = \"phylo\", call = self$call\n ))\n },\n align = function(self, panel, index) {\n data <- self$statistics\n tip <- vec_slice(data, .subset2(data, \"tip\"))\n ordered <- .subset2(tip, \"label\")[order(.subset2(tip, \"x\"))]\n index <- match(ordered, self$labels)\n if (!is.null(panel) && nlevels(panel) > 1L &&\n !all(index == reorder_index(panel, index))) {\n layout_name <- self$layout_name\n object_name <- object_name(self)\n cli_abort(c(\n sprintf(\"Cannot add %s to %s\", object_name, layout_name),\n i = sprintf(\n \"Group of %s will disrupt the ordering index of %s\", layout_name, object_name\n )\n ), call = self$call)\n }\n list(panel, index)\n },\n setup_plot = function(self, plot) {\n ggadd_default(plot, aes(x = .data$x, y = .data$y)) + switch_direction(\n self$direction,\n ggplot2::labs(x = \"timing\"),\n ggplot2::labs(y = \"timing\")\n )\n },\n build_plot = function(self, plot, design, extra_design = NULL,\n previous_design = NULL) {\n if (!is.null(panel <- .subset2(design, \"panel\")) &&\n nlevels(panel) > 1L) {\n layout_name <- self$layout_name\n object_name <- object_name(self)\n cli_abort(c(\n sprintf(\"Cannot add %s to %s\", object_name, layout_name),\n i = sprintf(\"%s cannot span multiple panels\", object_name)\n ))\n }\n\n data <- self$statistics\n edge <- ggalign_attr(data, \"edge\")\n node <- data\n node$.panel <- unique(panel)\n edge$.panel <- unique(panel)\n\n # add names\n if (!is.null(node$label)) {\n node$.names <- node$label\n }\n if (!is.null(edge$label)) {\n edge$.names <- edge$label\n }\n if (is_horizontal(self$direction)) {\n edge <- rename(\n edge,\n c(x = \"y\", xend = \"yend\", y = \"x\", yend = \"xend\")\n )\n node <- rename(node, c(x = \"y\", y = \"x\"))\n }\n plot <- gguse_data(plot, ggalign_data_set(node, edge = edge))\n position <- self$position\n if (!self$in_linear || # for circular layout\n # for top annotation, reverse y-axis\n (!is.null(position) && position == \"top\")) {\n plot <- reverse_continuous_axis(plot, \"y\")\n } else if (!is.null(position) && position == \"right\") {\n # for right annotation, reverse x-axis\n plot <- reverse_continuous_axis(plot, \"x\")\n }\n\n # always turn off clip, this is what dendrogram dependends on\n old_coord <- plot$coordinates\n if (!identical(old_coord$clip, \"off\")) {\n # to prevent from changing the input of user.\n plot$coordinates <- ggproto(NULL, old_coord, clip = \"off\")\n }\n plot\n },\n summary_align = function(self) c(TRUE, FALSE)\n)\n\n#' Build a matrix from `phylo` object\n#'\n#' @description This method allows a [`phylo`][ape::as.phylo] object to be\n#' directly input into `stack_discrete()` or `circle_discrete()`. This makes it\n#' possible to add [`align_phylo()`] to the stack independently, as\n#' [`align_phylo()`] requires the layout to have labels.\n#' @inheritParams rlang::args_dots_empty\n#' @param data A [`phylo`][ape::as.phylo] object.\n#' @inheritParams fortify_matrix\n#' @return A one-column matrix where the tip labels are the values, and the row\n#' names will also be the tip labels.\n#' @family fortify_matrix\n#' @export\nfortify_matrix.phylo <- function(data, ..., data_arg = caller_arg(data),\n call = NULL) {\n call <- call %||% current_call()\n rlang::check_dots_empty(call = call)\n if (is.null(labels <- data$tip.label)) {\n cli_abort(\n \"{.arg {data_arg}} must have tip labels to match the layout data\",\n call = call\n )\n }\n as.matrix(vec_set_names(labels, labels))\n}\n\n#' @inherit fortify_data_frame.default title description\n#' @inheritParams rlang::args_dots_empty\n#' @inheritParams fortify_data_frame.dendrogram\n#' @param tree_type A single string, one of\n#' `r oxford_or(c(\"phylogram\", \"cladogram\"))`, indicating the type of tree.\n#' - `phylogram`: Represents a phylogenetic tree where branch lengths indicate\n#' evolutionary distance or time.\n#' - `cladogram`: Represents a tree where branch lengths are not used, or the\n#' branches do not reflect evolutionary time.\n#'\n#' Usually, you don't need to modify this.\n#'\n#' @param tip_pos The x-coordinates of the tip. Must be the same length\n#' of the number of tips in `tree`.\n#' @return A `data frame` with the node coordinates:\n#' - `.index`: the original index in the tree for the the tip/node.\n#' - `label`: the tip/node label text.\n#' - `x` and `y`: x-axis and y-axis coordinates for the tip/node.\n#' - `tip`: A logical value indicates whether current node is a tip.\n#' @section ggalign attributes:\n#' `edge`: A `data frame` for edge coordinates:\n#'\n#' - `x` and `y`: x-axis and y-axis coordinates for the start node of the edge.\n#' - `xend` and `yend`: the x-axis and y-axis coordinates of the terminal node\n#' for edge.\n#' @family fortify_data_frame\n#' @export\nfortify_data_frame.phylo <- function(data, ..., type = \"rectangle\",\n center = FALSE,\n tree_type = NULL, tip_pos = NULL,\n data_arg = NULL, call = NULL) {\n call <- call %||% current_call()\n data_arg <- data_arg %||% \"data\"\n rlang::check_dots_empty(call = call)\n type <- arg_match0(type, c(\"rectangle\", \"triangle\"))\n rectangle <- type == \"rectangle\"\n edge <- data$edge\n edge_lengths <- data$edge.length\n if (!is.null(tree_type)) {\n tree_type <- arg_match0(tree_type,\n c(\"phylogram\", \"cladogram\"),\n error_call = call\n )\n if (tree_type == \"phylogram\" && is.null(edge_lengths)) {\n cli_warn(c(\n \"Cannot use {.code tree_type = 'phylogram'}\",\n \"No branch length found in {.arg {data_arg}}\"\n ))\n tree_type <- \"cladogram\"\n }\n }\n if (identical(tree_type, \"cladogram\")) {\n edge_lengths <- NULL\n }\n parent <- edge[, 1L, drop = TRUE]\n child <- edge[, 2L, drop = TRUE]\n tip_labels <- data$tip.label\n node_labels <- data$node.label\n N <- length(tip_labels)\n if (is.null(tip_pos)) {\n tip_pos <- seq_len(N)\n } else if (length(tip_pos) != N) {\n cli_abort(\n \"{.arg tip_pos} must have the same length as the number of tips in {.arg {data_arg}}\",\n call = call\n )\n }\n i <- 0L # tip index\n phylo_data <- function(index, level, timing) {\n if (any(select <- parent == index)) {\n # recursively for each child\n data <- list(index = child[select])\n # if we have edge length, timing should be available\n if (!is.null(edge_lengths)) {\n data <- c(data, list(timing = timing + edge_lengths[select]))\n }\n data <- list_transpose(.mapply(\n function(index, timing = NULL) {\n phylo_data(index, level = level + 1L, timing = timing)\n },\n data, NULL\n ))\n\n # integrate the data for each child\n node <- vec_rbind(!!!.subset2(data, \"node\"))\n edge <- vec_rbind(!!!.subset2(data, \"edge\"))\n\n # all coordinate for direct children nodes -------------\n direct_leaves_x <- unlist(\n .subset2(data, \"x\"),\n recursive = FALSE, use.names = FALSE\n )\n direct_leaves_y <- unlist(\n .subset2(data, \"y\"),\n recursive = FALSE, use.names = FALSE\n )\n\n # prepare node data ------------------------------------\n # all x coordinate for children nodes ------------------\n # used if center is `TRUE`, we'll calculate the center position\n # among all children nodes\n leaves <- vec_slice(node, .subset2(node, \"tip\")) # all leaves\n\n # x coordinate for current node: the midpoint\n if (center) {\n x <- sum(range(.subset2(leaves, \"x\"))) / 2L\n } else {\n x <- sum(range(direct_leaves_x)) / 2L\n }\n\n # y coordinate for current node\n if (is.null(edge_lengths) && is.null(timing)) {\n y <- min(direct_leaves_y) * level / (level + 1L)\n } else {\n y <- timing\n }\n\n # there is no node data for the root\n node <- vec_rbind(data_frame0(\n .index = index,\n label = node_labels[index - N],\n x = x, y = y, tip = FALSE\n ), node)\n\n # if it's the `rectangle`\n if (rectangle) {\n # vertical lines\n vertical_lines <- data_frame0(\n x = direct_leaves_x,\n xend = direct_leaves_x,\n y = y,\n yend = direct_leaves_y\n )\n added_edge <- vec_rbind(\n vertical_lines,\n # horizontal line\n data_frame0(\n x = x,\n xend = direct_leaves_x,\n y = y,\n yend = y\n )\n )\n } else {\n added_edge <- data_frame0(\n x = x,\n xend = direct_leaves_x,\n y = y,\n yend = direct_leaves_y\n )\n }\n if (is.null(edge)) {\n edge <- added_edge\n } else {\n edge <- vec_rbind(added_edge, edge)\n }\n list(node = node, edge = edge, x = x, y = y)\n } else if (any(select <- child == index)) { # for the tip\n i <<- i + 1L\n x <- tip_pos[i]\n if (is.null(edge_lengths)) {\n y <- 1L\n } else {\n y <- timing\n }\n\n list(\n node = data_frame0(\n .index = index,\n label = tip_labels[index],\n x = x,\n y = y,\n tip = TRUE\n ),\n edge = NULL,\n x = x, y = y\n )\n } else {\n cli_abort(\"Invalid {.cls phylo} provided in {.arg {data_arg}}\",\n call = call\n )\n }\n }\n\n # from ape::is.rooted, this should be the most ancester\n ans <- phylo_data(N + 1L, 0L, timing = 0)\n ggalign_data_set(.subset2(ans, \"node\"), edge = .subset2(ans, \"edge\"))\n}\n"], ["/ggalign/R/pair-links.R", "#' Helper function to create pairs of observation groups\n#'\n#' @description\n#' [`ggmark()`] and [`cross_link()`] allow users to add links between\n#' observations. These functions help define the linked observations. The\n#' selected pairs will either be linked together, or each group in the pair will\n#' be linked separately to the same plot area.\n#'\n#' - `pair_links`: Helper function to create pairs of observation groups.\n#' - `range_link`: Helper function to create a range of observations.\n#'\n#' @param ... <[dyn-dots][rlang::dyn-dots]> A list of formulas, where each side\n#' of the formula should be an `integer` or `character` index of the original\n#' data, or a `range_link()` object defining the linked observations. Use\n#' `NULL` to indicate no link on that side. You can also combine these by\n#' wrapping them into a single `list()`. If only the left-hand side of the\n#' formula exists, you can input it directly. For integer indices, wrap them\n#' with [`I()`] to use the ordering from the layout. You can also use\n#' [`waiver()`][ggplot2::waiver()] to inherit values from the other group.\n#' @param .handle_missing A string of `r oxford_or(c(\"error\", \"remove\"))`\n#' indicates the action for handling missing observations.\n#' @param .reorder A string of `r oxford_or(c(\"hand1\", \"hand2\"))` indicating\n#' whether to reorder the input links to follow the specified layout ordering.\n#' @examples\n#' x <- pair_links(\n#' # group on the left hand only\n#' c(\"a\", \"b\"),\n#' # normally, integer index will be interpreted as the index of the\n#' # origianl data\n#' 1:2,\n#' # wrapped with `I()` indicate` the integer index is ordering of the\n#' # layout\n#' I(1:2),\n#' range_link(1, 6),\n#' range_link(\"a\", \"b\"),\n#' # group on the right hand only\n#' ~ 1:2,\n#' ~ c(\"a\", \"b\"),\n#' ~ range_link(1, 6),\n#' # group on the both side\n#' range_link(1, 6) ~ c(\"a\", \"b\"),\n#' # waiver() indicates the right hand is the same of the left hand\n#' range_link(1, 6) ~ waiver(),\n#' # the same for the left hand\n#' waiver() ~ 1:2,\n#' ~NULL # an empty link\n#' )\n#' x\n#'\n#' # we can modify it as usual list\n#' x[[1]] <- NULL # remove the first link\n#' x$a <- ~LETTERS\n#' x\n#'\n#' # modify with a list\n#' x[1:2] <- list(~ c(\"a\", \"b\"), ~ range_link(\"a\", \"b\"))\n#' x\n#' @export\npair_links <- function(..., .handle_missing = \"error\", .reorder = NULL) {\n .handle_missing <- arg_match0(.handle_missing, c(\"error\", \"remove\"))\n if (!is.null(.reorder)) {\n .reorder <- arg_match0(.reorder, c(\"hand1\", \"hand2\"))\n }\n pairs <- rlang::dots_list(..., .ignore_empty = \"all\", .named = NULL)\n new_pair_links(\n lapply(pairs, as_pair_link, x_arg = \"...\", call = current_call()),\n handle_missing = .handle_missing, reorder = .reorder\n )\n}\n\nnew_pair_links <- function(x = list(), ..., class = character()) {\n new_vctr(x, ..., class = c(class, \"ggalign_pair_links\"))\n}\n\n#' @export\nobj_print_header.ggalign_pair_links <- function(x, ...) {\n cat(\"<\", vec_ptype_full(x), \">\", \"\\n\", sep = \"\")\n cat(\n sprintf(\n \"A total of %d pair%s of link groups\",\n vec_size(x), if (vec_size(x) > 1L) \"s\" else \"\"\n ),\n \"\\n\",\n sep = \"\"\n )\n invisible(x)\n}\n\n#' @export\nobj_print_data.ggalign_pair_links <- function(x, ...) {\n if (vec_size(x) > 0L) {\n hand1 <- vapply(x, function(hand) {\n deparse_link(hand, ..., hand = \"hand1\")\n }, character(1L), USE.NAMES = FALSE)\n hand2 <- vapply(x, function(hand) {\n deparse_link(hand, ..., hand = \"hand2\")\n }, character(1L), USE.NAMES = FALSE)\n nms <- c(\"\", paste0(names_or_index(x), \": \"))\n nms <- format(nms, justify = \"right\")\n empty <- character(vec_size(hand2))\n empty[hand1 == \"\" & hand2 == \"\"] <- \" \"\n empty <- format(c(\"\", empty), justify = \"left\")\n hand1 <- format(c(\"hand1\", hand1), justify = \"right\")\n hand2 <- format(c(\"hand2\", hand2), justify = \"left\")\n cat(\"\\n\")\n cat(paste0(\" \", nms, hand1, \" ~ \", hand2, empty), sep = \"\\n\")\n cat(\"\\n\")\n }\n invisible(x)\n}\n\n#' @export\nobj_print_footer.ggalign_pair_links <- function(x, ...) {\n NextMethod()\n # `lengths`: will call `length.ggalign_pair_link()` method\n n <- sum(lengths(x, use.names = FALSE))\n cat(\n sprintf(\n \"A total of %d link group%s\", n,\n if (n > 1L) \"s\" else \"\"\n ),\n \"\\n\",\n sep = \"\"\n )\n invisible(x)\n}\n\n#' @export\n`[<-.ggalign_pair_links` <- function(x, i, value) {\n value <- lapply(value, as_pair_link, x_arg = \"value\", call = current_call())\n NextMethod()\n}\n\n#' @export\n`[[<-.ggalign_pair_links` <- function(x, i, value) {\n # let `NULL` to remove the link\n if (!is.null(value)) value <- as_pair_link(value)\n NextMethod()\n}\n\n#' @export\n`$<-.ggalign_pair_links` <- function(x, i, value) {\n # let `NULL` to remove the link\n if (!is.null(value)) value <- as_pair_link(value)\n NextMethod()\n}\n\n#' @export\nvec_ptype2.ggalign_pair_links.list <- function(x, y, ...) {\n x\n}\n\n#' @export\nvec_ptype2.list.ggalign_pair_links <- function(x, y, ...) {\n y\n}\n\n#' @export\nvec_cast.ggalign_pair_links.list <- function(x, to, ...,\n x_arg = caller_arg(x),\n to_arg = \"\",\n call = caller_env()) {\n new_pair_links(lapply(x, as_pair_link, x_arg = x_arg, call = call))\n}\n\n#########################################################\n#' @param point1,point2 A single integer or character index, defining the lower\n#' and higher bounds of the range. For integer indices, wrap them with [`I()`]\n#' to indicate the ordered index by the layout.\n#' @export\n#' @rdname pair_links\nrange_link <- function(point1, point2) {\n if (!is_scalar(point1) ||\n (!is.character(point1) && !is.numeric(point1))) {\n cli_abort(\"{.arg point1} must be a single numeric or character index\")\n }\n if (!is_scalar(point2) ||\n (!is.character(point2) && !is.numeric(point2))) {\n cli_abort(\"{.arg point2} must be a single numeric or character index\")\n }\n point1 <- as_obs_link(point1)\n point2 <- as_obs_link(point2)\n structure(list(point1 = point1, point2 = point2),\n class = \"ggalign_range_link\"\n )\n}\n\nis_range_link <- function(x) inherits(x, \"ggalign_range_link\")\n\n########################################################\nnew_pair_link <- function(hand1 = NULL, hand2 = NULL,\n ..., class = character()) {\n structure(\n .Data = list(hand1 = hand1, hand2 = hand2),\n ...,\n class = c(class, \"ggalign_pair_link\")\n )\n}\n\n#' @export\nvec_proxy.ggalign_pair_link <- function(x, ...) x\n\n#' @export\nprint.ggalign_pair_link <- function(x, ...) obj_print(x, ...)\n\n#' @export\nobj_print_header.ggalign_pair_link <- function(x, ...) {\n cat(sprintf(\"<%s>\", vec_ptype_full(x)), \"\\n\", sep = \"\")\n invisible(x)\n}\n\n#' @export\nobj_print_data.ggalign_pair_link <- function(x, ...) {\n if (length(x) > 0L) {\n cat(c(\n sprintf(\" hand1: %s\", deparse_link(.subset2(x, \"hand1\"), ...)),\n sprintf(\" hand2: %s\", deparse_link(.subset2(x, \"hand2\"), ...))\n ), sep = \"\\n\")\n }\n invisible(x)\n}\n\n#' @param x A `ggalign_pair_link` object.\n#' @noRd\n#' @export\nlength.ggalign_pair_link <- function(x) {\n sum(!vapply(x, is.null, logical(1L), USE.NAMES = FALSE))\n}\n\n##################################################\n#' @export\nvec_ptype2.ggalign_pair_link.ggalign_pair_link <- function(x, y, ...) {\n x\n}\n\n#' @export\nvec_ptype2.ggalign_pair_link.NULL <- function(x, y, ...) {\n x\n}\n\n#' @export\nvec_ptype2.NULL.ggalign_pair_link <- function(x, y, ...) {\n y\n}\n\n#' @export\nvec_ptype2.ggalign_pair_link.numeric <- function(x, y, ...) {\n x\n}\n\n#' @export\nvec_ptype2.numeric.ggalign_pair_link <- function(x, y, ...) {\n y\n}\n\n#' @export\nvec_ptype2.ggalign_pair_link.integer <- function(x, y, ...) {\n x\n}\n\n#' @export\nvec_ptype2.integer.ggalign_pair_link <- function(x, y, ...) {\n y\n}\n\n#' @export\nvec_ptype2.ggalign_pair_link.double <- function(x, y, ...) {\n x\n}\n\n#' @export\nvec_ptype2.double.ggalign_pair_link <- function(x, y, ...) {\n y\n}\n\n#' @export\nvec_ptype2.ggalign_pair_link.character <- function(x, y, ...) {\n x\n}\n\n#' @export\nvec_ptype2.character.ggalign_pair_link <- function(x, y, ...) {\n y\n}\n\n#' @export\nvec_ptype2.ggalign_pair_link.formula <- function(x, y, ...) {\n x\n}\n\n#' @export\nvec_ptype2.formula.ggalign_pair_link <- function(x, y, ...) {\n y\n}\n\n#' @export\nvec_ptype2.ggalign_pair_link.waiver <- function(x, y, ...) {\n x\n}\n\n#' @export\nvec_ptype2.waiver.ggalign_pair_link <- function(x, y, ...) {\n y\n}\n\n#' @export\nvec_ptype2.ggalign_pair_link.ggalign_range_link <- function(x, y, ...) {\n x\n}\n\n#' @export\nvec_ptype2.ggalign_range_link.ggalign_pair_link <- function(x, y, ...) {\n y\n}\n\n#' @export\nvec_ptype2.ggalign_pair_link.AsIs <- function(x, y, ...) {\n vec_ptype2(x, remove_class(y, \"AsIs\"), ...)\n}\n\n#' @export\nvec_ptype2.AsIs.ggalign_pair_link <- function(x, y, ...) {\n vec_ptype2(remove_class(x, \"AsIs\"), y, ...)\n}\n\n#' @export\nvec_ptype2.ggalign_pair_link.list <- function(x, y, ...) {\n x\n}\n\n#' @export\nvec_ptype2.list.ggalign_pair_link <- function(x, y, ...) {\n y\n}\n\n#############################################################\n#' @export\nvec_cast.ggalign_pair_link.numeric <- function(x, to, ...,\n x_arg = caller_arg(x),\n to_arg = \"\",\n call = caller_env()) {\n new_pair_link(as_obs_link(x, arg = x_arg, call = call))\n}\n\n#' @export\nvec_cast.ggalign_pair_link.double <- vec_cast.ggalign_pair_link.numeric\n\n#' @export\nvec_cast.ggalign_pair_link.integer <- vec_cast.ggalign_pair_link.numeric\n\n#' @export\nvec_cast.ggalign_pair_link.character <- vec_cast.ggalign_pair_link.numeric\n\n#' @export\nvec_cast.ggalign_pair_link.ggalign_range_link <-\n vec_cast.ggalign_pair_link.integer\n\n#' @export\nvec_cast.ggalign_pair_link.list <- vec_cast.ggalign_pair_link.numeric\n\n#' @export\nvec_cast.ggalign_pair_link.AsIs <- function(x, to, ...,\n x_arg = caller_arg(x),\n to_arg = \"\",\n call = caller_env()) {\n I(vec_cast(\n remove_class(x, \"AsIs\"),\n to = to, ...,\n x_arg = x_arg, call = call\n ))\n}\n\n#' @export\nvec_cast.ggalign_pair_link.formula <- function(x, to, ...,\n x_arg = caller_arg(x),\n to_arg = \"\",\n call = caller_env()) {\n hand1 <- rlang::eval_tidy(rlang::f_lhs(x), env = rlang::f_env(x))\n hand1 <- as_obs_link(hand1, arg = x_arg, call = call)\n hand2 <- rlang::eval_tidy(rlang::f_rhs(x), env = rlang::f_env(x))\n hand2 <- as_obs_link(hand2, arg = x_arg, call = call)\n new_pair_link(hand1, hand2)\n}\n\nas_pair_link <- function(x, ...) {\n if (is.null(x)) { # vec_cast() cannot convert `NULL`\n new_pair_link()\n } else {\n vec_cast(x, to = new_pair_link(), ...)\n }\n}\n\n########################################################\nas_obs_link <- function(x, ..., arg = caller_arg(x), call = caller_env()) {\n UseMethod(\"as_obs_link\")\n}\n\n#' @export\nas_obs_link.NULL <- function(x, ...) x\n\n#' @export\nas_obs_link.AsIs <- function(x, ...) {\n I(as_obs_link(remove_class(x, \"AsIs\"), ...))\n}\n\n#' @export\nas_obs_link.numeric <- function(x, ..., arg = caller_arg(x),\n call = caller_env()) {\n vec_cast(x, integer(), x_arg = arg, call = call)\n}\n\n#' @export\nas_obs_link.integer <- as_obs_link.NULL\n\n#' @export\nas_obs_link.double <- as_obs_link.numeric\n\n#' @export\nas_obs_link.character <- function(x, ..., arg = caller_arg(x),\n call = caller_env()) {\n if (any(x == \"\")) {\n cli_abort(\"empty string is not allowed\", call = call)\n }\n x\n}\n\n#' @export\nas_obs_link.waiver <- as_obs_link.NULL\n\n#' @export\nas_obs_link.list <- function(x, ..., arg = caller_arg(x),\n call = caller_env()) {\n x <- x[!vapply(x, is.null, logical(1L), USE.NAMES = FALSE)]\n if (is_empty(x)) return(NULL) # styler: off\n lapply(x, as_obs_link, arg = arg, call = call)\n}\n\n#' @export\nas_obs_link.ggalign_range_link <- as_obs_link.NULL\n\n#' @export\nas_obs_link.default <- function(x, ..., arg = caller_arg(x),\n call = caller_env()) {\n stop_incompatible_cast(\n x, new_pair_link(),\n x_arg = arg, to_arg = \"\",\n call = call\n )\n}\n\n#' @export\nprint.ggalign_range_link <- function(x, ...) {\n cat(deparse_link(x))\n invisible(x)\n}\n\n###########################################################\n#' @return A single string\n#' @noRd\ndeparse_link <- function(x, ...) deparse_link2(x, ...) %||% \"\"\n\n#' @return A single string or `NULL`\n#' @noRd\ndeparse_link2 <- function(x, ...) UseMethod(\"deparse_link2\")\n\n# Basic object\n#' @export\ndeparse_link2.integer <- function(x, trunc = 3L, head = trunc - 1L,\n tail = 1L, ...) {\n l <- length(x)\n ans <- paste(\n deparse(x, control = c(\"keepNA\", \"niceNames\", \"showAttributes\")),\n collapse = \" \"\n )\n if (l > trunc && startsWith(ans, \"c\")) {\n ans <- sprintf(\"c(%s)\", paste(c(\n x[seq_len(head)], \"...\", x[seq.int(l - tail + 1L, l)]\n ), collapse = \", \"))\n }\n ans\n}\n\n#' @export\ndeparse_link2.character <- function(x, trunc = 3L, head = trunc - 1L,\n tail = 1L, ...) {\n l <- length(x)\n if (l <= trunc) {\n ans <- paste(deparse(x), collapse = \" \")\n } else {\n ans <- sprintf(\"c(%s)\", paste(c(\n x[seq_len(head)], \"...\", x[seq.int(l - tail + 1L, l)]\n ), collapse = \", \"))\n }\n ans\n}\n\n#' @export\ndeparse_link2.waiver <- function(x, ...) \"waiver()\"\n\n#' @export\ndeparse_link2.NULL <- function(x, ...) NULL\n\n# To allow `I()` to be used to the whole formula, we must define the method for\n# this, though `ggalign_pair_link` shouldn't be considered as an observation\n#' @export\ndeparse_link2.ggalign_pair_link <- function(x, ..., hand) {\n deparse_link2(.subset2(x, hand), ...)\n}\n\n#' @export\ndeparse_link2.AsIs <- function(x, ...) {\n ans <- deparse_link2(remove_class(x, \"AsIs\"), ...)\n if (!is.null(ans)) ans <- sprintf(\"I(%s)\", ans)\n ans\n}\n\n# Recurse version\n#' @export\ndeparse_link2.ggalign_range_link <- function(x, ...) {\n sprintf(\n \"range_link(%s, %s)\",\n deparse_link(.subset2(x, \"point1\"), ...),\n deparse_link(.subset2(x, \"point2\"), ...)\n )\n}\n\n#' @export\ndeparse_link2.list <- function(x, trunc = 3L, head = trunc - 1L,\n tail = 1L, ...) {\n l <- length(x)\n if (l <= trunc) {\n ans <- vapply(x, deparse_link, character(1L), ...,\n trunc = trunc, head = head, tail = tail,\n USE.NAMES = FALSE\n )\n } else {\n ans <- c(\n vapply(x[seq_len(head)],\n deparse_link, character(1L), ...,\n trunc = trunc, head = head, tail = tail,\n USE.NAMES = FALSE\n ),\n \"...\",\n vapply(x[seq.int(l - tail + 1L, l)],\n deparse_link, character(1L), ...,\n trunc = trunc, head = head, tail = tail,\n USE.NAMES = FALSE\n )\n )\n }\n sprintf(\"list(%s)\", paste(ans, collapse = \", \"))\n}\n\n###################################################\nmake_links_data <- function(links, design1, design2,\n labels1, labels2) {\n link_index_list <- lapply(\n links, make_pair_link_index,\n design1 = design1, design2 = design2,\n labels1 = labels1, labels2 = labels2,\n handle_missing = attr(links, \"handle_missing\")\n )\n names(link_index_list) <- names_or_index(links)\n if (!is.null(reorder <- attr(links, \"reorder\"))) {\n index <- vapply(link_index_list, function(link_index) {\n if (is.null(link_index) ||\n is.null(index <- .subset2(link_index, reorder))) {\n NA_integer_\n } else {\n vec_slice(index, 1L)\n }\n }, integer(1L), USE.NAMES = FALSE)\n link_index_list <- link_index_list[order(index)]\n }\n link_index_list\n}\n\nmake_pair_link_index <- function(pair_link, design1, design2,\n labels1, labels2, handle_missing) {\n input1 <- .subset2(pair_link, 1L)\n input2 <- .subset2(pair_link, 2L)\n\n # make the data\n hand1 <- make_link_index(input1,\n design = design1, labels = labels1,\n other = input2, data_index = !inherits(pair_link, \"AsIs\"),\n handle_missing = handle_missing\n )\n hand2 <- make_link_index(input2,\n design = design2, labels = labels2,\n other = input1, data_index = !inherits(pair_link, \"AsIs\"),\n handle_missing = handle_missing\n )\n if (is.null(hand1) && is.null(hand2)) {\n return(NULL)\n }\n list(hand1 = hand1, hand2 = hand2)\n}\n\nmake_link_index <- function(link, design, labels, other, data_index,\n handle_missing, arg = caller_arg(link),\n call = caller_call()) {\n link <- link_to_location(\n link,\n n = .subset2(design, \"nobs\"),\n labels = labels,\n index = .subset2(design, \"index\"),\n other = other,\n data_index = data_index,\n handle_missing = handle_missing,\n arg = arg, call = call\n )\n if (is_empty(link)) {\n return(NULL)\n }\n # always use integer, otherwise, will cause error when drawing\n # due to loss of precision, I don't know why, it should be integer already?\n vec_unique(vec_cast(link, integer()))\n}\n\nlink_to_location <- function(x, ...) UseMethod(\"link_to_location\")\n\n#' @export\nlink_to_location.AsIs <- function(x, ..., data_index) {\n link_to_location(remove_class(x, \"AsIs\"), ..., data_index = FALSE)\n}\n\n#' @export\nlink_to_location.character <- function(x, ..., n, labels, index, handle_missing,\n arg = caller_arg(x),\n call = caller_call()) {\n if (identical(handle_missing, \"remove\") && !is.null(labels)) {\n x <- x[x %in% labels]\n }\n ans <- vec_as_location(x, n = n, names = labels, arg = arg, call = call)\n match(ans, index) # character always match the original data\n}\n\n#' @export\nlink_to_location.integer <- function(x, ..., n, index, data_index,\n handle_missing, arg = caller_arg(x),\n call = caller_call()) {\n ans <- num_as_location(x,\n n = n,\n arg = arg, call = call,\n negative = \"error\",\n zero = \"error\",\n oob = handle_missing\n )\n # integer index by default match the original data\n if (isTRUE(data_index)) match(ans, index) else ans\n}\n\n#' @export\nlink_to_location.ggalign_range_link <- function(x, ..., arg = caller_arg(x),\n call = caller_call()) {\n point1 <- link_to_location(\n .subset2(x, \"point1\"),\n ...,\n arg = \"point1\",\n call = quote(range_link())\n )\n point2 <- link_to_location(\n .subset2(x, \"point2\"),\n ...,\n arg = \"point2\",\n call = quote(range_link())\n )\n point1:point2\n}\n\n#' @export\nlink_to_location.list <- function(x, ...) {\n unlist(lapply(x, link_to_location, ...), FALSE, FALSE)\n}\n\n#' @export\nlink_to_location.waiver <- function(x, ..., other) {\n link_to_location(other %|w|% NULL, ...)\n}\n\n#' @export\nlink_to_location.NULL <- function(x, ...) NULL\n"], ["/ggalign/R/layout-align.R", "#' Set Expansion for the Layout\n#'\n#' @description\n#' To align axes, it is important to keep the expansion consistent across all\n#' plots in the layout. You can add a `layout_expand` object to the layout. For\n#' the `quad_layout()` function, you must specify `x` and `y` arguments. For\n#' other layouts, you can pass the expansion values using `...` directly.\n#'\n#' @param ... A list of range expansion constants, used to add padding around\n#' the data to ensure they are placed some distance away from the axes. Use the\n#' convenience function [`expansion()`][ggplot2::expansion()] to generate the\n#' values.\n#' @param x,y Same as `...`, but specifically for `quad_layout()`.\n#'\n#' @importFrom rlang list2\n#' @keywords internal\nlayout_expand <- function(..., x = waiver(), y = waiver()) {\n if (...length() > 0L && (!is.waive(x) || !is.waive(y))) {\n cli_abort(\n \"Cannot mix the usage of {.arg ...} with {.arg x}/{.arg y} argument\"\n )\n }\n if (...length() > 0L) {\n ans <- list2(...)\n names(ans) <- NULL\n } else {\n ans <- list(x = x, y = y)\n }\n structure(ans, class = \"ggalign_layout_expand\")\n}\n\n#' Set continuous limits for the layout\n#'\n#' @description\n#' To align continuous axes, it is important to keep the limits consistent\n#' across all plots in the layout. You can set the limits by passing a function\n#' directly to the `limits` or `xlim`/`ylim` argument, using `...` only.\n#' Alternatively, you can add a `continuous_limits()` object to the layout. For\n#' the `quad_layout()` function, you must specify `x`/`y` arguments. For other\n#' layouts, you should pass the limits using `...` directly.\n#'\n#' @param ... A list of two numeric values, specifying the left/lower limit and\n#' the right/upper limit of the scale.\n#' @inheritParams layout_expand\n#' @importFrom rlang list2\n#' @export\ncontinuous_limits <- function(..., x = waiver(), y = waiver()) {\n if (...length() > 0L && (!is.waive(x) || !is.waive(y))) {\n cli_abort(\n \"Cannot mix the usage of {.arg ...} with {.arg x}/{.arg y} argument\"\n )\n }\n if (...length() > 0L) {\n ans <- list2(...)\n names(ans) <- NULL\n } else {\n ans <- list(x = x, y = y)\n }\n structure(ans, class = c(\"continuous_limits\", \"layout_design\"))\n}\n\n# layout params are used to align the observations\ndiscrete_design <- function(panel = NULL, index = NULL, nobs = NULL) {\n structure(\n list(panel = panel, index = index, nobs = nobs),\n class = c(\"discrete_design\", \"layout_design\")\n )\n}\n\n################################################################\nis_continuous_design <- function(x) {\n is.null(x) || inherits(x, \"continuous_limits\")\n}\n\nis_discrete_design <- function(x) inherits(x, \"discrete_design\")\n\n#' Layout can align ordinal variable or continuous variable\n#'\n#' @param x A `LayoutProto` object.\n#' @noRd\nis_layout_discrete <- function(x, ...) UseMethod(\"is_layout_discrete\")\n\nis_layout_continuous <- function(x, ...) UseMethod(\"is_layout_continuous\")\n\n################################################################\n# Initialize the index and panel\n# Reorder the panel based the ordering index and\nsetup_design <- function(design) {\n # for continuous axis, do noting special\n if (is_continuous_design(design)) return(design) # styler: off\n # if `nobs` is not initialized, it means no `Align` object exist\n # it's not necessary to initialize the `panel` and `index`\n # this is for `stack_layout` which may have no data\n if (is.null(nobs <- .subset2(design, \"nobs\"))) {\n return(design)\n }\n panel <- .subset2(design, \"panel\") %||% factor(rep_len(1L, nobs))\n index <- .subset2(design, \"index\") %||% reorder_index(panel)\n discrete_design(panel[index], index, nobs)\n}\n\nreorder_index <- function(panel, index = NULL) {\n index <- index %||% seq_along(panel)\n unlist(split(index, panel[index]), recursive = FALSE, use.names = FALSE)\n}\n\n############################################################\n#' @keywords internal\nupdate_design <- function(layout, ..., design, object_name) {\n UseMethod(\"update_design\")\n}\n\n#' @importFrom methods slot slot<-\n#' @export\nupdate_design.QuadLayout <- function(layout, ..., direction, design,\n object_name) {\n slot(layout, direction) <- design\n if (is_horizontal(direction)) {\n if (!is.null(left <- layout@left)) {\n layout@left <- update_design(left,\n design = design, object_name = object_name\n )\n }\n if (!is.null(right <- layout@right)) {\n layout@right <- update_design(right,\n design = design, object_name = object_name,\n from_head = TRUE\n )\n }\n } else {\n if (!is.null(top <- layout@top)) {\n layout@top <- update_design(top,\n design = design, object_name = object_name\n )\n }\n if (!is.null(bottom <- layout@bottom)) {\n layout@bottom <- update_design(bottom,\n design = design, object_name = object_name,\n from_head = TRUE\n )\n }\n }\n layout\n}\n\n#' @importFrom methods slot slot<-\n#' @export\nupdate_design.StackLayout <- function(layout, ..., design, object_name) {\n layout@design <- design\n layout@plot_list <- lapply(layout@plot_list, function(plot) {\n if (is_craftbox(plot)) return(plot) # styler: off\n update_design(plot,\n direction = layout@direction,\n design = design\n )\n })\n layout\n}\n\n#' @export\nupdate_design.CircleLayout <- update_design.StackLayout\n\n#' @importFrom methods slot slot<-\n#' @export\nupdate_design.StackCross <- function(layout, ..., design, object_name,\n from_head = FALSE) {\n # `design` must be a discrete_design()\n design_list <- c(layout@odesign, list(layout@design))\n\n # for cross_points, the updating will span it, but only update the panel\n # information\n cross_points <- layout@cross_points\n\n # the break_points set breaks, updating won't span the break points\n break_points <- layout@break_points\n\n plot_list <- layout@plot_list\n n <- length(plot_list)\n points <- c(cross_points, n)\n point_index <- seq_along(points)\n if (!from_head) point_index <- rev(point_index)\n for (i in point_index) {\n cross_point <- .subset(points, i)\n\n # we first update the design in the updated tail\n # it means the first design when `from_head` is `TRUE`\n # the last design when `from_head` is `FALSE`\n if ((from_head && i == 1L) || (!from_head && cross_point == n)) {\n new_design <- design\n } else if (!from_head && any(cross_point == break_points)) {\n break\n } else {\n # for design not in updated tail, we'll only update `panel` and\n # `nobs`, we check the new panel doesn't break the original index\n new_nobs <- .subset2(design, \"nobs\")\n new_panel <- .subset2(design, \"panel\")\n new_design <- .subset2(design_list, i)\n # we check the new panel don't disrupt the ordering index\n if (!is.null(new_panel) &&\n !is.null(old_index <- .subset2(new_design, \"index\"))) {\n # we always prevent from reordering twice.\n new_index <- reorder_index(new_panel, old_index)\n if (!all(old_index == new_index)) {\n cli_abort(sprintf(\n \"%s disrupt the previously established ordering index of %s (%d)\",\n object_name, object_name(layout), i\n ))\n }\n new_design[\"index\"] <- list(new_index)\n }\n new_design[\"nobs\"] <- list(new_nobs)\n new_design[\"panel\"] <- list(new_panel)\n }\n design_list[i] <- list(new_design)\n\n # we then update the design for each plot\n if (i == 1L) {\n subset <- seq_len(cross_point)\n } else {\n subset <- (.subset(points, i - 1L) + 1L):cross_point\n }\n\n layout@plot_list[subset] <- lapply(\n plot_list[subset], function(plot) {\n if (is_craftbox(plot)) {\n return(plot)\n }\n update_design(plot,\n direction = layout@direction,\n design = new_design\n )\n }\n )\n if (from_head && any(cross_point == break_points)) break\n }\n layout@odesign <- vec_slice(design_list, seq_len(length(design_list) - 1L))\n layout@design <- design_list[[length(design_list)]]\n layout\n}\n\n############################################################\nmelt_discrete_design <- function(old, new, old_name, new_name,\n call = caller_call()) {\n old_nobs <- .subset2(old, \"nobs\")\n new_nobs <- .subset2(new, \"nobs\")\n if (is.null(new_nobs)) { # no `nobs` provided\n nobs <- old_nobs\n } else if (is.null(old_nobs)) {\n nobs <- new_nobs\n } else if (!identical(new_nobs, old_nobs)) {\n cli_abort(sprintf(\n \"%s (nobs: %d) is not compatible with the %s (nobs: %d)\",\n new_name, new_nobs, old_name, old_nobs\n ), call = call)\n } else {\n nobs <- new_nobs\n }\n\n # check panel\n old_panel <- .subset2(old, \"panel\")\n new_panel <- .subset2(new, \"panel\")\n\n if (is.null(new_panel)) { # no panel provided\n panel <- old_panel\n } else if (!is.null(old_panel) && !(new_panel %nest% old_panel)) {\n cli_abort(sprintf(\n \"%s disrupt the previously established panel groups of %s\",\n new_name, old_name\n ), call = call)\n } else {\n panel <- new_panel\n }\n\n # check index\n old_index <- .subset2(old, \"index\")\n new_index <- .subset2(new, \"index\")\n if (is.null(new_index)) {\n index <- old_index\n } else {\n index <- new_index\n }\n\n # we always make the index following the panel\n if (!is.null(panel) && !is.null(index)) {\n index <- reorder_index(panel, index)\n }\n\n # we always prevent from reordering twice.\n if (!is.null(old_index) && !all(old_index == index)) {\n cli_abort(sprintf(\n \"%s disrupt the previously established ordering index of %s\",\n new_name, old_name\n ), call = call)\n }\n discrete_design(panel, index, nobs)\n}\n\n#######################################################################\n# ggplot2 add default scales in `compute_aesthetics` process\n# then ggplot2 transform all scales\n# layout:\n# in ggplot_build\n# - `setup`:\n# - call `facet$setup_params`\n# - attach `plot_env`\n# - call `facet$setup_data`\n# - call `facet$compute_layout`\n# - call `coord$setup_layout`\n# - call `facet$map_data`\n# - `train_position`: (run twice)\n# - call `facet$init_scales`\n# - call `facet$train_scales`\n# - `setup_panel_params`\n# - call `coord$modify_scales`: we align scales here, since this step\n# scales have been trained\n# - call `coord$setup_panel_params`: `view_scales_from_scale()`\n# - `map_position`\n# - `setup_panel_guides`\n# - call `coord$setup_panel_guides`\n# - call `coord$train_panel_guides`\n# in ggplot_gtable\n# - `layout$render`:\n# - call `facet$draw_back`\n# - call `facet$draw_front`\n# - call `coord$draw_panel` for each panel\n# - call `facet$draw_panels`: only once\n# - call `facet$init_gtable`:\n# - call `facet$attach_axes`:\n# - call `coord$render_axis_h`:\n# - call `guide$draw`:\n# - call `coord$render_axis_v`:\n# - call `guide$draw`:\n# - call `facet$attach_strips`:\n\n#' Set `limits`, `breaks`, `labels` for each panel\n#'\n#' @param x,y design for the layout.\n#' @keywords internal\n#' @noRd\nggalign_design <- function(x = NULL, y = NULL,\n xlabels = NULL, ylabels = NULL,\n xlim = TRUE, ylim = TRUE) {\n structure(\n list(\n x = x, y = y,\n xlabels = xlabels, ylabels = ylabels,\n xlim = xlim, ylim = ylim\n ),\n class = \"ggalign_design\"\n )\n}\n\nsetup_discrete_limits <- function(axis, design, n_panels) {\n panel <- .subset2(design, \"panel\")\n index <- .subset2(design, \"index\")\n if (n_panels == 1L) {\n list(range(index) + c(-0.5, 0.5))\n } else {\n # For y-axis, ggplot arrange panel from top to bottom,\n # we always choose to reverse the panel order\n if (axis == \"y\") panel <- fct_rev(panel)\n lapply(split(seq_along(index), panel), function(plot_index) {\n range(plot_index) + c(-0.5, 0.5)\n })\n }\n}\n\n#' @importFrom ggplot2 ggplot_add ggproto ggproto_parent\n#' @export\nggplot_add.ggalign_design <- function(object, plot, object_name, ...) {\n x_design <- .subset2(object, \"x\")\n y_design <- .subset2(object, \"y\")\n if (is.null(x_design) && is.null(y_design)) {\n return(plot)\n }\n ParentCoord <- plot$coordinates\n plot$coordinates <- ggproto(\n NULL, ParentCoord,\n num_of_panels = NULL,\n panel_counter = NULL,\n n_row_panels = NULL, # should be the number of panels in y\n n_column_panels = NULL, # should be the number of panels in x\n setup_layout = function(self, layout, params) {\n # we always initialize the number of panels and a panel counter\n self$num_of_panels <- vec_unique_count(.subset2(layout, \"PANEL\"))\n self$panel_counter <- 0L\n self$n_column_panels <- vec_unique_count(.subset2(layout, \"COL\"))\n self$n_row_panels <- vec_unique_count(.subset2(layout, \"ROW\"))\n if (.subset2(object, \"xlim\") && !is.null(x_design)) {\n if (is_discrete_design(x_design)) {\n self$xlim_list <- setup_discrete_limits(\n \"x\", x_design, self$n_column_panels\n )\n } else {\n self$xlim_list <- x_design\n }\n }\n if (.subset2(object, \"ylim\") && !is.null(y_design)) {\n if (is_discrete_design(y_design)) {\n self$ylim_list <- setup_discrete_limits(\n \"y\", y_design, self$n_row_panels\n )\n } else {\n self$ylim_list <- y_design\n }\n }\n # call the parent method\n ggproto_parent(ParentCoord, self)$setup_layout(layout, params)\n },\n # take the tricks to modify scales in place\n modify_scales = function(self, scales_x, scales_y) {\n # for each scale, we set the `breaks` and `labels`\n if (is_discrete_design(x_design)) {\n align_discrete_scales(\n \"x\", scales_x, x_design,\n labels = .subset2(object, \"xlabels\"),\n n_panels = self$n_column_panels,\n circle_layout = inherits(ParentCoord, \"CoordRadial\")\n )\n }\n if (is_discrete_design(y_design)) {\n align_discrete_scales(\n \"y\", scales_y, y_design,\n labels = .subset2(object, \"ylabels\"),\n n_panels = self$n_row_panels,\n circle_layout = inherits(ParentCoord, \"CoordRadial\")\n )\n }\n ggproto_parent(ParentCoord, self)$modify_scales(scales_x, scales_y)\n },\n setup_panel_params = function(self, scale_x, scale_y, params = list()) {\n # `setup_panel_params()` will utilize the `limits`\n # set limits here to ensure each plot will have the same limits\n cur_panel <- self$panel_counter + 1L\n if (!is.null(self$xlim_list)) {\n xlim <- .subset2(\n self$xlim_list,\n recycle_whole(cur_panel, self$n_column_panels)\n )\n if (is_discrete_design(x_design) && scale_x$is_discrete() &&\n !is.null(scale_x$range$range)) {\n # for discrete scale, the limits starts from zero in each\n # panel\n xlim <- xlim - (min(xlim) - 0.5)\n }\n if (inherits(self, \"CoordRadial\")) {\n self$limits$theta <- xlim\n } else {\n self$limits$x <- xlim\n }\n }\n if (!is.null(self$ylim_list)) {\n ylim <- .subset2(\n self$ylim_list,\n recycle_each(cur_panel, self$n_column_panels)\n )\n if (is_discrete_design(y_design) && scale_y$is_discrete() &&\n !is.null(scale_y$range$range)) {\n # for discrete scale, the limits starts from zero in each\n # panel\n ylim <- ylim - (min(ylim) - 0.5)\n }\n if (inherits(self, \"CoordRadial\")) {\n self$limits$r <- ylim\n } else {\n self$limits$y <- ylim\n }\n }\n self$panel_counter <- cur_panel\n ggproto_parent(ParentCoord, self)$setup_panel_params(\n scale_x = scale_x, scale_y = scale_y, params = params\n )\n }\n )\n plot\n}\n\nalign_discrete_scales <- function(axis, scales, design, labels, n_panels,\n circle_layout) {\n panel <- .subset2(design, \"panel\")\n index <- .subset2(design, \"index\")\n\n if (n_panels == 1L) {\n panel <- factor(vec_rep(1L, length(index)))\n } else {\n # For y-axis, ggplot arrange panel from top to bottom,\n # we always choose to reverse the panel order\n if (axis == \"y\") panel <- fct_rev(panel)\n }\n if (is.null(labels)) {\n data_labels <- NULL\n } else {\n data_labels <- split(labels, panel)\n }\n data_index <- split(index, panel)\n plot_index <- split(seq_along(index), panel)\n default_expand <- ggplot2::expansion()\n for (i in seq_along(scales)) {\n scale <- .subset2(scales, i)\n # we always use the discrete scale to determine labels and breaks\n # https://github.com/tidyverse/ggplot2/blob/7fb4c382f9ea332844d469663a8047355a88dd7a/R/scale-.R#L927\n # setup breaks and labels --------------------\n if (is.null(data_labels) &&\n is.waive(scale$labels) &&\n is.waive(scale$breaks)) {\n # special case for data have no labels\n # By default we also remove the breaks\n scale$breaks <- NULL\n scale$labels <- NULL\n } else {\n dindex <- .subset2(data_index, i)\n pindex <- .subset2(plot_index, i)\n labels <- .subset2(data_labels, i)\n scale$breaks <- get_discrete_breaks(scale, pindex, dindex, labels)\n scale$labels <- get_discrete_labels(\n scale, scale$breaks, pindex, dindex, labels\n )\n }\n\n # by default we elways remove any expansion\n # we don't allow the set of expansion for discrete variables\n # otherwise, ggmark and `cross_mark` won't work properly\n if (!circle_layout) scale$expand <- default_expand\n\n # for continuous scale, we don't allow the trans\n # if (!scale$is_discrete() && !identical(scale$trans$name, \"identity\")) {\n # cli_warn(sprintf(\n # \"{.arg trans} must be {.field identity} in {.code %s}\",\n # deparse(scale$call)\n # ))\n # scale$trans <- scales::as.transform(\"identity\")\n # }\n }\n}\n\n#' @importFrom rlang is_empty\nget_discrete_breaks <- function(scale, pindex, dindex, labels) {\n if (scale$is_empty()) return(numeric()) # styler: off\n breaks <- scale$breaks\n if (identical(breaks, NA)) {\n cli_abort(c(\n \"Invalid {.arg breaks} specification.\",\n i = \"Use {.code NULL}, not {.code NA}.\"\n ), call = scale$call)\n }\n if (is.null(breaks)) {\n return(NULL)\n }\n if (is.waive(breaks)) {\n if (scale$is_discrete() &&\n !is.null(labels) &&\n !is.null(scale$range$range) &&\n all(scale$range$range %in% labels)) {\n ans <- labels\n } else {\n ans <- pindex\n }\n } else {\n if (is.null(labels)) {\n limits <- dindex\n } else {\n limits <- labels\n }\n if (is.function(breaks)) {\n breaks <- breaks(limits)\n }\n\n if (is.factor(breaks) || is.character(breaks)) {\n # we interpreted the character breaks as the names of the original\n # matrix data.\n pos <- match(\n as.character(limits),\n vec_cast(breaks, character(),\n x_arg = \"breaks\", call = scale$call\n )\n )\n } else {\n # By default, we interpreted the breaks as the data index\n # If wrapped with `I()`, we interpreted it as the plot index\n if (inherits(breaks, \"AsIs\")) { # plot index\n pos <- match(pindex, vec_cast(breaks, integer(),\n x_arg = \"breaks\", call = scale$call\n ))\n } else { # data index\n pos <- match(dindex, vec_cast(breaks, integer(),\n x_arg = \"breaks\", call = scale$call\n ))\n }\n }\n index <- which(!is.na(pos))\n if (is_empty(index)) {\n return(NULL)\n }\n pos <- pos[index]\n if (scale$is_discrete() &&\n !is.null(labels) &&\n !is.null(scale$range$range) &&\n all(scale$range$range %in% labels)) {\n ans <- structure(labels[index], index = index, pos = pos)\n } else {\n ans <- structure(pindex[index], index = index, pos = pos)\n }\n }\n ans\n}\n\n#' @importFrom rlang is_empty\nget_discrete_labels <- function(scale, breaks, pindex, dindex, labels) {\n scale_labels <- scale$labels\n if (is_empty(breaks) || is.null(scale_labels)) { # if no breaks, no labels\n return(NULL)\n }\n\n if (identical(scale_labels, NA)) {\n cli_abort(c(\n \"Invalid {.arg labels} specification.\",\n i = \"Use {.code NULL}, not {.code NA}.\"\n ), call = scale$call)\n }\n\n # Need to ensure that if breaks were dropped\n if (!is.null(index <- attr(breaks, \"index\"))) {\n dindex <- dindex[index]\n labels <- labels[index]\n }\n\n # if layout have no names, use the data index directly\n # re-defined the breaks, the plot use the coordinates index\n # we interpreted user input as the data index\n if (is.null(labels)) {\n user_breaks <- dindex\n } else {\n user_breaks <- labels\n }\n if (is.waive(scale_labels)) { # By default, use the breaks\n user_breaks\n } else if (is.function(scale_labels)) {\n scale_labels(user_breaks)\n } else if (!is.null(names(scale_labels))) {\n # If labels have names, use them to match with breaks\n map <- match(as.character(user_breaks), names(scale_labels))\n user_breaks[map] <- scale_labels[!is.na(map)]\n user_breaks\n } else {\n # Need to ensure that if breaks were dropped, corresponding labels\n # are too\n if (is.null(pos <- attr(breaks, \"pos\"))) {\n if (inherits(scale_labels, \"AsIs\")) { # already in the plot index\n # we sort the `pos` so labels ordering won't be changed\n scale_labels <- scale_labels[pindex]\n } else { # in the data index\n scale_labels <- scale_labels[dindex]\n }\n } else {\n if (inherits(scale_labels, \"AsIs\")) { # already in the plot index\n # we sort the `pos` so labels ordering won't be changed\n scale_labels <- scale_labels[sort(pos)]\n } else { # in the data index\n scale_labels <- scale_labels[pos]\n }\n }\n scale_labels\n }\n}\n\n######################################################\n# this will remove the old coordinate,\n# so always run firstly\ngguse_linear_coord <- function(plot, layout_name) {\n coord <- plot$coordinates\n if (!inherits(coord, \"CoordTrans\") && !coord$is_linear()) {\n cli_warn(c(\n sprintf(\n \"{.fn %s} is not supported in %s\",\n snake_class(coord), layout_name\n ),\n i = \"Will use {.fn coord_cartesian} instead\"\n ))\n plot$coordinates <- ggplot2::coord_cartesian()\n }\n plot\n}\n\ngguse_circle_coord <- function(plot, coord, ..., layout_name) {\n if (inherits(plot_coord <- plot$coordinates, \"CoordRadial\")) {\n out <- ggproto(\n NULL, plot_coord,\n theta = coord$theta,\n r = coord$r,\n arc = coord$arc,\n direction = coord$direction,\n r_axis_inside = coord$r_axis_inside,\n expand = coord$expand,\n ...,\n setup_panel_params = circle_panel_params\n )\n } else {\n if (!isTRUE(plot$coordinates$default)) {\n cli_warn(c(\n sprintf(\n \"{.fn %s} is not supported in %s\",\n snake_class(plot_coord), layout_name\n ),\n i = sprintf(\"Will use {.fn %s} instead\", snake_class(coord))\n ))\n }\n if (!inherits(coord, \"CoordCircle\")) {\n out <- ggproto(NULL, coord, ...,\n setup_panel_params = circle_panel_params\n )\n } else {\n out <- ggproto(NULL, coord, ...)\n }\n }\n out\n}\n\n######################################################\n#' @importFrom ggplot2 ggproto\nggfacet_modify <- function(plot, ...) {\n ParentFacet <- plot$facet\n plot$facet <- ggproto(NULL, ParentFacet, ...)\n plot\n}\n\ngguse_facet <- function(plot, facet) {\n plot$facet <- facet\n plot\n}\n\nggmelt_facet <- function(plot, facet, ...) {\n gguse_facet(plot, melt_facet(facet, plot$facet, ...))\n}\n\n#' @param use A template facet object which will be used.\n#' @param facet User provided facet object.\n#' @noRd\nmelt_facet <- function(use, facet, ...) UseMethod(\"melt_facet\")\n\n#' @export\nmelt_facet.NULL <- function(use, facet, ...) {\n facet\n}\n\n#' @importFrom ggplot2 ggproto\n#' @export\nmelt_facet.FacetGrid <- function(use, facet, ...,\n free_row = FALSE,\n free_column = FALSE) {\n if (inherits(facet, \"FacetGrid\")) {\n # re-dispatch parameters\n params <- facet$params\n if (length(use$params$rows) || !free_row) {\n params$rows <- use$params$rows\n }\n if (length(use$params$cols) || !free_column) {\n params$cols <- use$params$cols\n }\n if (!free_row) { # Don't allow user change the rows\n params$free$y <- use$params$free$y\n params$space_free$y <- use$params$space_free$y\n }\n if (!free_column) { # Don't allow user change the cols\n params$free$x <- use$params$free$x\n params$space_free$x <- use$params$space_free$x\n }\n\n params$drop <- use$params$drop\n params$as.table <- use$params$as.table\n\n # if the use is free, it must be free\n ggproto(NULL, facet, params = params)\n } else {\n use\n }\n}\n\n#' @importFrom ggplot2 ggproto\n#' @export\nmelt_facet.FacetWrap <- function(use, facet, ...) {\n if (inherits(facet, \"FacetWrap\")) {\n # re-dispatch parameters\n params <- facet$params\n\n # we always fix the grid rows and cols\n params$facets <- use$params$facets\n params$nrow <- use$params$nrow\n params$ncol <- use$params$ncol\n params$drop <- use$params$drop\n params$as.table <- use$params$as.table\n ggproto(NULL, facet, params = params)\n } else {\n use\n }\n}\n\n#' @export\nmelt_facet.FacetNull <- function(use, facet, ...) {\n if (inherits(facet, \"FacetNull\")) {\n facet\n } else {\n use\n }\n}\n\n#' @export\nmelt_facet.FacetStack <- function(use, facet, ...) {\n if (inherits(facet, \"FacetGrid\")) {\n params <- facet$params\n if (is_horizontal(.subset2(use, \"direction\"))) {\n # for horizontal stack, we cannot facet by rows\n if (!is.null(params$rows)) {\n cli_warn(sprintf(\n \"Cannot facet by rows in %s\",\n .subset2(use, \"object_name\")\n ))\n params$rows <- NULL\n }\n } else if (!is.null(params$cols)) {\n # for vertical stack, we cannot facet by cols\n cli_warn(sprintf(\n \"Cannot facet by cols in %s\",\n .subset2(use, \"object_name\")\n ))\n params$cols <- NULL\n }\n ggproto(NULL, facet, params = params)\n } else if (inherits(facet, \"FacetWrap\")) {\n params <- facet$params\n if (is_horizontal(.subset2(use, \"direction\"))) {\n # for horizontal stack, we cannot facet by rows\n if (is.null(params$nrow)) {\n params$nrow <- 1L\n } else if (params$nrow > 1L) {\n cli_warn(sprintf(\n \"Cannot wrap facet by rows in %s\",\n .subset2(use, \"object_name\")\n ))\n params$nrow <- 1L\n }\n } else if (!is.null(params$cols)) {\n # for vertical stack, we cannot facet by cols\n if (is.null(params$ncol)) {\n params$ncol <- 1L\n } else if (params$ncol > 1L) {\n cli_warn(sprintf(\n \"Cannot wrap facet by cols in %s\",\n .subset2(use, \"object_name\")\n ))\n params$ncol <- 1L\n }\n }\n } else if (inherits(facet, \"FacetNull\")) {\n facet\n } else {\n ggplot2::facet_null()\n }\n}\n\nfacet_stack <- function(direction, object_name) {\n structure(\n list(direction = direction, object_name = object_name),\n class = \"FacetStack\"\n )\n}\n\n#' @export\nmelt_facet.FacetQuad <- function(use, facet, ...,\n free_row = FALSE,\n free_column = FALSE) {\n if (inherits(facet, \"FacetGrid\")) {\n if (free_row || free_column) {\n params <- facet$params\n if (!free_row && !is.null(params$rows)) {\n cli_warn(sprintf(\n \"Cannot facet by rows in %s\",\n .subset2(use, \"layout_name\")\n ))\n params$rows <- NULL\n # for horizontal stack, we cannot facet by rows\n }\n if (!free_column && !is.null(params$cols)) {\n cli_warn(sprintf(\n \"Cannot facet by cols in %s\",\n .subset2(use, \"layout_name\")\n ))\n params$cols <- NULL\n }\n ggproto(NULL, facet, params = params)\n } else {\n ggplot2::facet_null()\n }\n } else if (inherits(facet, \"FacetNull\")) {\n facet\n } else {\n ggplot2::facet_null()\n }\n}\n\nfacet_quad <- function(layout_name) {\n structure(list(layout_name = layout_name), class = \"FacetQuad\")\n}\n"], ["/ggalign/R/craft-cross-.R", "cross <- function(cross = NULL, data = waiver(),\n data_params = list(), ...,\n inherit_index = NULL,\n inherit_panel = NULL,\n inherit_nobs = NULL,\n plot = NULL, active = NULL, size = NULL, schemes = NULL,\n data_arg = caller_arg(data),\n call = caller_call()) {\n if (override_call(call)) {\n call <- current_call()\n }\n new_craftbox(\n craftsman = cross %||% CraftCross,\n data = allow_lambda(data), data_params = data_params,\n ...,\n inherit_nobs = inherit_nobs,\n inherit_panel = inherit_panel,\n inherit_index = inherit_index,\n plot = plot, active = active, size = size, schemes = schemes,\n data_arg = data_arg, call = call\n )\n}\n\n#' @importFrom ggplot2 ggproto ggproto_parent\n#' @include craftbox-.R\nCraftCross <- ggproto(\n \"CraftCross\", Craftsman,\n free_facet = TRUE,\n free_limits = TRUE,\n data_params = NULL,\n inherit_nobs = NULL,\n inherit_panel = NULL,\n inherit_index = NULL,\n interact_layout = function(self, layout) {\n # 1. check layout is `*_cross()`\n # 2. add `cross_points`\n # 3. add `odesign`\n # 4. define `labels`, we'll rename the `labels` to `labels0`\n layout <- ggproto_parent(CrossGg, self)$interact_layout(layout)\n\n # will define `labels0`\n self$labels0 <- self$labels\n\n # check the previous (between two `break_points`) define has been\n # initialized\n if (length(layout@break_points) &&\n is.null(.subset2(layout@design, \"nobs\"))) {\n cli_abort(sprintf(\n \"layout {.field nobs} for %s must be initialized before adding %s\",\n self$layout_name, object_name(self)\n ))\n }\n\n # setup data\n layout_data <- layout@data\n design <- layout@design\n\n if (is.waive(input_data <- self$data)) { # inherit from the layout\n data <- layout_data\n # `data` is NULL, `inherit_nobs` can be `TRUE` or `FALSE`, we by\n # default regard `inherit_nobs` as `TRUE`\n if (is.null(data) && isFALSE(self$inherit_nobs)) {\n design[\"nobs\"] <- list(NULL)\n }\n\n # `data` is not `NULL`, the `nobs` will always be the same with\n # previous design, nothing to do\n } else {\n if (is.function(input_data)) {\n if (is.null(layout_data)) {\n cli_abort(c(\n sprintf(\n \"{.arg data} in %s cannot be a function\",\n object_name(self)\n ),\n i = sprintf(\"no data was found in %s\", self$layout_name)\n ))\n }\n data <- input_data(layout_data)\n } else {\n data <- input_data\n }\n data <- inject(\n fortify_matrix(\n data, !!!self$data_params,\n data_arg = self$data_arg,\n call = self$call\n )\n ) %|w|% NULL\n if (isTRUE(self$inherit_nobs)) { # we require inherit nobs\n # we check if the data match original data dimention\n if (!is.null(data) &&\n !is.null(.subset2(design, \"nobs\")) &&\n NROW(data) != .subset2(design, \"nobs\")) {\n cli_abort(c(\n sprintf(\n \"%s (nobs: %d) is not compatible with the %s (nobs: %d)\",\n object_name(self), NROW(data), layout_name, layout_nobs\n ),\n i = \"try to set {.code inherit_nobs = FALSE}\"\n ))\n }\n } else { # for `FALSE` and `NULL`\n if (is.null(data)) {\n design[\"nobs\"] <- list(NULL)\n } else {\n if (NROW(data) == 0L) {\n cli_abort(\"{.arg data} cannot be empty\",\n call = self$call\n )\n }\n design[\"nobs\"] <- list(NROW(data))\n }\n }\n }\n\n # we keep the names from the layout data for usage\n self$labels <- vec_names(data)\n\n # determine if we should inherit panel\n # by default, `inherit_panel = FALSE`\n if (isTRUE(self$inherit_panel)) {\n if (is.null(self$labels0)) {\n cli_abort(c(\n \"Cannot inherit panel from the layout\",\n i = \"No labels found in the layout data\"\n ))\n }\n if (is.null(self$labels)) {\n cli_abort(c(\n \"Cannot inherit panel from the layout\",\n i = \"No labels found in the current {.arg data}\"\n ))\n }\n if (!all(self$labels %in% self$labels0)) {\n cli_abort(c(\n \"Cannot inherit panel from the layout\",\n i = \"Some labels in the current data are not found in the previous layout data\"\n ))\n }\n if (!is.null(panel <- .subset2(design, \"panel\"))) {\n design[\"panel\"] <- list(\n droplevels(panel[match(self$labels, self$labels0)])\n )\n }\n } else {\n design[\"panel\"] <- list(NULL)\n }\n\n # determine if we should inherit panel\n # by default, `inherit_index = FALSE`\n if (isTRUE(self$inherit_index)) {\n if (is.null(self$labels0)) {\n cli_abort(c(\n \"Cannot inherit ordering index from the layout\",\n i = \"No labels found in the previous layout data\"\n ))\n }\n\n if (is.null(self$labels)) {\n cli_abort(c(\n \"Cannot inherit ordering index from the layout\",\n i = \"No labels found in the current {.arg data}\"\n ))\n }\n\n if (!all(self$labels %in% self$labels0)) {\n cli_abort(c(\n \"Cannot inherit ordering index from the layout\",\n i = \"Some labels in the current data are not found in the previous layout data\"\n ))\n }\n\n if (!is.null(index <- .subset2(design, \"index\"))) {\n new_index <- order(match(\n self$labels,\n vec_slice(self$labels0, index)\n ))\n\n # we always make the index following the panel\n if (!is.null(panel <- .subset2(design, \"panel\"))) {\n new_index <- reorder_index(panel, new_index)\n }\n design[\"index\"] <- list(new_index)\n }\n } else {\n design[\"index\"] <- list(NULL)\n }\n\n # reset layout data\n layout@data <- data # don't restore the attribute\n\n # update the design\n layout@design <- design\n\n # udpate break_points\n layout@break_points <- c(layout@break_points, length(layout@plot_list))\n layout\n }\n)\n"], ["/ggalign/R/layout-chain-.R", "# Used by both `circle_layout()` and `stack_layout()`\n#' @keywords internal\n#' @include layout-.R\nmethods::setClass(\n \"ChainLayout\",\n contains = \"LayoutProto\",\n list(\n data = \"ANY\",\n name = \"character\", # used to provide message\n plot_list = \"list\", # save the list of plots\n design = \"ANY\" # used to align axis\n )\n)\n\n#' Finalize plot modifications from a ChainLayout object.\n#'\n#' This generic function lets a ChainLayout apply any final transformations\n#' to the composed plot before returning it. It does not extract or store\n#' the plot, but instead allows the layout to inject custom modifications\n#' (e.g., spacing guides, annotations, alignment fixes) at the last step.\n#'\n#' @param layout A ChainLayout object.\n#' @param plot The plot being finalized.\n#' @keywords internal\nchain_decorate <- function(layout, plot) UseMethod(\"chain_decorate\")\n\n#' @export\nchain_decorate.ChainLayout <- function(layout, plot) plot\n\n#' @export\nis_layout_discrete.ChainLayout <- function(x, ...) {\n is_discrete_design(x@design)\n}\n\n#' @export\nis_layout_continuous.ChainLayout <- function(x, ...) {\n is_continuous_design(x@design)\n}\n\n#############################################################\n# To-DO: Use double dispatch\n#' @keywords internal\nchain_layout_add <- function(object, layout, object_name) {\n UseMethod(\"chain_layout_add\")\n}\n\n#' @export\nchain_layout_add.layout_title <- function(object, layout, object_name) {\n layout@titles <- update_non_waive(layout@titles, object)\n layout\n}\n\n#' @export\nchain_layout_add.list <- function(object, layout, object_name) {\n for (o in object) layout <- chain_layout_add(o, layout, object_name)\n layout\n}\n\n#' @export\nchain_layout_add.NULL <- function(object, layout, object_name) {\n layout\n}\n\n#' @export\nchain_layout_add.CraftBox <- function(object, layout, object_name) {\n craftsman <- object@craftsman\n # To-Do: Use S7 and double dispatch\n if (is.null(active_index <- layout@active) ||\n is_craftbox(plot <- .subset2(layout@plot_list, active_index))) {\n # unlock the object\n craftsman$unlock()\n\n # we lock the `Craftsman` object to prevent user from modifying this\n # object in `$build_plot()` method, we shouldn't do any calculations in\n # `$build_plot()` method\n on.exit(craftsman$lock())\n\n # initialize the necessary parameters for `Craftsman` object\n if (is_stack_layout(layout)) {\n craftsman$direction <- layout@direction\n craftsman$position <- .subset2(layout@heatmap, \"position\")\n } else if (is_circle_layout(layout)) {\n # we treat circle layout as a vertical stack layout\n craftsman$direction <- \"vertical\"\n }\n craftsman$in_linear <- is_linear(layout)\n craftsman$layout_name <- object_name(layout)\n\n # firstly, we let the object do some changes in the layout\n layout <- craftsman$interact_layout(layout)\n\n # this step, the object will act with the stack layout\n # group rows into panel or reorder rows, we can also\n # initialize object data\n new_design <- craftsman$setup_design(layout@design)\n\n # initialize the plot object\n object@plot <- craftsman$setup_plot(object@plot)\n\n layout <- chain_add_plot(layout, object, object@active, object_name)\n } else { # should be a QuadLayout object\n plot <- quad_layout_add(object, plot, object_name)\n layout@plot_list[[active_index]] <- plot\n new_design <- slot(plot, layout@direction)\n }\n update_design(layout, design = new_design, object_name = object_name)\n}\n\n#' @export\nchain_layout_add.continuous_limits <- function(object, layout, object_name) {\n if (is_discrete_design(layout@design)) {\n cli_abort(c(\n sprintf(\n \"Cannot add {.var {object_name}} to %s\",\n object_name(layout)\n ),\n i = sprintf(\n \"%s cannot align continuous variables\",\n object_name(layout)\n )\n ))\n }\n update_design(layout, design = object, object_name = object_name)\n}\n\n#' @export\nchain_layout_add.ggplot <- function(object, layout, object_name) {\n chain_layout_add(ggfree(data = object), layout, object_name)\n}\n\n# Add ggplot2 elements\n#' @export\nchain_layout_add.default <- function(object, layout, object_name) {\n if (is.null(active_index <- layout@active)) {\n cli_abort(c(\n sprintf(\n \"Cannot add {.var {object_name}} to %s\",\n object_name(layout)\n ),\n i = \"No active plot component\",\n i = paste(\n \"Did you forget to initialize a {.cls ggplot} object\",\n \"with {.fn ggalign} or {.fn ggfree}?\"\n )\n ))\n }\n plot <- .subset2(layout@plot_list, active_index)\n if (is_craftbox(plot)) {\n plot <- chain_plot_add(plot, object, object_name, TRUE)\n } else {\n plot <- quad_layout_add(object, plot, object_name)\n }\n layout@plot_list[[active_index]] <- plot\n layout\n}\n\n#' @export\nchain_layout_add.layout_theme <- function(object, layout, object_name) {\n if (is.null(active_index <- layout@active) ||\n is_craftbox(plot <- .subset2(layout@plot_list, active_index))) {\n layout@theme <- update_layout_theme(layout@theme, object)\n } else {\n layout@plot_list[[active_index]] <- quad_layout_add(\n object, plot, object_name\n )\n }\n layout\n}\n\nchain_plot_add <- function(plot, object, object_name, force) {\n # if `align` has plot, we added the object\n if (force || !is.null(plot@plot)) {\n plot <- craftbox_add(object, plot, object_name)\n }\n plot\n}\n\nchain_add_plot <- function(layout, plot, active, object_name) {\n # set up context index\n plot_list <- layout@plot_list\n if (.subset2(active, \"use\")) {\n active_index <- length(plot_list) + 1L\n } else {\n active_index <- layout@active\n }\n # check the name is unique\n if (!is.na(name <- .subset2(active, \"name\"))) {\n if (any(names(plot_list) == name)) {\n cli_warn(\n \"Adding {.var {object_name}} will replace existing {.field {name}} plot\"\n )\n }\n plot_list[[name]] <- plot\n } else {\n plot_list <- c(plot_list, list(plot))\n }\n\n # add QuadLayout\n layout@plot_list <- plot_list\n layout@active <- active_index\n layout\n}\n\nswitch_chain_plot <- function(layout, what, call = caller_call()) {\n if (!is.waive(what)) {\n if (!is.null(what)) {\n what <- vec_as_location2(\n what,\n vec_size(layout@plot_list),\n vec_names(layout@plot_list),\n missing = \"error\",\n arg = \"what\", call = call\n )\n }\n layout@active <- what\n }\n layout\n}\n\n##############################################################\n# for `stack_layout()` only\n#' @export\nchain_layout_add.ggalign_with_quad <- function(object, layout, object_name) {\n if (!is_stack_layout(layout)) {\n cli_abort(sprintf(\n \"Cannot add {.var {object_name}} to %s\",\n object_name(layout)\n ))\n }\n if (is.null(active_index <- layout@active) ||\n is_craftbox(plot <- .subset2(layout@plot_list, active_index))) {\n cli_abort(c(\n sprintf(\n \"Cannot add {.var {object_name}} to %s\",\n object_name(layout)\n ),\n i = \"Did you forget to add a {.fn quad_layout}?\"\n ))\n } else {\n layout@plot_list[[active_index]] <- quad_layout_add(\n object, plot, object_name\n )\n }\n layout\n}\n\n#' @export\nchain_layout_add.quad_active <- chain_layout_add.ggalign_with_quad\n\n#' @export\nchain_layout_add.quad_anno <- chain_layout_add.quad_active\n\n#' @export\nchain_layout_add.StackLayout <- chain_layout_add.quad_active\n\n#' @export\nchain_layout_add.StackCross <- function(object, layout, object_name) {\n if (!is_stack_layout(layout)) {\n cli_abort(sprintf(\n \"Cannot add {.var {object_name}} to %s\",\n object_name(layout)\n ))\n }\n\n # preventing from adding `stack_cross` with the same direction in this way,\n # `stack_cross()` cannot be added to the heatmap annotation parallelly with\n # the `stack_layout()`\n if (identical(object@direction, layout@direction)) {\n cli_abort(c(\n sprintf(\n \"Cannot add {.var {object_name}} to %s\",\n object_name(layout)\n ),\n i = \"Cannot add {.fn stack_cross} with the same direction as {.fn stack_discrete}.\"\n ))\n }\n NextMethod() # call StackLayout method\n}\n\n#' @export\nchain_layout_add.stack_switch <- function(object, layout, object_name) {\n if (!is_stack_layout(layout)) {\n cli_abort(c(\n sprintf(\n \"Cannot add {.var {object_name}} to %s\",\n object_name(layout)\n ),\n i = \"Did you want to add a {.fn circle_switch}?\"\n ))\n }\n layout <- switch_chain_plot(\n layout, .subset2(object, \"what\"),\n quote(stack_switch())\n )\n if (!is.null(sizes <- .subset2(object, \"sizes\"))) {\n layout@sizes <- sizes\n }\n layout\n}\n\n#' @importFrom methods slot\n#' @export\nchain_layout_add.QuadLayout <- function(object, layout, object_name) {\n if (!is_stack_layout(layout)) {\n cli_abort(sprintf(\n \"Cannot add {.var {object_name}} to %s\",\n object_name(layout)\n ))\n }\n\n # preventing from adding `stack_cross` with the same direction\n # `cross_link()` cannot be added to the heatmap annotation\n # parallelly with the `stack_cross()`\n if (is_horizontal(direction <- layout@direction)) {\n if (is_cross_layout(object@left) || is_cross_layout(object@right)) {\n cli_abort(c(\n sprintf(\n \"Cannot add {.var {object_name}} to %s\",\n object_name(layout)\n ),\n i = sprintf(\n \"{.field left} or {.field right} annotation contains %s\",\n \"{.fn stack_cross}\"\n )\n ))\n }\n } else if (is_cross_layout(object@top) || is_cross_layout(object@bottom)) {\n cli_abort(c(\n sprintf(\n \"Cannot add {.var {object_name}} to %s\",\n object_name(layout)\n ),\n i = sprintf(\n \"{.field top} or {.field bottom} annotation contains %s\",\n \"{.fn stack_cross}\"\n )\n ))\n }\n\n # check quad layout is compatible with stack layout\n quad_data <- object@data\n stack_design <- layout@design\n quad_design <- slot(object, direction)\n if (is_continuous_design(quad_design)) {\n if (is_discrete_design(stack_design)) {\n cli_abort(c(\n sprintf(\n \"Cannot add %s to %s\",\n object_name(object), object_name(layout)\n ),\n i = sprintf(\n \"%s cannot align continuous variable\",\n object_name(layout)\n )\n ))\n }\n # `quad_layout()` will align continuous variables,\n # `data` can be `NULL`\n extra_design <- slot(object, vec_set_difference(\n c(\"vertical\", \"horizontal\"), direction\n ))\n allow_null <- is_continuous_design(extra_design)\n if (is.waive(quad_data) || is.function(quad_data)) {\n # check if we should initialize the `quad_layout()` data\n if (is.null(stack_data <- layout@data)) {\n if (allow_null) {\n quad_data <- NULL\n } else {\n cli_abort(c(\n sprintf(\n \"you must provide {.arg data} argument in %s\",\n object_name(object)\n ),\n i = sprintf(\n \"no data was found in %s\",\n object_name(layout)\n )\n ))\n }\n } else {\n data <- stack_data # should be a data frame\n if (is.waive(quad_data)) { # inherit from the stack layout\n if (!allow_null) { # we need a matrix\n cli_abort(c(\n sprintf(\n \"Cannot add %s to %s\",\n object_name(object), object_name(layout)\n ),\n i = sprintf(\n \"{.arg data} in %s is %s, but %s need a {.cls matrix}.\",\n object_name(layout),\n \"{.obj_type_friendly {data}}\",\n object_name(object)\n ),\n i = sprintf(\n \"Try provide {.arg data} in %s\",\n object_name(object)\n )\n ))\n }\n } else { # `quad_data` is a function\n data <- quad_data(data)\n # check the data format is correct\n if (allow_null) { # we need a data frame\n if (!is.data.frame(data)) {\n cli_abort(sprintf(\n \"{.arg data} in %s must return a {.cls data.frame}\",\n object_name(object)\n ))\n }\n } else if (!is.matrix(data)) { # we need a matrix\n cli_abort(sprintf(\n \"{.arg data} in %s must return a {.cls matrix}\",\n object_name(object)\n ))\n } else {\n if (NROW(data) == 0L || ncol(data) == 0L) {\n cli_abort(sprintf(\n \"{.arg data} in %s return an empty matrix\",\n object_name(object)\n ))\n }\n }\n }\n # we initialize the `nobs` of the extra_design for the\n # `quad_layout()`\n if (is_horizontal(direction)) {\n if (is_discrete_design(slot(object, \"vertical\"))) {\n slot(object, \"vertical\")$nobs <- ncol(data)\n }\n } else {\n if (is_discrete_design(slot(object, \"horizontal\"))) {\n slot(object, \"horizontal\")$nobs <- nrow(data)\n }\n }\n }\n # restore the ggalign attribute\n object@data <- ggalign_data_restore(data, stack_data)\n }\n layout_design <- quad_design\n } else if (is_discrete_design(stack_design)) {\n # both `quad_layout()` and `stack_layout()` will align discrete\n # variables\n if (is.waive(quad_data) || is.function(quad_data)) {\n if (is.null(stack_data <- layout@data)) {\n cli_abort(c(\n sprintf(\n \"you must provide {.arg data} argument in %s\",\n object_name(object)\n ),\n i = sprintf(\n \"no data was found in %s\",\n object_name(layout)\n )\n ))\n }\n # set `quad_layout()` data\n data <- switch_direction(direction, stack_data, t(stack_data))\n if (is.function(quad_data)) {\n data <- quad_data(data)\n if (!is.matrix(data)) {\n cli_abort(sprintf(\n \"{.arg data} in %s must return a matrix\",\n object_name(object)\n ))\n }\n if (NROW(data) == 0L || ncol(data) == 0L) {\n cli_abort(sprintf(\n \"{.arg data} in %s return an empty matrix\",\n object_name(object)\n ))\n }\n } else {\n if (NROW(data) == 0L || ncol(data) == 0L) {\n cli_abort(c(\n sprintf(\n \"Cannot use data from %s in %s\",\n object_name(layout), object_name(object)\n ),\n i = sprintf(\n \"{.arg data} in %s is an empty matrix\",\n object_name(layout)\n )\n ))\n }\n }\n # set the `nobs` for `quad_layout()`\n if (is_horizontal(direction)) {\n quad_design$nobs <- nrow(data)\n if (is_discrete_design(slot(object, \"vertical\"))) {\n slot(object, \"vertical\")$nobs <- ncol(data)\n }\n } else {\n quad_design$nobs <- ncol(data)\n if (is_discrete_design(slot(object, \"horizontal\"))) {\n slot(object, \"horizontal\")$nobs <- nrow(data)\n }\n }\n # restore the ggalign attribute\n object@data <- ggalign_data_restore(data, stack_data)\n }\n layout_design <- melt_discrete_design(\n stack_design, quad_design,\n old_name = object_name(layout),\n new_name = object_name\n )\n } else {\n cli_abort(c(\n sprintf(\n \"Cannot add %s to %s\",\n object_name(object), object_name(layout)\n ),\n i = sprintf(\n \"%s cannot align discrete variable\",\n object_name(layout)\n )\n ))\n }\n stack <- chain_add_plot(layout, object, object@plot_active, object_name)\n update_design(\n stack,\n design = layout_design,\n object_name = object_name\n )\n}\n\n##################################################\n#' @export\nchain_layout_add.circle_switch <- function(object, layout, object_name) {\n if (!is_circle_layout(layout)) {\n cli_abort(c(\n sprintf(\n \"Cannot add {.var {object_name}} to %s\",\n object_name(layout)\n ),\n i = \"Did you want to add a {.fn stack_switch}?\"\n ))\n }\n if (!is.waive(radial <- .subset2(object, \"radial\"))) {\n layout@radial <- radial\n }\n if (!is.null(direction <- .subset2(object, \"direction\"))) {\n layout@direction <- direction\n }\n layout <- switch_chain_plot(\n layout, .subset2(object, \"what\"),\n quote(circle_switch())\n )\n layout\n}\n"], ["/ggalign/R/layout-chain-circle-.R", "#' Arrange plots in a circular layout\n#'\n#' @description\n#' `r lifecycle::badge('experimental')`\n#'\n#' If `limits` is provided, a continuous variable will be required and aligned\n#' in the direction specified (`circle_continuous`). Otherwise, a discrete\n#' variable will be required and aligned (`circle_discrete`).\n#'\n#' @param radial A [`coord_circle()`]/[`coord_radial()`][ggplot2::coord_radial]\n#' object that defines the global parameters for coordinate across all plots\n#' in the layout. The parameters `start`, `end`, `direction`, and `expand` will\n#' be inherited and applied uniformly to all plots within the layout. The\n#' parameters `theta` and `r.axis.inside` will always be ignored and will be set\n#' to `\"x\"` and `TRUE`, respectively, for all plots.\n#' @param direction A single string of `r oxford_or(c(\"inward\", \"outward\"))`,\n#' indicating the direction in which the plot is added.\n#' - `outward`: The plot is added from the inner to the outer.\n#' - `inward`: The plot is added from the outer to the inner.\n#' @inheritParams stack_layout\n#' @return A `CircleLayout` object.\n#' @examples\n#' set.seed(123)\n#'\n#' small_mat <- matrix(rnorm(56), nrow = 7)\n#' rownames(small_mat) <- paste0(\"row\", seq_len(nrow(small_mat)))\n#' colnames(small_mat) <- paste0(\"column\", seq_len(ncol(small_mat)))\n#'\n#' # circle_layout\n#' # same for circle_discrete()\n#' circle_layout(small_mat) +\n#' ggalign() +\n#' geom_tile(aes(y = .column_index, fill = value)) +\n#' scale_fill_viridis_c() +\n#' align_dendro(aes(color = branch), k = 3L) +\n#' scale_color_brewer(palette = \"Dark2\")\n#'\n#' # same for circle_continuous()\n#' circle_layout(mpg, limits = continuous_limits(c(3, 5))) +\n#' ggalign(mapping = aes(displ, hwy, colour = class)) +\n#' geom_point(size = 2) +\n#' ggalign(mapping = aes(displ, hwy, colour = class)) +\n#' geom_point(size = 2) &\n#' scale_color_brewer(palette = \"Dark2\") &\n#' theme_bw()\n#'\n#' @export\ncircle_layout <- function(data = NULL, ..., radial = NULL,\n direction = \"outward\", sector_spacing = NULL,\n limits = waiver(), theme = NULL,\n spacing_theta = deprecated()) {\n if (is.waive(limits)) {\n circle_discrete(\n data = data, ..., radial = radial,\n direction = direction, sector_spacing = sector_spacing,\n theme = theme, spacing_theta = spacing_theta\n )\n } else {\n circle_continuous(\n data = data, ..., radial = radial,\n direction = direction, theme = theme, limits = limits,\n spacing_theta = spacing_theta\n )\n }\n}\n\n############################################################\n#' @inheritParams facet_sector\n#' @examples\n#' # circle_discrete()\n#' # direction outward\n#' circle_discrete(small_mat) +\n#' align_dendro(aes(color = branch), k = 3L) +\n#' scale_color_brewer(palette = \"Dark2\") +\n#' ggalign() +\n#' geom_tile(aes(y = .column_index, fill = value)) +\n#' scale_fill_viridis_c()\n#'\n#' # direction inward\n#' circle_discrete(small_mat, direction = \"inward\") +\n#' ggalign() +\n#' geom_tile(aes(y = .column_index, fill = value)) +\n#' scale_fill_viridis_c() +\n#' align_dendro(aes(color = branch), k = 3L) +\n#' scale_color_brewer(palette = \"Dark2\")\n#'\n#' @export\n#' @rdname circle_layout\ncircle_discrete <- function(data = NULL, ..., radial = NULL,\n direction = \"outward\", sector_spacing = NULL,\n theme = NULL, spacing_theta = deprecated()) {\n UseMethod(\"circle_discrete\", data)\n}\n\n#' @export\ncircle_discrete.default <- function(data = NULL, ..., radial = NULL,\n direction = \"outward\",\n sector_spacing = NULL,\n theme = NULL,\n spacing_theta = deprecated()) {\n # the observations are rows, we use matrix to easily\n # reshape it into a long formated data frame for ggplot,\n # and we can easily determine the number of observations\n # from matrix\n data <- data %|w|% NULL\n data <- fortify_matrix(data = data, ...)\n schemes <- default_schemes()\n if (!is.null(data) && !is.function(data)) {\n # if we have provided data, we initialize the `nobs`\n nobs <- vec_size(data)\n } else {\n nobs <- NULL\n }\n new_circle_layout(\n data = data,\n design = discrete_design(nobs = nobs),\n radial = radial, direction = direction, sector_spacing = sector_spacing,\n schemes = schemes, theme = theme, spacing_theta = spacing_theta\n )\n}\n\n#' @export\ncircle_discrete.function <- function(data = NULL, ...) {\n cli_abort(paste0(\n \"{.arg data} must be a {.cls matrix}, \",\n \"or an object coercible by {.fn fortify_matrix}, or a valid \",\n \"{.cls matrix}-like object coercible by {.fn as.matrix}\"\n ))\n}\n\n#' @export\ncircle_discrete.formula <- circle_discrete.function\n\n################################################################\n#' @examples\n#' # circle_continuous()\n#' circle_continuous(mpg, limits = continuous_limits(c(3, 5))) +\n#' ggalign(mapping = aes(displ, hwy, colour = class)) +\n#' geom_point(size = 2) +\n#' ggalign(mapping = aes(displ, hwy, colour = class)) +\n#' geom_point(size = 2) &\n#' scale_color_brewer(palette = \"Dark2\") &\n#' theme_bw()\n#' @export\n#' @rdname circle_layout\ncircle_continuous <- function(data = NULL, ..., radial = NULL,\n direction = \"outward\", sector_spacing = NULL,\n limits = NULL, theme = NULL,\n spacing_theta = deprecated()) {\n UseMethod(\"circle_continuous\", data)\n}\n\n#' @export\ncircle_continuous.default <- function(data = NULL, ..., radial = NULL,\n direction = \"outward\",\n sector_spacing = NULL,\n limits = NULL, theme = NULL,\n spacing_theta = deprecated()) {\n assert_limits(limits)\n data <- data %|w|% NULL\n data <- fortify_data_frame(data = data, ...)\n schemes <- default_schemes()\n new_circle_layout(\n data = data, design = limits,\n radial = radial, direction = direction, sector_spacing = sector_spacing,\n schemes = schemes, theme = theme, spacing_theta = spacing_theta\n )\n}\n\n#' @export\ncircle_continuous.function <- function(data = NULL, ...) {\n cli_abort(paste0(\n \"{.arg data} must be a {.cls data.frame}, \",\n \"or an object coercible by {.fn fortify_data_frame}, or a valid \",\n \"{.cls data.frame}-like object coercible by {.fn as.data.frame}\"\n ))\n}\n\n#' @export\ncircle_continuous.formula <- circle_continuous.function\n\n#' @importFrom methods new\nnew_circle_layout <- function(data, design, radial, direction,\n sector_spacing = NULL, schemes = NULL,\n theme = NULL, name = NULL,\n spacing_theta = deprecated(),\n call = caller_call()) {\n if (!is.null(theme)) assert_s3_class(theme, \"theme\", call = call)\n if (!is.null(radial) && !inherits(radial, c(\"CoordRadial\"))) {\n cli_abort(\"{.arg radial} must be created with {.fn coord_circle}\",\n call = call\n )\n }\n if (!is.null(radial) && abs(diff(radial$arc)) < pi / 2L) {\n cli_abort(\n \"Cannot create circle of acute angle < 90 in {.arg radial}\",\n call = call\n )\n }\n direction <- arg_match0(direction, c(\"inward\", \"outward\"))\n if (is.null(name)) {\n if (is_continuous_design(design)) {\n name <- \"circle_continuous\"\n } else {\n name <- \"circle_discrete\"\n }\n }\n if (lifecycle::is_present(spacing_theta)) {\n lifecycle::deprecate_warn(\n \"1.0.2\",\n \"facet_sector(spacing_theta = )\",\n \"facet_sector(sector_spacing = )\"\n )\n if (is.null(sector_spacing)) sector_spacing <- spacing_theta\n }\n new(\n \"CircleLayout\",\n name = name, data = data,\n schemes = schemes, # used by the layout\n design = design,\n sector_spacing = sector_spacing,\n theme = theme,\n radial = radial, direction = direction\n )\n}\n\n############################################################\n# Used to place multiple objects in one axis\n#' @importFrom grid unit\n#' @importFrom ggplot2 waiver\n#' @keywords internal\n#' @include layout-chain-.R\nmethods::setClass(\"CircleLayout\",\n contains = \"ChainLayout\",\n list(radial = \"ANY\", sector_spacing = \"ANY\", direction = \"character\")\n)\n"], ["/ggalign/R/import-standalone-obj-type.R", "# Standalone file: do not edit by hand\n# Source: https://github.com/Yunuuuu/standalone/blob/HEAD/R/standalone-obj-type.R\n# Generated by: usethis::use_standalone(\"Yunuuuu/standalone\", \"obj-type\")\n# ----------------------------------------------------------------------\n#\n# ---\n# repo: Yunuuuu/standalone\n# file: standalone-obj-type.R\n# last-updated: 2025-04-11\n# license: https://unlicense.org\n# imports: rlang (>= 1.1.0)\n# ---\n#\n# ## Changelog\n# 2025-04-11:\n# - new `allow_what_type`\n#\n# 2024-11-10:\n# - `obj_type_friendly()` gains a `length` argument to control whether to show\n# the length of the vector.\n# - `stop_input_type()` gains a `show_length` argument passed to\n# `obj_type_friendly`.\n#\n# 2024-02-14:\n# - `obj_type_friendly()` now works for S7 objects.\n#\n# 2023-05-01:\n# - `obj_type_friendly()` now only displays the first class of S3 objects.\n#\n# 2023-03-30:\n# - `stop_input_type()` now handles `I()` input literally in `arg`.\n#\n# 2022-10-04:\n# - `obj_type_friendly(value = TRUE)` now shows numeric scalars\n# literally.\n# - `stop_friendly_type()` now takes `show_value`, passed to\n# `obj_type_friendly()` as the `value` argument.\n#\n# 2022-10-03:\n# - Added `allow_na` and `allow_null` arguments.\n# - `NULL` is now backticked.\n# - Better friendly type for infinities and `NaN`.\n#\n# 2022-09-16:\n# - Unprefixed usage of rlang functions with `rlang::` to\n# avoid onLoad issues when called from rlang (#1482).\n#\n# 2022-08-11:\n# - Prefixed usage of rlang functions with `rlang::`.\n#\n# 2022-06-22:\n# - `friendly_type_of()` is now `obj_type_friendly()`.\n# - Added `obj_type_oo()`.\n#\n# 2021-12-20:\n# - Added support for scalar values and empty vectors.\n# - Added `stop_input_type()`\n#\n# 2021-06-30:\n# - Added support for missing arguments.\n#\n# 2021-04-19:\n# - Added support for matrices and arrays (#141).\n# - Added documentation.\n# - Added changelog.\n#\n# nocov start\n# Following codes were modified from `rlang` package\n\n#' @param x The object type which does not conform to `what`. Its\n#' `obj_type_friendly()` is taken and mentioned in the error message.\n#' @param show_value Passed to `value` argument of `obj_type_friendly()`.\n#' @param show_length Passed to `length` argument of `obj_type_friendly()`.\n#' @param ... Arguments passed to [abort()].\n#' @inheritParams args_error_context\n#' @importFrom rlang caller_arg caller_env abort\n#' @noRd\nstop_input_type <- function(x,\n what,\n ...,\n allow_na = FALSE,\n allow_null = FALSE,\n show_value = TRUE,\n show_length = FALSE,\n arg = caller_arg(x),\n call = caller_env()) {\n what <- allow_what_type(\n what,\n allow_na = allow_na,\n allow_null = allow_null\n )\n if (inherits(arg, \"AsIs\")) {\n format_arg <- identity\n } else {\n format_arg <- function(x) sprintf(\"`%s`\", x)\n }\n message <- sprintf(\n \"%s must be %s, not %s.\",\n format_arg(arg), what,\n obj_type_friendly(x, value = show_value, length = show_length)\n )\n abort(message, ..., call = call, arg = arg)\n}\n\n#' @param what The friendly expected type as a string. Can be a\n#' character vector of expected types, in which case the error\n#' message mentions all of them in an \"or\" enumeration.\n#' @noRd\nallow_what_type <- function(what, allow_na = FALSE, allow_null = FALSE) {\n if (allow_na) {\n what <- c(what, \"`NA`\")\n }\n if (allow_null) {\n what <- c(what, \"`NULL`\")\n }\n if (length(what)) {\n what <- .standalone_oxford_comma(what, final = \"or\")\n }\n what\n}\n\n#' Return English-friendly type\n#' @param x Any R object.\n#' @param value Whether to describe the value of `x`. Special values\n#' like `NA` or `\"\"` are always described.\n#' @param length Whether to mention the length of vectors and lists.\n#' @return A string describing the type. Starts with an indefinite\n#' article, e.g. \"an integer vector\".\n#' @importFrom rlang is_missing is_vector\n#' @noRd\nobj_type_friendly <- function(x, value = TRUE, length = FALSE) {\n if (is_missing(x)) {\n return(\"absent\")\n }\n\n if (is.object(x)) {\n if (inherits(x, \"quosure\")) {\n type <- \"quosure\"\n } else {\n type <- class(x)[[1L]]\n }\n return(sprintf(\"a <%s> object\", type))\n }\n\n if (!is_vector(x)) {\n return(.rlang_as_friendly_type(typeof(x)))\n }\n\n n_dim <- length(dim(x))\n\n if (!n_dim) {\n if (!is.list(x) && length(x) == 1) {\n if (is.na(x)) {\n return(switch(typeof(x),\n logical = \"`NA`\",\n integer = \"an integer `NA`\",\n double =\n if (is.nan(x)) {\n \"`NaN`\"\n } else {\n \"a numeric `NA`\"\n },\n complex = \"a complex `NA`\",\n character = \"a character `NA`\",\n .rlang_stop_unexpected_typeof(x)\n ))\n }\n\n show_infinites <- function(x) {\n if (x > 0) {\n \"`Inf`\"\n } else {\n \"`-Inf`\"\n }\n }\n str_encode <- function(x, width = 30, ...) {\n if (nchar(x) > width) {\n x <- substr(x, 1, width - 3)\n x <- paste0(x, \"...\")\n }\n encodeString(x, ...)\n }\n\n if (value) {\n if (is.numeric(x) && is.infinite(x)) {\n return(show_infinites(x))\n }\n\n if (is.numeric(x) || is.complex(x)) {\n number <- as.character(round(x, 2))\n what <- if (is.complex(x)) {\n \"the complex number\"\n } else {\n \"the number\"\n }\n return(paste(what, number))\n }\n\n return(switch(typeof(x),\n logical = if (x) \"`TRUE`\" else \"`FALSE`\",\n character = {\n what <- if (nzchar(x)) {\n \"the string\"\n } else {\n \"the empty string\"\n }\n paste(what, str_encode(x, quote = \"\\\"\"))\n },\n raw = paste(\"the raw value\", as.character(x)),\n .rlang_stop_unexpected_typeof(x)\n ))\n }\n\n return(switch(typeof(x),\n logical = \"a logical value\",\n integer = \"an integer\",\n double = if (is.infinite(x)) show_infinites(x) else \"a number\",\n complex = \"a complex number\",\n character = if (nzchar(x)) \"a string\" else \"\\\"\\\"\",\n raw = \"a raw value\",\n .rlang_stop_unexpected_typeof(x)\n ))\n }\n\n if (length(x) == 0) {\n return(switch(typeof(x),\n logical = \"an empty logical vector\",\n integer = \"an empty integer vector\",\n double = \"an empty numeric vector\",\n complex = \"an empty complex vector\",\n character = \"an empty character vector\",\n raw = \"an empty raw vector\",\n list = \"an empty list\",\n .rlang_stop_unexpected_typeof(x)\n ))\n }\n }\n\n vec_type_friendly(x, length = length)\n}\n\n#' @importFrom rlang is_vector abort\nvec_type_friendly <- function(x, length = FALSE) {\n if (!is_vector(x)) {\n abort(\"`x` must be a vector.\")\n }\n type <- typeof(x)\n n_dim <- length(dim(x))\n\n add_length <- function(type) {\n if (length && !n_dim) {\n paste0(type, sprintf(\" of length %s\", length(x)))\n } else {\n type\n }\n }\n\n if (type == \"list\") {\n if (n_dim < 2) {\n return(add_length(\"a list\"))\n } else if (is.data.frame(x)) {\n return(\"a data frame\")\n } else if (n_dim == 2) {\n return(\"a list matrix\")\n } else {\n return(\"a list array\")\n }\n }\n\n type <- switch(type,\n logical = \"a logical %s\",\n integer = \"an integer %s\",\n numeric = ,\n double = \"a double %s\",\n complex = \"a complex %s\",\n character = \"a character %s\",\n raw = \"a raw %s\",\n type = paste0(\"a \", type, \" %s\")\n )\n\n if (n_dim < 2) {\n kind <- \"vector\"\n } else if (n_dim == 2) {\n kind <- \"matrix\"\n } else {\n kind <- \"array\"\n }\n out <- sprintf(type, kind)\n\n if (n_dim >= 2) {\n out\n } else {\n add_length(out)\n }\n}\n\n.rlang_as_friendly_type <- function(type) {\n switch(type,\n list = \"a list\",\n NULL = \"`NULL`\",\n environment = \"an environment\",\n externalptr = \"a pointer\",\n weakref = \"a weak reference\",\n S4 = \"an S4 object\",\n name = ,\n symbol = \"a symbol\",\n language = \"a call\",\n pairlist = \"a pairlist node\",\n expression = \"an expression vector\",\n char = \"an internal string\",\n promise = \"an internal promise\",\n ... = \"an internal dots object\",\n any = \"an internal `any` object\",\n bytecode = \"an internal bytecode object\",\n primitive = ,\n builtin = ,\n special = \"a primitive function\",\n closure = \"a function\",\n type\n )\n}\n\n#' @importFrom rlang abort caller_env\n.rlang_stop_unexpected_typeof <- function(x, call = caller_env()) {\n abort(sprintf(\"Unexpected type <%s>.\", typeof(x)), call = call)\n}\n\n#' Return OO type\n#' @param x Any R object.\n#' @return One of `\"bare\"` (for non-OO objects), `\"S3\"`, `\"S4\"`,\n#' `\"R6\"`, or `\"S7\"`.\n#' @noRd\nobj_type_oo <- function(x) {\n if (!is.object(x)) {\n return(\"bare\")\n }\n\n class <- inherits(x, c(\"R6\", \"S7_object\"), which = TRUE)\n\n if (class[[1]]) {\n \"R6\"\n } else if (class[[2]]) {\n \"S7\"\n } else if (isS4(x)) {\n \"S4\"\n } else {\n \"S3\"\n }\n}\n\n.standalone_oxford_comma <- function(x, sep = \", \", final = \"and\") {\n n <- length(x)\n\n if (n < 2L) return(x) # styler: off\n\n head <- x[seq_len(n - 1L)]\n last <- x[n]\n\n head <- paste(head, collapse = sep)\n\n # Write a or b. But a, b, or c.\n if (n > 2L) {\n paste0(head, sep, final, \" \", last)\n } else {\n paste0(head, \" \", final, \" \", last)\n }\n}\n\n# nocov end\n"], ["/ggalign/R/fortify-data-frame-dendrogram.R", "#' @inherit fortify_data_frame.default title description\n#'\n#' @param data A [`hclust`][stats::hclust] or a\n#' [`dendrogram`][stats::as.dendrogram] object.\n#' @param center A boolean value. if `TRUE`, nodes are plotted centered with\n#' respect to all leaves/tips in the branch. Otherwise (default), plot them in\n#' the middle of the direct child nodes.\n#' @param type A string indicates the plot type, `\"rectangle\"` or `\"triangle\"`.\n#' @param leaf_pos The x-coordinates of the leaf node. Must be the same length\n#' of the number of observations in `tree`.\n#' @param leaf_braches Branches of the leaf node. Must be the same length of the\n#' number of observations in `tree`. Usually come from [cutree][stats::cutree].\n#' @param reorder_branches A single boolean value, indicates whether reorder the\n#' provided `leaf_braches` based on the actual index.\n#' @param branch_gap A single numeric value indicates the gap between different\n#' branches.\n#' @param root A length one string or numeric indicates the root branch.\n#' @param priority A string of \"left\" or \"right\". if we draw from `right` to\n#' `left`, the left will override the right, so we take the `\"left\"` as the\n#' priority. If we draw from `left` to `right`, the right will override the\n#' left, so we take the `\"right\"` as priority. This is used by\n#' [`align_dendro()`] to provide support of facet operation in ggplot2.\n#' @param double A single logical value indicating whether horizontal lines\n#' should be doubled when segments span multiple branches. If `TRUE`, the\n#' horizontal lines will be repeated for each branch that the segment spans. If\n#' `FALSE`, only one horizontal line will be drawn. This is used by\n#' [`align_dendro()`] to provide support of facet operation in ggplot2.\n#' @inheritParams fortify_data_frame\n#' @return A `data frame` with the node coordinates:\n#' - `.panel`: Similar with `panel` column, but always give the correct\n#' branch for usage of the ggplot facet.\n#' - `.index`: the original index in the tree for the the node\n#' - `label`: node label text\n#' - `x` and `y`: x-axis and y-axis coordinates for the node\n#' - `branch`: which branch the node is. You can use this column to color\n#' different groups.\n#' - `panel`: which panel the node is, if we split the plot into panel\n#' using [facet_grid][ggplot2::facet_grid], this column will show\n#' which panel the node is from. Note: some nodes may\n#' fall outside panel (between two panels), so there are possible\n#' `NA` values in this column.\n#' - `leaf`: A logical value indicates whether the node is a leaf.\n#' @section ggalign attributes:\n#' `edge`: A `data frame` for edge coordinates:\n#' - `.panel`: Similar with `panel` column, but always give the correct\n#' branch for usage of the ggplot facet.\n#' - `x` and `y`: x-axis and y-axis coordinates for the start node of the edge.\n#' - `xend` and `yend`: the x-axis and y-axis coordinates of the terminal node\n#' for edge.\n#' - `branch`: which branch the edge is. You can use this column to color\n#' different groups.\n#' - `panel1` and `panel2`: The panel1 and panel2 columns have the same\n#' functionality as `panel`, but they are specifically for the `edge` data\n#' and correspond to both nodes of each edge.\n#' @examples\n#' fortify_data_frame(hclust(dist(USArrests), \"ave\"))\n#' @importFrom grid is.unit\n#' @importFrom stats order.dendrogram\n#' @importFrom rlang arg_match0\n#' @family fortify_data_frame\n#' @export\nfortify_data_frame.dendrogram <- function(data, ...,\n priority = \"right\",\n center = FALSE,\n type = \"rectangle\",\n leaf_pos = NULL,\n leaf_braches = NULL,\n reorder_branches = TRUE,\n branch_gap = NULL,\n root = NULL,\n double = TRUE,\n data_arg = NULL, call = NULL) {\n call <- call %||% current_call()\n data_arg <- data_arg %||% \"data\"\n rlang::check_dots_empty(call = call)\n assert_bool(center, call = call)\n assert_bool(reorder_branches, call = call)\n type <- arg_match0(type, c(\"rectangle\", \"triangle\"), error_call = call)\n priority <- arg_match0(priority, c(\"left\", \"right\"), error_call = call)\n N <- stats::nobs(data)\n rectangle <- type == \"rectangle\"\n if (is.null(leaf_pos)) {\n leaf_pos <- seq_len(N)\n } else if (length(leaf_pos) != N) {\n cli_abort(\n \"{.arg leaf_pos} must be of the same length of {.arg tree}\",\n call = call\n )\n }\n\n # if no branches provided, all branch will be regarded as the `root`\n if (is.null(leaf_braches)) {\n root <- root %||% \"root\"\n } else if (anyNA(leaf_braches)) {\n cli_abort(\"`NA` is not allowed in {.arg leaf_braches}\",\n call = call\n )\n } else if (length(leaf_braches) != N) {\n cli_abort(\n \"{.arg leaf_braches} must be of the same length of {.arg tree}\",\n call = call\n )\n } else if (is.character(leaf_braches)) {\n root <- root %||% \"root\"\n } else if (is.factor(leaf_braches)) {\n leaf_braches <- as.character(leaf_braches)\n root <- root %||% \"root\"\n } else if (is.numeric(leaf_braches)) {\n root <- root %||% (min(leaf_braches) - 1L)\n } else {\n cli_abort(\"{.arg leaf_braches} must be a character or numeric\",\n call = call\n )\n }\n\n if (!is.null(leaf_braches) && reorder_branches) {\n leaf_braches <- .subset(leaf_braches, order.dendrogram(data))\n }\n\n # check `branch_gap`\n if (is.numeric(branch_gap)) {\n if (!is_scalar(branch_gap)) {\n cli_abort(\"{.arg branch_gap} must be of length 1\",\n call = call\n )\n }\n } else if (is.null(branch_gap)) {\n branch_gap <- 0\n } else {\n cli_abort(\"{.arg branch_gap} must be numeric value.\",\n call = call\n )\n }\n\n # the root value shouldn't be the same of leaf branches.\n if (!is_scalar(root)) {\n cli_abort(\"{.arg root} must be of length 1\", call = call)\n } else if (anyNA(root)) {\n cli_abort(\"{.arg root} cannot be `NA`\", call = call)\n } else if (any(root == leaf_braches)) {\n cli_abort(\n \"{.arg root} cannot contain value in {.arg leaf_braches}\",\n call = call\n )\n }\n\n # initialize values\n i <- 0L # leaf index\n branch_levels <- NULL\n last_branch <- root\n total_gap <- 0\n dendrogram_data <- function(dend, from_root = TRUE) {\n if (stats::is.leaf(dend)) { # base version\n index <- as.integer(dend) # the column index of the original data\n y <- attr(dend, \"height\") %||% 0\n label <- attr(dend, \"label\") %||% NA\n i <<- i + 1L\n if (is.null(leaf_braches)) {\n branch <- root\n } else {\n branch <- .subset(leaf_braches, i)\n }\n\n x <- .subset(leaf_pos, i) + total_gap\n # for every new branch, we saved the branch for later use, in order\n # to order the branch levels, and we add a gap between two branch\n if (branch != last_branch) {\n branch_levels <<- c(branch_levels, branch)\n x <- x + branch_gap\n total_gap <<- total_gap + branch_gap\n }\n last_branch <<- branch\n\n node <- data_frame0(\n index = index, label = label,\n x = x, y = y, branch = branch,\n leaf = TRUE, panel = branch,\n ggpanel = branch\n )\n list(\n # current node\n node = node, edge = NULL,\n # current node information\n x = x, y = y,\n branch = branch,\n panel = branch,\n ggpanel = branch\n )\n } else if (inherits(dend, \"dendrogram\")) { # recursive version\n # the parent height -------------------------------------\n y <- attr(dend, \"height\")\n\n # for the children nodes ---------------------------------\n data <- list_transpose(\n lapply(dend, dendrogram_data, from_root = FALSE)\n )\n\n # node should be the direct children\n node <- vec_rbind(!!!.subset2(data, \"node\"))\n edge <- vec_rbind(!!!.subset2(data, \"edge\"))\n\n # all coordinate for direct children nodes -------------\n # following should be length 2\n direct_leaves_x <- unlist(\n .subset2(data, \"x\"),\n recursive = FALSE, use.names = FALSE\n )\n direct_leaves_y <- unlist(\n .subset2(data, \"y\"),\n recursive = FALSE, use.names = FALSE\n )\n direct_leaves_branch <- unlist(\n .subset2(data, \"branch\"),\n recursive = FALSE, use.names = FALSE\n )\n direct_leaves_panel <- unlist(\n .subset2(data, \"panel\"),\n recursive = FALSE, use.names = FALSE\n )\n direct_leaves_ggpanel <- unlist(\n .subset2(data, \"ggpanel\"),\n recursive = FALSE, use.names = FALSE\n )\n\n # prepare node data ------------------------------------\n\n # all x coordinate for children nodes --------------------\n # used if center is `TRUE`, we'll calculate the center position\n # among all children nodes\n leaves <- vec_slice(node, .subset2(node, \"leaf\")) # all leaves\n\n # we assign the `panel` for current branch node\n ranges <- split(\n .subset2(leaves, \"x\"),\n .subset2(leaves, \"panel\")\n )\n ranges <- ranges[\n order(vapply(ranges, min, numeric(1L), USE.NAMES = FALSE))\n ]\n full_panel <- names(ranges)\n\n # x coordinate for current branch: the midpoint\n if (center) {\n x <- sum(range(.subset2(leaves, \"x\"))) / 2L\n } else {\n x <- sum(direct_leaves_x) / 2L\n }\n if (is.null(leaf_braches)) { # no branches\n ggpanel <- panel <- branch <- root\n } else {\n # we assign the branch for current branch node\n branch <- unique(direct_leaves_branch)\n # if two children leaves are different, this branch should be\n # `root`, this is often used to color the segments\n if (length(branch) > 1L) branch <- root\n\n # we assign the `panel` for current branch node\n panel <- NA\n for (i in seq_along(ranges)) {\n if (x < min(.subset2(ranges, i))) {\n panel <- NA\n break\n } else if (x <= max(.subset2(ranges, i))) {\n panel <- .subset2(full_panel, i)\n break\n }\n }\n # if the node is between two panels, no panel\n # we choose the priority\n if (is.na(ggpanel <- panel)) {\n # it's not possible for an branch node live outside the\n # all panels - the left or right most. So `i` won't be 1 or\n # length(ranges). we don't need to check the argument\n ggpanel <- switch(priority,\n left = .subset(full_panel, i - 1L),\n right = .subset(full_panel, i)\n )\n }\n }\n\n # there is no node data in dendrogram root\n if (!from_root) {\n node <- vec_rbind(node, data_frame0(\n index = NA, label = NA,\n x = x, y = y, branch = branch, leaf = FALSE,\n panel = panel, ggpanel = ggpanel\n ))\n }\n\n # if it's the `rectangle`\n if (rectangle) {\n # 2 vertical lines\n vertical_lines <- data_frame0(\n x = direct_leaves_x,\n xend = direct_leaves_x,\n y = direct_leaves_y,\n yend = rep_len(y, 2L),\n branch = direct_leaves_branch,\n panel1 = direct_leaves_panel,\n panel2 = direct_leaves_panel,\n ggpanel = direct_leaves_ggpanel\n )\n # 2 horizontal lines\n # if the horizontal lines spanned multiple panels\n # we double the left line and the right line\n added_edge <- vec_rbind(\n vertical_lines,\n # left horizontal line\n make_horizontal(\n c(direct_leaves_x[1L], x),\n panels = c(direct_leaves_panel[1L], panel),\n ggpanels = c(direct_leaves_ggpanel[1L], ggpanel),\n y = y,\n branch = direct_leaves_branch[1L],\n ranges = ranges,\n full_panel = full_panel,\n double = double\n ),\n # right horizontal line\n make_horizontal(\n c(x, direct_leaves_x[2L]),\n panels = c(panel, direct_leaves_panel[2L]),\n ggpanels = c(ggpanel, direct_leaves_ggpanel[2L]),\n y = y,\n branch = direct_leaves_branch[2L],\n ranges = ranges,\n full_panel = full_panel,\n double = double\n )\n )\n } else {\n added_edge <- data_frame0(\n x = rep_len(x, 2L),\n xend = direct_leaves_x,\n y = rep_len(y, 2L),\n yend = direct_leaves_y,\n branch = direct_leaves_branch,\n panel1 = rep_len(panel, 2L),\n panel2 = direct_leaves_panel,\n ggpanel = rep_len(ggpanel, 2L)\n )\n }\n if (is.null(edge)) {\n edge <- added_edge\n } else {\n edge <- vec_rbind(edge, added_edge)\n }\n list(\n node = node, edge = edge,\n x = x, y = y, branch = branch,\n panel = panel, ggpanel = ggpanel\n )\n } else {\n cli_abort(\"Invalid {.cls dendrogram} provided in {.arg {data_arg}}\",\n call = call\n )\n }\n }\n ans <- dendrogram_data(data)\n node <- .subset2(ans, \"node\")\n edge <- .subset2(ans, \"edge\")\n\n # set factor levels for branch and panel ---------------\n panel_levels <- branch_levels\n branch_levels <- c(branch_levels, root)\n node$panel <- factor(.subset2(node, \"panel\"), panel_levels)\n node$branch <- factor(.subset2(node, \"branch\"), branch_levels)\n node$ggpanel <- factor(.subset2(node, \"ggpanel\"), panel_levels)\n if (!is.null(edge)) {\n edge$panel1 <- factor(.subset2(edge, \"panel1\"), panel_levels)\n edge$panel2 <- factor(.subset2(edge, \"panel2\"), panel_levels)\n edge$branch <- factor(.subset2(edge, \"branch\"), branch_levels)\n edge$ggpanel <- factor(.subset2(edge, \"ggpanel\"), panel_levels)\n }\n node <- rename(node, c(ggpanel = \".panel\", index = \".index\"))\n edge <- rename(edge, c(ggpanel = \".panel\"))\n ggalign_data_set(node, edge = edge)\n}\n\n#' @param ... Additional arguments passed to `dendrogram` method.\n#' @export\n#' @rdname fortify_data_frame.dendrogram\nfortify_data_frame.hclust <- function(data, ...) {\n fortify_data_frame.dendrogram(stats::as.dendrogram(data), ...)\n}\n\n#' @param ggpanels Won't be `NA`\n#' @noRd\nmake_horizontal <- function(x, panels, ggpanels, y, branch,\n ranges, full_panel = names(ranges),\n double = TRUE) {\n if (!isTRUE(double) || identical(ggpanels[1L], ggpanels[2L])) {\n # in the same panel\n data_frame0(\n x = x[1L],\n xend = x[2L],\n y = y,\n yend = y,\n branch = branch,\n panel1 = panels[1L],\n panel2 = panels[2L],\n ggpanel = ggpanels[1L]\n )\n } else {\n index <- match(ggpanels, full_panel)\n ending <- index[2L] # right index\n panel0 <- panels[1L]\n ggpanel0 <- ggpanels[1L]\n point0 <- x[1L] # the left point coordinate x\n out <- vector(\"list\", diff(index))\n right_index <- (index[1L] + 1L):ending\n for (i in seq_along(right_index)) {\n i1 <- .subset(right_index, i) # right index\n if (i1 == ending) {\n point1 <- x[2L]\n panel1 <- panels[2L]\n ggpanel1 <- ggpanels[2L]\n } else {\n point1 <- mean(range(.subset2(ranges, i1)))\n ggpanel1 <- panel1 <- .subset(full_panel, i1)\n }\n out[[i]] <- data_frame0(\n x = c(point0, point1),\n xend = c(point1, point0),\n y = y,\n yend = y,\n branch = branch,\n panel1 = c(panel0, panel1),\n panel2 = c(panel1, panel0),\n ggpanel = c(ggpanel0, ggpanel1)\n )\n point0 <- point1\n panel0 <- panel1\n ggpanel0 <- ggpanel1\n }\n vec_rbind(!!!out)\n }\n}\n"], ["/ggalign/R/craft-align-order2.R", "#' Reorders layout observations based on specific statistics.\n#'\n#' @details\n#' `r lifecycle::badge('experimental')`\n#'\n#' The `align_order2()` function differs from `align_order()` in that the\n#' `weights` argument in `align_order()` must return atomic weights for each\n#' observation. In contrast, the `stat` argument in `align_order2()` can\n#' return more complex structures, such as [hclust][stats::hclust] or\n#' [dendrogram][stats::as.dendrogram], among others.\n#'\n#' Typically, you can achieve the functionality of `align_order2()` using\n#' `align_order()` by manually extracting the ordering information from\n#' the statistic.\n#'\n#' @param stat A statistical function which accepts a data and returns the\n#' statistic, which we'll call [`order2()`] to extract the ordering information.\n#' @param ... <[dyn-dots][rlang::dyn-dots]> Additional arguments passed to\n#' function provided in `stat` argument.\n#' @param data A `matrix`, `data frame`, or atomic vector used as the input for\n#' the `stat` function. Alternatively, you can specify a `function` (including\n#' purrr-like lambda syntax) that will be applied to the layout matrix,\n#' transforming it as necessary for statistic calculations. By default, it will\n#' inherit from the layout matrix.\n#' @inheritParams align_order\n#' @inheritSection align Discrete Axis Alignment\n#' @examples\n#' ggheatmap(matrix(rnorm(81), nrow = 9)) +\n#' anno_left() +\n#' align_order2(hclust2)\n#' @seealso [order2()]\n#' @importFrom ggplot2 waiver\n#' @importFrom rlang list2\n#' @export\nalign_order2 <- function(stat, ..., reverse = FALSE,\n strict = TRUE, data = NULL,\n active = NULL) {\n stat <- rlang::as_function(stat)\n assert_bool(strict)\n assert_bool(reverse)\n assert_active(active)\n active <- update_active(active, new_active(use = FALSE))\n align(\n align = AlignOrder2,\n stat = stat,\n params = list2(...),\n reverse = reverse,\n strict = strict,\n active = active,\n data = data\n )\n}\n\n#' @importFrom ggplot2 ggproto\n#' @importFrom rlang inject\nAlignOrder2 <- ggproto(\"AlignOrder2\", CraftAlign,\n interact_layout = function(self, layout) {\n layout <- ggproto_parent(CraftAlign, self)$interact_layout(layout)\n layout_data <- layout@data\n if (is.null(input_data <- self$input_data) ||\n is.waive(input_data)) { # inherit from the layout\n if (is.null(data <- layout_data)) {\n cli_abort(c(\n sprintf(\n \"you must provide {.arg data} in %s\",\n object_name(self)\n ),\n i = sprintf(\"no data was found in %s\", self$layout_name)\n ))\n }\n } else if (is.function(input_data)) {\n if (is.null(layout_data)) {\n cli_abort(c(\n sprintf(\n \"{.arg data} in %s cannot be a function\",\n object_name(self)\n ),\n i = sprintf(\"no data was found in %s\", self$layout_name)\n ))\n }\n data <- input_data(layout_data)\n } else {\n data <- input_data\n }\n\n design <- layout@design\n layout_nobs <- .subset2(design, \"nobs\")\n\n # we always regard rows as the observations\n if (is.null(layout_nobs)) {\n layout_nobs <- vec_size(data)\n if (layout_nobs == 0L) {\n cli_abort(\"{.arg data} cannot be empty\", call = self$call)\n }\n design[\"nobs\"] <- list(layout_nobs)\n layout@design <- design\n } else if (vec_size(data) != layout_nobs) {\n cli_abort(sprintf(\n \"%s (nobs: %d) is not compatible with the %s (nobs: %d)\",\n object_name, vec_size(data), layout_name, layout_nobs\n ))\n }\n\n # save the labels\n self$labels <- vec_names(data) %||% vec_names(layout_data)\n self$data <- ggalign_data_restore(data, layout_data)\n layout\n },\n compute = function(self, panel, index) {\n inject(self$stat(self$data, !!!self$params))\n },\n align = function(self, panel, index) {\n index <- vec_cast(\n order2(self$statistics), integer(),\n x_arg = \"stat\", call = self$call\n )\n assert_mismatch_nobs(\n self, vec_size(self$data), vec_size(index),\n arg = \"stat\"\n )\n if (self$reverse) index <- rev(index)\n assert_reorder(self, panel, index, self$strict)\n list(panel, index)\n },\n summary_align = function(self) c(TRUE, FALSE)\n)\n\n#' Ordering Permutation\n#'\n#' `order2` returns a permutation which rearranges its first argument into\n#' ascending order.\n#' @param x Any objects can be extracting ordering.\n#' @return An integer vector unless any of the inputs has `2^31` or more\n#' elements, when it is a double vector.\n#' @examples\n#' order2(hclust2(matrix(rnorm(100L), nrow = 10L)))\n#' @export\norder2 <- function(x) UseMethod(\"order2\")\n\n#' @export\n#' @rdname order2\norder2.hclust <- function(x) x$order\n\n#' @importFrom stats order.dendrogram\n#' @export\n#' @rdname order2\norder2.dendrogram <- function(x) order.dendrogram(x)\n\n#' @export\n#' @rdname order2\norder2.ser_permutation_vector <- function(x) {\n rlang::check_installed(\n \"seriation\", \"to extract order from `ser_permutation_vector`\"\n )\n getExportedValue(\"seriation\", \"get_order\")(x)\n}\n\n#' @export\n#' @rdname order2\norder2.ser_permutation <- function(x) {\n rlang::check_installed(\n \"seriation\", \"to extract order from `ser_permutation`\"\n )\n getExportedValue(\"seriation\", \"get_order\")(x)\n}\n\n#' @export\n#' @rdname order2\norder2.phylo <- function(x) {\n second <- x$edge[, 2L, drop = TRUE]\n second[second <= length(x$tip.label)]\n}\n"], ["/ggalign/R/ggfree.R", "#' Add ggplot to layout without alignment\n#'\n#' @description\n#' `r lifecycle::badge('experimental')`\n#'\n#' The `ggfree()` function allows you to incorporate a ggplot object into your\n#' layout. Unlike `ggalign()`, which aligns every axis value precisely,\n#' `ggfree()` focuses on integrating plots into the layout without enforcing\n#' strict axis alignment.\n#'\n#' @inheritParams ggalign\n#'\n#' @section ggplot2 specification:\n#' `ggalign` initializes a ggplot object. The underlying data is created using\n#' [`fortify_data_frame()`]. Please refer to this method for more details.\n#'\n#' When used in `quad_layout()`/`ggheatmap()`, if the data is inherited from the\n#' `quad_layout()` and the other direction aligns discrete variables, following\n#' columns will be added:\n#'\n#' - `.extra_panel`: Provides the panel information for the column (left or\n#' right annotation) or row (top or bottom annotation).\n#' - `.extra_index`: The index information for the column (left or right\n#' annotation) or row (top or bottom annotation).\n#'\n#' @examples\n#' ggheatmap(matrix(rnorm(56), nrow = 7)) +\n#' anno_top() +\n#' align_dendro() +\n#' ggfree(mtcars, aes(wt, mpg)) +\n#' geom_point()\n#' @export\nggfree <- function(data = waiver(), ..., size = NULL, active = NULL) {\n UseMethod(\"ggfree\", data)\n}\n\n#' @inheritParams ggplot2::ggplot\n#' @importFrom ggplot2 ggplot\n#' @export\n#' @rdname ggfree\nggfree.default <- function(data = waiver(), mapping = aes(), ...,\n size = NULL, active = NULL) {\n data <- fortify_data_frame(data = data, ...)\n new_free_gg(\n plot = ggplot(data = NULL, mapping = mapping),\n data = data,\n size = size,\n active = active\n )\n}\n\n#' @export\nggfree.uneval <- function(data = waiver(), ...) {\n cli_abort(c(\n \"{.arg data} cannot be {.obj_type_friendly {data}}\",\n \"i\" = \"Have you misspelled the {.arg data} argument in {.fn ggalign}\"\n ))\n}\n\n#' @export\nggfree.ggplot <- function(data = waiver(), ..., size = NULL, active = NULL) {\n rlang::check_dots_empty()\n plot <- data\n # In ggplot2, `waiver()` was regard to no data\n data <- plot$data %|w|% NULL\n plot <- gguse_data(plot, waiver())\n new_free_gg(plot, data, size = size, active = active)\n}\n\nnew_free_gg <- function(plot, data, size, active,\n call = caller_call()) {\n assert_active(active, allow_null = TRUE, call = call)\n active <- update_active(active, new_active(use = TRUE))\n new_craftbox(\n FreeGg,\n # new field for FreeGg\n input_data = data,\n # slots for the plot\n plot = plot,\n size = size,\n active = active,\n schemes = default_schemes(data),\n call = call\n )\n}\n\n#' @importFrom ggplot2 ggproto\nFreeGg <- ggproto(\"FreeGg\", Craftsman,\n free_facet = TRUE,\n free_limits = TRUE,\n interact_layout = function(self, layout) {\n layout_data <- layout@data\n if (is.waive(input_data <- self$input_data)) { # inherit from the layout\n data <- layout_data\n self$labels <- vec_names(layout_data)\n\n # for data inherit from the layout, and the design is for discrete\n # variable, we'll integrate the design into the plot data\n self$use_design <- is_stack_layout(layout)\n\n # if the layout data is from the quad-layout, we use the discrete\n # `design`\n self$use_extra_design <- is_stack_layout(layout) &&\n isTRUE(layout@heatmap$quad_matrix)\n } else if (is.function(input_data)) {\n if (is.null(layout_data)) {\n cli_abort(c(\n sprintf(\n \"{.arg data} in %s cannot be a function\",\n object_name(self)\n ),\n i = sprintf(\"no data was found in %s\", self$layout_name)\n ))\n }\n data <- input_data(layout_data)\n } else {\n data <- input_data\n }\n self$data <- ggalign_data_restore(\n fortify_data_frame(data, call = self$call), layout_data\n )\n layout\n },\n build_plot = function(self, plot, design, extra_design = NULL,\n previous_design = NULL) {\n if (is.function(data <- self$data)) {\n data <- NULL\n }\n if (is.null(data)) {\n return(gguse_data(plot, data))\n }\n if (isTRUE(self$use_extra_design) &&\n is_discrete_design(extra_design) &&\n !is.null(.subset2(extra_design, \"nobs\"))) {\n extra_plot_data <- data_frame0(\n .extra_panel = .subset2(extra_design, \"panel\"),\n .extra_index = .subset2(extra_design, \"index\")\n )\n } else {\n extra_plot_data <- NULL\n }\n\n # if inherit from the parent layout\n if (isTRUE(self$use_design) &&\n is_discrete_design(design) &&\n !is.null(.subset2(design, \"nobs\"))) {\n plot_data <- data_frame0(\n .panel = .subset2(design, \"panel\"),\n .index = .subset2(design, \"index\"),\n .names = .subset(self$labels, .subset2(design, \"index\"))\n )\n if (!is.null(extra_plot_data)) {\n plot_data <- cross_join(plot_data, extra_plot_data)\n data <- full_join(data, plot_data,\n by.x = c(\".column_index\", \".row_index\"),\n by.y = c(\".extra_index\", \".index\")\n )\n } else {\n data <- full_join(data, plot_data,\n by.x = \".row_index\", by.y = \".index\"\n )\n }\n } else if (!is.null(extra_plot_data)) {\n data <- full_join(data, extra_plot_data,\n by.x = \".column_index\", by.y = \".extra_index\"\n )\n }\n gguse_data(plot, data)\n },\n summary = function(self, plot) {\n header <- ggproto_parent(Craftsman, self)$summary(plot)\n c(header, \" Add plot without alignment\")\n }\n)\n"], ["/ggalign/R/ggalign.R", "#' Add ggplot by Aligning discrete or continuous variable\n#'\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' `ggalign()` is similar to `ggplot` in that it initializes a `ggplot` data and\n#' `mapping`. `ggalign()` allowing you to provide data in various formats,\n#' including matrices, data frames, or simple vectors. By default, it will\n#' inherit from the layout. If a function, it will apply with the layout matrix.\n#' `ggalign()` focuses on integrating plots into a layout by aligning the axes.\n#'\n#' @param data The following options can be used:\n#' - `NULL`: No data is set.\n#' - [`waiver()`][ggplot2::waiver]: Inherits the data from the layout matrix.\n#' - A `function` (including purrr-like lambda syntax): Applied to the layout\n#' matrix to transform the data before use. To transform the final plot\n#' data, please use [`scheme_data()`].\n#' - A `matrix`, `data.frame`, or atomic vector.\n#' @inheritParams ggplot2::ggplot\n#' @param ... <[dyn-dots][rlang::dyn-dots]> Additional arguments passed to\n#' [`fortify_data_frame()`].\n#' @param size The relative size of the plot, can be specified as a\n#' [`unit()`][grid::unit]. Note that for [`circle_layout()`], all size values\n#' will be interpreted as relative sizes, as this layout type adjusts based on\n#' the available space in the circular arrangement.\n#' @param no_axes `r lifecycle::badge('experimental')` Logical; if `TRUE`,\n#' removes axes elements for the alignment axis using [`theme_no_axes()`]. By\n#' default, will use the option-\n#' `r code_quote(sprintf(\"%s.align_no_axes\", pkg_nm()))`.\n#' @param active A [`active()`] object that defines the context settings when\n#' added to a layout.\n#' @section ggplot2 specification:\n#' `ggalign` initializes a ggplot object. The underlying data is created using\n#' [`fortify_data_frame()`]. Please refer to it for more details.\n#'\n#' When aligning discrete variables, `ggalign()` always applies a default\n#' mapping for the axis of the data index in the layout. Specifically:\n#'\n#' - `aes(y = .data$.y)` is used for the horizontal `stack_layout()` (including\n#' left and right annotations).\n#' - `aes(x = .data$.x)` is used for the vertical `stack_layout()` (including\n#' top and bottom annotations) and `circle_layout()`.\n#'\n#' The following columns will be added to the data frame to align discrete\n#' variables:\n#'\n#' - `.panel`: The panel for the aligned axis. Refers to the `x-axis` for\n#' vertical `stack_layout()` (including top and bottom annotations), and the\n#' `y-axis` for horizontal `stack_layout()` (including left and right\n#' annotations).\n#'\n#' - `.names` ([`vec_names()`][vctrs::vec_names]) and `.index`\n#' ([`vec_size()`][vctrs::vec_size()]/[`NROW()`]): Character names (if\n#' available) and the integer index of the original data.\n#'\n#' - `.x`/`.y` and `.discrete_x`/`.discrete_y`: Integer indices for `x`/`y`\n#' coordinates, and a factor of the data labels (only applicable when names\n#' exist).\n#'\n#' It is recommended to use `.x`/`.y`, or `.discrete_x`/`.discrete_y` as the\n#' `x`/`y` mapping.\n#'\n#' If the data inherits from [`quad_layout()`]/[`ggheatmap()`], additional\n#' columns will be added:\n#'\n#' - `.extra_panel`: Provides the panel information for the column (left or\n#' right annotation) or row (top or bottom annotation).\n#' - `.extra_index`: The index information for the column (left or right\n#' annotation) or row (top or bottom annotation).\n#'\n#' @inheritSection align Discrete Axis Alignment\n#' @examples\n#' ggheatmap(matrix(rnorm(81), nrow = 9)) +\n#' anno_top() +\n#' ggalign() +\n#' geom_point(aes(y = value))\n#'\n#' ggheatmap(matrix(rnorm(81), nrow = 9)) +\n#' anno_top(size = 0.5) +\n#' align_dendro(k = 3L) +\n#' ggalign(data = NULL, size = 0.2) +\n#' geom_tile(aes(y = 1L, fill = .panel))\n#'\n#' @importFrom ggplot2 ggplot aes\n#' @importFrom rlang list2\n#' @export\nggalign <- function(data = waiver(), mapping = aes(), ..., size = NULL,\n no_axes = NULL, active = NULL) {\n if (inherits(data, \"uneval\")) {\n cli_abort(c(\n \"{.arg data} cannot be {.obj_type_friendly {data}}\",\n \"i\" = \"Have you misspelled the {.arg data} argument in {.fn ggalign}\"\n ))\n }\n no_axes <- no_axes %||%\n getOption(sprintf(\"%s.align_no_axes\", pkg_nm()), default = TRUE)\n assert_active(active)\n active <- update_active(active, new_active(use = TRUE))\n new_craftbox(\n AlignGg,\n input_data = allow_lambda(data),\n data_params = list2(...),\n plot = ggplot(mapping = mapping),\n size = size,\n schemes = default_schemes(data, th = theme_no_strip()),\n no_axes = no_axes, active = active\n )\n}\n\n#' @importFrom rlang inject\n#' @importFrom ggplot2 ggproto ggplot\nAlignGg <- ggproto(\"AlignGg\", Craftsman,\n interact_layout = function(self, layout) {\n layout_name <- self$layout_name\n input_data <- self$input_data\n object_name <- object_name(self)\n layout_data <- layout@data\n\n # inherit data from the layout\n if (is.function(input_data)) {\n if (is.null(layout_data)) {\n cli_abort(c(\n sprintf(\n \"{.arg data} in %s cannot be a function\",\n object_name\n ),\n i = sprintf(\"no data was found in %s\", layout_name)\n ))\n }\n data <- input_data(layout_data)\n } else if (is.waive(input_data)) {\n data <- layout_data %|w|% NULL\n # for data inherit from the layout, and the layout data is from\n # the quad-layout, we'll integrate the `extra_design`\n self$use_extra_design <- is_stack_layout(layout) &&\n isTRUE(layout@heatmap$quad_matrix)\n } else {\n data <- input_data\n }\n plot_data <- inject(\n fortify_data_frame(data, !!!self$data_params, call = self$call)\n )\n\n # for discrete design, # we need ensure the nobs is the same\n if (is_discrete_design(design <- layout@design)) {\n if (!is.null(data)) {\n if (is.null(layout_nobs <- design$nobs)) {\n layout_nobs <- NROW(data)\n if (layout_nobs == 0L) {\n cli_abort(\"{.arg data} cannot be empty\",\n call = self$call\n )\n }\n } else if (NROW(data) != layout_nobs) {\n cli_abort(sprintf(\n \"%s (nobs: %d) is not compatible with the %s (nobs: %d)\",\n object_name, NROW(data), layout_name, layout_nobs\n ))\n }\n design[\"nobs\"] <- list(layout_nobs)\n\n # we always add `.index` to align the observations\n # For matrix-like object\n if (!is.data.frame(data) &&\n vec_is(dim(data), integer(), size = 2L)) {\n plot_data$.index <- vec_rep(seq_len(NROW(data)), NCOL(data))\n } else {\n plot_data$.index <- seq_len(NROW(data))\n }\n layout@design <- design\n self$labels <- vec_names(data) %||% vec_names(layout_data)\n # always remove names, we'll add it in `build_plot()`\n plot_data$.names <- NULL\n } else {\n self$labels <- vec_names(layout_data)\n }\n self$add_mapping <- TRUE\n }\n self$data <- ggalign_data_restore(plot_data, layout_data)\n layout\n },\n setup_plot = function(self, plot) {\n direction <- self$direction\n ggadd_default(\n plot,\n mapping = if (isTRUE(self$add_mapping)) {\n switch_direction(\n direction,\n aes(y = .data$.y),\n aes(x = .data$.x)\n )\n },\n theme = if (is.null(self$data)) {\n # remove the title and text of axis vertically with the layout\n theme_no_axes(switch_direction(direction, \"x\", \"y\"))\n }\n ) + switch_direction(\n direction,\n ggplot2::labs(y = NULL),\n ggplot2::labs(x = NULL)\n )\n },\n\n #' @importFrom stats reorder\n build_plot = function(self, plot, design, extra_design = NULL,\n previous_design = NULL) {\n data <- self$data\n\n # if inherit from the parent layout\n if (isTRUE(self$use_extra_design) &&\n is_discrete_design(extra_design) &&\n !is.null(.subset2(extra_design, \"nobs\"))) {\n # if the data is inherit from the `quad_layout()`\n # the data must be a matrix\n extra_plot_data <- data_frame0(\n .extra_panel = .subset2(extra_design, \"panel\"),\n .extra_index = .subset2(extra_design, \"index\")\n )\n } else {\n extra_plot_data <- NULL\n }\n\n if (is_continuous_design(design)) {\n if (!is.null(data) && !is.null(extra_plot_data)) {\n data <- full_join(data, extra_plot_data,\n by.x = \".column_index\", by.y = \".extra_index\"\n )\n }\n return(gguse_data(plot, data))\n } else if (is.null(.subset2(design, \"nobs\"))) {\n cli_abort(c(\n sprintf(\n \"you must initialize %s before drawing %s\",\n self$layout_name, object_name(self)\n ),\n i = \"Or you should use {.fn ggfree}\"\n ), call = self$call)\n }\n direction <- self$direction\n axis <- to_coord_axis(direction)\n panel <- .subset2(design, \"panel\")\n index <- .subset2(design, \"index\")\n coord_name <- paste0(\".\", axis)\n plot_data <- data_frame0(\n .panel = panel,\n .index = index,\n # `data_frame0` will omit `NULL`\n .names = .subset(self$labels, index)\n )\n plot_data[[coord_name]] <- seq_along(index)\n if (!is.null(.subset2(plot_data, \".names\"))) {\n plot_data[[paste0(\".discrete_\", axis)]] <- reorder(\n .subset2(plot_data, \".names\"),\n .subset2(plot_data, coord_name),\n order = FALSE\n )\n }\n\n if (!is.null(extra_plot_data)) {\n plot_data <- cross_join(plot_data, extra_plot_data)\n if (!is.null(data)) {\n plot_data <- full_join(data, plot_data,\n by.x = c(\".column_index\", \".index\"),\n by.y = c(\".extra_index\", \".index\")\n )\n }\n } else if (!is.null(data)) {\n plot_data <- full_join(data, plot_data, by = \".index\")\n }\n gguse_data(plot, ggalign_data_restore(plot_data, data))\n },\n\n # let Craftsman to add schemes and theme acoordingly\n finish_plot = function(self, plot, schemes, theme) {\n direction <- self$direction\n # remove axis titles, text, ticks used for alignment\n if (isTRUE(self$no_axes)) {\n schemes$scheme_theme <- .subset2(schemes, \"scheme_theme\") +\n theme_no_axes(switch_direction(direction, \"y\", \"x\"))\n }\n plot <- plot_add_schemes(plot, schemes)\n if (is_horizontal(direction)) {\n theme <- theme(\n panel.spacing.y = calc_element(\"panel.spacing.y\", theme)\n )\n } else {\n theme <- theme(\n panel.spacing.x = calc_element(\"panel.spacing.x\", theme)\n )\n }\n plot <- plot + theme\n ggremove_margin(plot, direction) + theme_recycle()\n },\n summary = function(self, plot) {\n header <- ggproto_parent(Craftsman, self)$summary(plot)\n c(header, \" Add plot by Aligning discrete or continuous variable\")\n }\n)\n\n#' Create ggplot object with layout panel data\n#'\n#' @description\n#' `r lifecycle::badge(\"deprecated\")`\n#'\n#' This function was deprecated because we realised that it's a special case of\n#' the [`ggalign()`] function. Please use `ggalign(data = NULL)` instead.\n#' @export\n#' @keywords internal\nalign_panel <- function(...) {\n lifecycle::deprecate_stop(\"0.0.5\", \"align_panel()\", \"ggalign(data = NULL)\")\n}\n\n#' @export\n#' @rdname align_panel\nggpanel <- function(...) {\n lifecycle::deprecate_stop(\"0.0.5\", \"ggpanel()\", \"ggalign(data = NULL)\")\n}\n"], ["/ggalign/R/craft-align-.R", "#' Create a New `CraftBox` Object with `CraftAlign` craftsman\n#'\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' An `CraftAlign` object interacts with the `Layout` object to reorder or split\n#' observations and, in some cases, add plot components to the `Layout`.\n#'\n#' @param align An `CraftAlign` object.\n#' @param ... Additional fields passed to the `align` object.\n#' @param plot A ggplot object.\n#' @inheritParams ggalign\n#' @param schemes Options for `schemes`:\n#' - `NULL`: Used when `align` do not add a plot.\n#' - [`waiver()`][ggplot2::waiver]: Try to infer `schemes` based on `data`.\n#' @param call The `call` used to construct the `align` object, for\n#' reporting messages.\n#'\n#' @section Discrete Axis Alignment:\n#' It is important to note that we consider rows as observations, meaning\n#' `vec_size(data)`/`NROW(data)` must match the number of observations along the\n#' axis used for alignment (x-axis for a vertical stack layout, y-axis for a\n#' horizontal stack layout).\n#'\n#' @return A new `CraftBox` object.\n#' @examples\n#' align_dendro()\n#' @importFrom rlang caller_call current_call\n#' @importFrom ggplot2 ggproto\n#' @export\n#' @keywords internal\nalign <- function(align, data = NULL, ..., plot = NULL,\n size = NULL, schemes = NULL, no_axes = NULL,\n active = NULL, call = caller_call()) {\n if (override_call(call)) {\n call <- current_call()\n }\n\n # check arguments ---------------------------------------------\n data <- allow_lambda(data)\n no_axes <- no_axes %||%\n getOption(sprintf(\"%s.align_no_axes\", pkg_nm()), default = TRUE)\n schemes <- schemes %|w|% default_schemes(data)\n\n new_craftbox(\n craftsman = align,\n\n # additional field for `align` object\n no_axes = no_axes,\n ...,\n\n # Following fields will be initialzed when added into the layout\n # and will be saved and accessed across the plot rendering process\n direction = NULL,\n position = NULL,\n data = NULL, # Used to save the modified `input_data`\n statistics = NULL, # `$compute` method\n labels = NULL, # the original `vec_names()` of the `input_data`\n\n # the input data\n input_data = data,\n\n # object slots\n plot = plot,\n active = active,\n size = size,\n schemes = schemes,\n\n # call\n call = call\n )\n}\n\n#' @details\n#' Each of the `Align*` objects is just a [`ggproto()`][ggplot2::ggproto]\n#' object, descended from the top-level `CraftAlign`, and each implements\n#' various methods and fields.\n#'\n#' To create a new type of `Align*` object, you typically will want to\n#' override one or more of the following:\n#' - `setup_params`: Prepare parameter or check parameters used by this plot.\n#' - `setup_data`: Prepare data used by this plot.\n#' - `compute`: A method used to compute statistics.\n#' - `align`: A method used to group observations into panel or reorder\n#' observations.\n#' - `draw`: A method used to draw the plot. Must return a `ggplot` object.\n#' @importFrom ggplot2 ggproto\n#' @export\n#' @format NULL\n#' @usage NULL\n#' @rdname align\n#' @include craftbox-.R\nCraftAlign <- ggproto(\"CraftAlign\", Craftsman,\n interact_layout = function(self, layout) {\n # check plot is compatible with the layout\n if (is_layout_continuous(layout)) {\n layout_name <- self$layout_name\n # `CraftAlign` object is special for discrete variables\n cli_abort(c(\n sprintf(\"Cannot add %s to %s\", object_name(self), layout_name),\n i = sprintf(\"%s cannot align discrete variables\", layout_name)\n ))\n }\n layout\n },\n setup_design = function(self, design) {\n old_panel <- .subset2(design, \"panel\")\n old_index <- .subset2(design, \"index\")\n # prepare the data -------------------------------\n # compute statistics ---------------------------------\n self$statistics <- self$compute(panel = old_panel, index = old_index)\n\n # make the new layout -------------------------------\n panel_and_index <- self$align(panel = old_panel, index = old_index)\n\n # check panel\n layout_name <- self$layout_name\n nobs <- .subset2(design, \"nobs\")\n new_panel <- .subset2(panel_and_index, 1L)\n if (!is.null(new_panel)) {\n if (!is.atomic(new_panel)) {\n cli_abort(c(\n sprintf(\n \"invalid layout panels defined by %s\",\n object_name(self)\n ),\n i = \"layout panels must be an atomic vector\"\n ))\n } else if (anyNA(new_panel)) {\n cli_abort(sprintf(\n \"layout panels defined by %s contain `NA`\",\n object_name(self)\n ))\n } else if (is.null(nobs)) {\n # we have defined panel, but don't define the `nobs`\n cli_abort(sprintf(\n \"%s defined the panels but not define {.field nobs}\", object_name(self)\n ))\n } else if (length(new_panel) != nobs) {\n # we have defined panel, but don't define the `nobs`\n cli_abort(sprintf(\n \"layout panels defined by %s (nobs: %d) is not compatible with the nobs: %d\",\n object_name(self), length(new_panel), nobs\n ))\n } else if (!is.null(old_panel) && !(new_panel %nest% old_panel)) {\n cli_abort(sprintf(\n \"%s disrupt the previously established panel groups of %s\",\n object_name(self), layout_name\n ))\n }\n } else if (!is.null(old_panel)) {\n # push developer to reset the panel in the layout\n cli_abort(c(\n sprintf(\"invalid %s\", object_name(self)),\n i = sprintf(\n \"%s reset the {.field panel}, but don't change the {.field panel} of the layout\", object_name(self)\n )\n ))\n }\n panel <- new_panel\n if (!is.null(panel) && !is.factor(panel)) panel <- factor(panel)\n\n # check index\n new_index <- .subset2(panel_and_index, 2L)\n if (!is.null(new_index)) {\n if (!is.integer(new_index)) {\n cli_abort(c(\n sprintf(\n \"invalid layout ordering index defined by %s\", object_name(self)\n ),\n i = \"layout ordering index must be an integer\"\n ))\n } else if (anyNA(new_index)) {\n cli_abort(sprintf(\n \"layout ordering index defined by %s contain `NA`\",\n object_name(self)\n ))\n } else if (is.null(nobs)) {\n # we have defined panel, but don't define the `nobs`\n cli_abort(sprintf(\n \"%s defined the ordering index but not define nobs\", object_name(self)\n ))\n } else if (length(new_index) != nobs) {\n # we have defined index, but don't define the `nobs`\n cli_abort(sprintf(\n \"layout ordering index defined by %s (nobs: %d) is not compatible with the nobs (%d)\",\n object_name(self), length(new_index), nobs\n ))\n }\n } else if (!is.null(old_index)) {\n # push developer to reset the `index` in the layout\n cli_abort(c(\n sprintf(\"invalid %s\", object_name(self)),\n i = sprintf(\n \"%s reset the {.field index}, but don't change the {.field index} of the layout\",\n object_name(self)\n )\n ))\n }\n index <- new_index\n\n # we always make the index following the panel\n if (!is.null(panel) && !is.null(index)) {\n index <- reorder_index(panel, index)\n }\n\n # we always prevent from reordering twice.\n if (!is.null(old_index) && !all(old_index == index)) {\n cli_abort(sprintf(\n \"%s disrupt the previously established ordering index of %s\",\n object_name(self), layout_name\n ))\n }\n discrete_design(panel, index, nobs)\n },\n\n # Following fields should be defined for the new `CraftAlign` object.\n # argument name in these function doesn't matter.\n compute = function(self, panel, index) NULL,\n\n # Group heamap row/column and reorder, Must return a list of 2:\n # - the first one should be the groups for heatmap row/column, the factor\n # levels will determine the panel order, so it should always follow the\n # index if you don't want the panel levels break the index. See\n # `AlignDendro` for example.\n # - the second one should be the heatmap row/column order index, and will\n # determine the order in each grouped panel.\n #\n # See `$setup_design()` method for details\n # There will have following situations (the input is old index and old\n # panel):\n #\n # 1. old index is NULL and old panel is NULL, there is nothing wrong to\n # define any new index or panel\n # 2. old index is `NULL` and old panel is not `NULL`, in this way, new\n # index must follow the old panel.\n #\n # For new `CraftAlign` object, which can do clustering, we must\n # abort, if it can not do sub-clustering, if it can do sub-clustering, we\n # should know if we want to change the order between the groups (panel\n # levels).\n #\n # Please check `AlignGroup` object and `CraftAlign` object\n # For dendrogram, it can do sub-clustering within each group, it also\n # allows reordering between groups (it provide `reorder_group` argument),\n # so the new panel levels may be not the same with old panel\n #\n # For `CraftAlign` object reordering the heatmap rows/columns.\n # usually we provide a `strict` argument, to allow reorder heatmap within\n # group only. See `AlignOrder2`.\n #\n # 3. old index is not `NULL`, no matter whether old panel is `NULL` or not,\n # in this way, we should always ensure the new index won't change the old\n # index, this will be checked in `$setup_design()` method.\n align = function(self, panel, index) list(panel, index),\n\n # let Craftsman to add schemes and theme acoordingly\n finish_plot = function(self, plot, schemes, theme) {\n ggproto_parent(AlignGg, self)$finish_plot(plot, schemes, theme)\n },\n summary = function(self, plot) {\n header <- ggproto_parent(Craftsman, self)$summary(plot)\n oo <- self$summary_align()\n nms <- c(\"plot\", \"reorder\", \"split\")\n content <- c(\n if (is.null(plot)) \"no\" else \"yes\",\n if (isTRUE(oo[1L])) \"yes\" else \"no\",\n if (isTRUE(oo[2L])) \"yes\" else \"no\"\n )\n nms <- format(nms, justify = \"right\")\n content <- format(content, justify = \"left\")\n content <- paste0(\" \", nms, \": \", content)\n c(header, content)\n },\n\n # Summary the action of `Align`\n #\n # @return A logical vector of length 2, indicating:\n # - Whether the object reorders the observations.\n # - Whether the object splits the observations into groups.\n # @keywords internal\n summary_align = function(self) c(FALSE, FALSE)\n)\n"], ["/ggalign/R/fortify-matrix-maftools.R", "#' Build a Matrix for OncoPrint\n#'\n#' @description\n#' Convert `MAF` object to a matrix:\n#' - `fortify_matrix.MAF`: Extract genomic alterations for genes.\n#' - `fortify_matrix.MAF_pathways`: Extract genomic alterations for pathways.\n#' [`tune.MAF()`] helps convert `MAF` object to a `MAF_pathways` object.\n#'\n#' @inheritParams rlang::args_dots_empty\n#' @param data A [`MAF`][maftools::read.maf] object.\n#' @param genes An atomic character defines the genes to draw.\n#' @param n_top A single number indicates how many top genes to be drawn.\n#' @param remove_empty_genes A single boolean value indicats whether to drop\n#' genes without any genomic alterations.\n#' @param remove_empty_samples A single boolean value indicats whether to drop\n#' samples without any genomic alterations.\n#' @param collapse_vars A single boolean value indicating whether to collapse\n#' multiple alterations in the same sample and gene into a single value\n#' `\"Multi_Hit\"`. Alternatively, you can provide a single string indicates the\n#' collapsed values.\n#' @param use_syn A single boolean value indicates whether to include synonymous\n#' variants when Classifies SNPs into transitions and transversions.\n#' @param missing_genes A string, either `\"error\"` or `\"remove\"`, specifying the\n#' action for handling missing genes.\n#' @inheritParams fortify_matrix\n#' @section ggalign attributes:\n#' For `fortify_matrix.MAF`:\n#' - `gene_summary`: A data frame of gene summary informations. See\n#' `maftools::getGeneSummary()` for details.\n#' - `sample_summary`: A data frame of sample summary informations. See\n#' `maftools::getSampleSummary()` for details.\n#' - `sample_anno`: A data frame of sample clinical informations. See\n#' `maftools::getClinicalData()` for details.\n#' - `variant_weights`: A data frame of variant weights. Each gene in a sample\n#' is assigned a total weight of `1`. When multiple variants occur in the\n#' same gene-sample pair, the weight for each variant reflects its proportion\n#' of the total.\n#' - `n_genes`: Total number of genes.\n#' - `n_samples`: Total number of samples.\n#' - `titv`: A list of data frame with Transitions and Transversions\n#' summary. See `maftools::titv()` for details.\n#'\n#' The levels of `Variant_Classification` will be stored in [`ggalign_lvls()`].\n#' If they do not exist, alphabetical ordering will be used.\n#'\n#' @family fortify_matrix\n#' @importFrom utils getFromNamespace\n#' @importFrom rlang is_string\n#' @export\nfortify_matrix.MAF <- function(data, ..., genes = NULL, n_top = NULL,\n remove_empty_genes = TRUE,\n remove_empty_samples = TRUE,\n collapse_vars = TRUE, use_syn = TRUE,\n missing_genes = \"error\",\n data_arg = NULL, call = NULL) {\n call <- call %||% current_call()\n rlang::check_dots_empty(call = call)\n rlang::check_installed(\n \"maftools\", \"to make alterations matrix from `MAF` object\"\n )\n # prepare arguments\n missing_genes <- arg_match0(\n missing_genes, c(\"error\", \"remove\"),\n error_call = call\n )\n if (isTRUE(collapse_vars)) {\n collapse_vars <- \"Multi_Hit\"\n } else if (isFALSE(collapse_vars)) {\n collapse_vars <- NULL\n } else if (is_string(collapse_vars)) {\n if (collapse_vars == \"\") {\n cli_abort(\"{.arg collapse_vars} cannot be an empty string\",\n call = call\n )\n }\n } else {\n cli_abort(\n paste(\n \"{.arg collapse_vars} must be a single boolean value or a string,\",\n \"but you provide {.obj_type_friendly {collapse_vars}}\"\n ),\n call = call\n )\n }\n\n getSampleSummary <- getExportedValue(\"maftools\", \"getSampleSummary\")\n getGeneSummary <- getExportedValue(\"maftools\", \"getGeneSummary\")\n getClinicalData <- getExportedValue(\"maftools\", \"getClinicalData\")\n\n # if `maftools` is installed, `data.table` must have been installed\n # No need to check if `data.table` is installed\n dcast <- getExportedValue(\"data.table\", \"dcast\")\n setDT <- getExportedValue(\"data.table\", \"setDT\")\n setDF <- getExportedValue(\"data.table\", \"setDF\")\n\n sample_summary <- new_data_frame(getSampleSummary(data))\n gene_summary <- new_data_frame(getGeneSummary(data))\n sample_anno <- new_data_frame(getClinicalData(data))\n\n titv <- getExportedValue(\"maftools\", \"titv\")\n titv <- titv(data, useSyn = use_syn, plot = FALSE)\n titv <- lapply(titv, new_data_frame)\n\n # we transform the data into a normal data frame\n data <- new_data_frame(data@data)[\n c(\"Tumor_Sample_Barcode\", \"Hugo_Symbol\", \"Variant_Classification\")\n ]\n n_genes <- vec_unique_count(.subset2(data, \"Hugo_Symbol\"))\n n_samples <- vec_unique_count(.subset2(data, \"Tumor_Sample_Barcode\"))\n\n # filter by genes --------------------------------------\n if (!is.null(genes)) {\n # reorder the gene annotation based on the provided genes\n genes <- vec_cast(genes, character())\n if (vec_any_missing(genes)) {\n cli_abort(\n \"{.arg genes} cannot contain missing values\",\n call = call\n )\n }\n if (vec_duplicate_any(genes)) {\n cli_abort(\n \"{.arg genes} cannot contain duplicated values\",\n call = call\n )\n }\n if (identical(missing_genes, \"remove\")) {\n genes <- genes[genes %in% .subset2(gene_summary, \"Hugo_Symbol\")]\n }\n if (is_empty(genes)) {\n cli_abort(\n \"No {.arg genes} remain after removing missing genes\",\n call = call\n )\n }\n gene_summary <- vec_slice(\n gene_summary,\n vec_as_location(\n genes,\n n = vec_size(gene_summary),\n names = .subset2(gene_summary, \"Hugo_Symbol\"),\n missing = \"error\"\n )\n )\n }\n genes <- .subset2(gene_summary, \"Hugo_Symbol\")\n if (!is.null(n_top)) {\n n_top <- min(n_top, vec_size(genes))\n index <- vec_slice(\n order(gene_summary$AlteredSamples, decreasing = TRUE),\n seq_len(n_top)\n )\n index <- sort(index) # don't change the order, we do only subset\n genes <- vec_slice(genes, index)\n gene_summary <- vec_slice(gene_summary, index)\n }\n data <- vec_slice(data, .subset2(data, \"Hugo_Symbol\") %in% genes)\n\n # Group variants --------------------------------------\n indices <- vec_group_loc(data[c(\"Tumor_Sample_Barcode\", \"Hugo_Symbol\")])\n vars <- .subset2(data, \"Variant_Classification\")\n lvls <- levels(vars) %||% sort(vec_unique(vars))\n nlvls <- vec_size(lvls)\n var_list <- vec_chop(as.character(vars), indices = .subset2(indices, \"loc\"))\n\n # calcualte the variant weights -----------------------\n variant_weights <- lapply(var_list, function(var) {\n o <- numeric(nlvls)\n names(o) <- lvls\n counts <- vec_count(var)\n o[.subset2(counts, \"key\")] <- .subset2(counts, \"count\") /\n sum(.subset2(counts, \"count\"))\n o\n })\n variant_weights <- inject(rbind(!!!variant_weights))\n gene_indices <- vec_group_loc(\n .subset2(.subset2(indices, \"key\"), \"Hugo_Symbol\")\n )\n variant_weights <- lapply(\n vec_chop(variant_weights, indices = .subset2(gene_indices, \"loc\")),\n colSums\n )\n variant_weights <- vec_cbind(\n Hugo_Symbol = .subset2(gene_indices, \"key\"),\n vec_rbind(!!!variant_weights)\n )\n\n # collapse the vars ------------------------------------\n if (is.null(collapse_vars)) {\n vars <- vapply(var_list, function(var) {\n if (length(var) > 1L) {\n paste(var, collapse = \";\")\n } else {\n var\n }\n }, character(1L), USE.NAMES = FALSE)\n } else {\n vars <- vapply(var_list, function(var) {\n if (vec_unique_count(var) > 1L) {\n collapse_vars\n } else if (length(var) > 1L) {\n paste(var, collapse = \";\")\n } else {\n var\n }\n }, character(1L), USE.NAMES = FALSE)\n if (any(vars == collapse_vars)) lvls <- c(lvls, collapse_vars)\n }\n ans <- vec_cbind(\n .subset2(indices, \"key\"),\n new_data_frame(list(Variant_Classification = vars))\n )\n\n # restore all samples, this will introduce `NA` in `Hugo_Symbol`\n ans <- right_join(ans, data_frame0(\n Tumor_Sample_Barcode = vec_unique(sample_summary$Tumor_Sample_Barcode)\n ))\n setDT(ans)\n ans <- dcast(ans, Hugo_Symbol ~ Tumor_Sample_Barcode,\n value.var = \"Variant_Classification\"\n )\n setDF(ans)\n ans <- vec_slice(ans, !is.na(.subset2(ans, \"Hugo_Symbol\")))\n\n # convert data into a matrix\n if (remove_empty_genes) {\n # convert to a matrix\n ans <- as.matrix(column_to_rownames(ans, \"Hugo_Symbol\"))\n\n # reorder the rows based on the `genes` specified\n index <- match(genes, rownames(ans))\n ans <- vec_slice(ans, index[!is.na(index)])\n } else {\n # restore all genes\n ans <- right_join(ans, data_frame0(Hugo_Symbol = genes))\n\n # convert to a matrix\n ans <- as.matrix(column_to_rownames(ans, \"Hugo_Symbol\"))\n\n # reorder the rows based on the `genes` specified\n ans <- vec_slice(ans, genes)\n }\n\n # filter samples when necessary\n if (remove_empty_samples) {\n keep <- colSums(!is.na(ans)) > 0L\n ans <- ans[, keep, drop = FALSE]\n }\n\n # reorder the rows based on the gene ordering\n gene_summary <- vec_slice(\n gene_summary,\n vec_as_location(\n rownames(ans),\n n = vec_size(gene_summary),\n names = vec_cast(gene_summary$Hugo_Symbol, character())\n )\n )\n variant_weights <- vec_slice(\n variant_weights,\n vec_as_location(\n rownames(ans),\n n = vec_size(variant_weights),\n names = variant_weights$Hugo_Symbol\n )\n )\n\n # reorder columns based on the sample ordering\n sample_summary <- vec_slice(\n sample_summary,\n vec_as_location(\n colnames(ans),\n n = vec_size(sample_summary),\n names = vec_cast(sample_summary$Tumor_Sample_Barcode, character())\n )\n )\n sample_anno <- vec_slice(\n sample_anno,\n vec_as_location(\n colnames(ans),\n n = vec_size(sample_anno),\n names = sample_anno$Tumor_Sample_Barcode\n )\n )\n titv <- lapply(titv, function(data) {\n data <- left_join(\n data_frame0(Tumor_Sample_Barcode = colnames(ans)),\n data\n )\n vec_slice(data, vec_as_location(\n colnames(ans),\n n = vec_size(data),\n names = vec_cast(data$Tumor_Sample_Barcode, character())\n ))\n })\n ggalign_data_set(ans,\n sample_summary = sample_summary,\n gene_summary = gene_summary,\n sample_anno = sample_anno,\n variant_weights = variant_weights,\n n_samples = n_samples, n_genes = n_genes, titv = titv,\n .lvls = lvls\n )\n}\n\n#' Convert the shape of a MAF for fortify method\n#'\n#' @param data A [`MAF`][maftools::read.maf] object.\n#' @param shape Not used currently.\n#' @seealso [`fortify_matrix.MAF_pathways()`]\n#' @family tune\n#' @export\ntune.MAF <- function(data, shape = NULL) {\n if (!is.null(shape)) {\n cli_abort(\"{.arg shape} cannot be used currently for {.cls MAF} object\")\n }\n new_tune(data, class = \"MAF_pathways\")\n}\n\n#' @param pathdb A string of `r oxford_or(c(\"smgbp\", \"sigpw\"))`, or a named list\n#' of genes to define the pathways.\n#' @param remove_empty_pathways A single boolean value indicats whether to drop\n#' pathways without any genomic alterations.\n#' @section ggalign attributes:\n#' For `fortify_matrix.MAF_pathways`:\n#' - `gene_list`: the pathway contents.\n#' - `pathway_summary`: pathway summary informations. See\n#' `maftools::pathways()` for details.\n#' - `sample_summary`: sample summary informations. See\n#' `maftools::getSampleSummary()` for details.\n#' - `sample_anno`: sample clinical informations. See\n#' `maftools::getClinicalData()` for details.\n#' @export\n#' @rdname fortify_matrix.MAF\nfortify_matrix.MAF_pathways <- function(data, ..., pathdb = \"smgbp\",\n remove_empty_pathways = TRUE,\n remove_empty_samples = TRUE,\n data_arg = NULL,\n call = NULL) {\n call <- call %||% current_call()\n rlang::check_dots_empty(call = call)\n rlang::check_installed(\n \"maftools\", \"to make alterations matrix from `MAF` object\"\n )\n get_pw_summary <- getFromNamespace(\"get_pw_summary\", \"maftools\")\n maf <- tune_data(data)\n if (rlang::is_string(pathdb)) {\n pathdb <- arg_match0(pathdb, c(\"sigpw\", \"smgbp\"))\n pathway_summary <- get_pw_summary(maf, pathways = pathdb)\n } else if (is.data.frame(pathdb)) {\n cli_abort(\"{.arg pathdb} cannot be a data frame\", call = call)\n } else if (is.list(pathdb)) {\n if (!rlang::is_named(pathdb)) {\n cli_abort(sprintf(\n \"{.arg pathdb} must be a named list of a single string of %s\",\n oxford_or(c(\"sigpw\", \"smgbp\"))\n ), call = call)\n }\n pathdb <- data_frame0(\n Pathway = factor(\n vec_rep_each(names(pathdb), lengths(pathdb)),\n names(pathdb)\n ),\n Gene = unlist(pathdb, FALSE, FALSE)\n )\n pathdb <- vec_unique(pathdb)\n pathway_summary <- get_pw_summary(maf, pathways = pathdb)\n }\n getSampleSummary <- getExportedValue(\"maftools\", \"getSampleSummary\")\n getClinicalData <- getExportedValue(\"maftools\", \"getClinicalData\")\n sample_summary <- new_data_frame(getSampleSummary(maf))\n sample_anno <- new_data_frame(getClinicalData(maf))\n\n gene_list <- attr(pathway_summary, \"genes\") # a list of genes\n ans <- new_data_frame(maf@data)[\n c(\"Tumor_Sample_Barcode\", \"Hugo_Symbol\", \"Variant_Classification\")\n ]\n full_genes <- unlist(gene_list, FALSE, FALSE)\n ans$pathways <- vec_slice(\n vec_set_names(\n vec_rep_each(names(gene_list), lengths(gene_list)),\n full_genes\n ),\n if_else(ans$Hugo_Symbol %in% full_genes,\n ans$Hugo_Symbol, NA_character_\n )\n )\n ans$Alt <- if_else(is.na(.subset2(ans, \"pathways\")), NA_character_, \"Alt\")\n ans <- vec_unique(ans[c(\"Tumor_Sample_Barcode\", \"pathways\", \"Alt\")])\n\n # if `maftools` is installed, `data.table` must have been installed\n # No need to check if `data.table` is installed\n dcast <- getExportedValue(\"data.table\", \"dcast\")\n setDT <- getExportedValue(\"data.table\", \"setDT\")\n setDF <- getExportedValue(\"data.table\", \"setDF\")\n setDT(ans)\n ans <- dcast(ans, pathways ~ Tumor_Sample_Barcode,\n value.var = \"Alt\", fill = NA_character_\n )\n setDF(ans)\n ans <- vec_slice(ans, !is.na(.subset2(ans, \"pathways\")))\n\n # convert data into a matrix\n if (remove_empty_pathways) {\n # convert to a matrix\n ans <- as.matrix(column_to_rownames(ans, \"pathways\"))\n\n # reorder the rows based on the `pathways` specified\n index <- match(names(gene_list), rownames(ans))\n gene_list <- gene_list[!is.na(index)]\n ans <- vec_slice(ans, index[!is.na(index)])\n } else {\n # restore all pathways\n ans <- right_join(ans, data_frame0(pathways = names(gene_list)))\n\n # convert to a matrix\n ans <- as.matrix(column_to_rownames(ans, \"pathways\"))\n\n # reorder the rows based on the `pathways` specified\n ans <- vec_slice(ans, names(gene_list))\n }\n\n # filter samples when necessary\n if (remove_empty_samples) {\n keep <- colSums(!is.na(ans)) > 0L\n ans <- ans[, keep, drop = FALSE]\n }\n\n # reorder the rows based on the pathways ordering\n setDF(pathway_summary)\n pathway_summary <- vec_slice(\n pathway_summary,\n vec_as_location(\n rownames(ans),\n n = vec_size(pathway_summary),\n names = vec_cast(pathway_summary$Pathway, character())\n )\n )\n\n # reorder columns based on the sample ordering\n sample_summary <- vec_slice(\n sample_summary,\n vec_as_location(\n colnames(ans),\n n = vec_size(sample_summary),\n names = vec_cast(sample_summary$Tumor_Sample_Barcode, character())\n )\n )\n sample_anno <- vec_slice(\n sample_anno,\n vec_as_location(\n colnames(ans),\n n = vec_size(sample_anno),\n names = sample_anno$Tumor_Sample_Barcode\n )\n )\n ggalign_data_set(ans,\n gene_list = gene_list,\n pathway_summary = pathway_summary,\n sample_summary = sample_summary,\n sample_anno = sample_anno\n )\n}\n\n#' Build a matrix from a maftools object\n#'\n#' @inheritParams rlang::args_dots_empty\n#' @param data A [`GISTIC`][maftools::readGistic] object.\n#' @param n_top A single number indicates how many top bands to be drawn.\n#' @param bands An atomic character defines the bands to draw.\n#' @param ignored_bands An atomic character defines the bands to be ignored.\n#' @param sample_anno A data frame of sample clinical features to be added.\n#' @param remove_empty_samples A single boolean value indicating whether to drop\n#' samples without any genomic alterations.\n#' @inheritParams fortify_matrix\n#' @section ggalign attributes:\n#' - `sample_anno`: sample clinical informations provided in `sample_anno`.\n#' - `sample_summary`: sample copy number summary informations. See\n#' `data@@cnv.summary` for details.\n#' - `cytoband_summary`: cytoband summary informations. See\n#' `data@@cytoband.summary` for details.\n#' - `gene_summary`: gene summary informations. See\n#' `data@@gene.summary` for details.\n#' - `summary`: A data frame of summary information. See `data@@summary` for\n#' details.\n#' @family fortify_matrix\n#' @export\nfortify_matrix.GISTIC <- function(data, ..., n_top = NULL, bands = NULL,\n ignored_bands = NULL, sample_anno = NULL,\n remove_empty_samples = TRUE,\n data_arg = NULL,\n call = NULL) {\n call <- call %||% current_call()\n rlang::check_dots_empty(call = call)\n rlang::check_installed(\n \"maftools\",\n \"to make CNV matrix from `GISTIC` object\"\n )\n assert_number_whole(n_top,\n allow_null = TRUE,\n call = call\n )\n assert_character(bands,\n allow_null = TRUE,\n call = call\n )\n assert_character(ignored_bands,\n allow_null = TRUE,\n call = call\n )\n assert_s3_class(sample_anno, \"data.frame\",\n allow_null = TRUE,\n call = call\n )\n assert_bool(remove_empty_samples,\n call = call\n )\n cn_mat <- data@cnMatrix\n if (is.null(bands)) {\n bands <- rownames(cn_mat)\n } else {\n bands <- intersect(bands, rownames(cn_mat))\n }\n if (!is.null(ignored_bands)) {\n bands <- setdiff(bands, ignored_bands)\n }\n if (!is.null(bands)) {\n cn_mat <- vec_slice(cn_mat, rownames(cn_mat) %in% bands)\n }\n if (!is.null(n_top)) {\n cn_mat <- vec_slice(cn_mat, seq_len(min(n_top, nrow(cn_mat))))\n }\n if (remove_empty_samples) {\n keep <- colSums(cn_mat != \"\") > 0L\n cn_mat <- cn_mat[, keep, drop = FALSE]\n }\n if (!is.null(sample_anno)) {\n loc <- vec_locate_matches(\n colnames(cn_mat),\n .subset2(sample_anno, \"Tumor_Sample_Barcode\") %||%\n .subset2(sample_anno, 1L),\n relationship = \"one-to-one\",\n needles_arg = \"data\",\n haystack_arg = \"sample_anno\",\n error_call = call\n )\n sample_anno <- vec_slice(sample_anno, .subset2(loc, \"haystack\"))\n }\n sample_summary <- new_data_frame(data@cnv.summary)\n sample_summary <- vec_slice(\n sample_summary,\n vec_as_location(\n colnames(cn_mat),\n n = vec_size(sample_summary),\n names = vec_cast(sample_summary$Tumor_Sample_Barcode, character())\n )\n )\n gene_summary <- new_data_frame(data@gene.summary)\n cytoband_sumamry <- new_data_frame(data@cytoband.summary)\n cytoband_sumamry <- vec_slice(\n cytoband_sumamry,\n vec_as_location(\n rownames(cn_mat),\n n = vec_size(cytoband_sumamry),\n names = vec_cast(cytoband_sumamry$Unique_Name, character())\n )\n )\n ggalign_data_set(cn_mat,\n sample_anno = sample_anno,\n sample_summary = sample_summary,\n cytoband_sumamry = cytoband_sumamry,\n gene_summary = gene_summary,\n sumamry = data@summary\n )\n}\n"], ["/ggalign/R/craftbox-.R", "# Use S4 to override the double dispatch problem of ggplot2\n# And it's easy to convert a S4 Class to a S7 Class\nmethods::setClass(\n \"CraftBox\",\n list(\n plot = \"ANY\", # To avoid modify in place, we put plot in a slot\n active = \"ANY\",\n size = \"ANY\",\n schemes = \"ANY\",\n craftsman = \"ANY\" # `Craftsman` object\n )\n)\n\n#' Show `CraftBox` information\n#' @param object A `CraftBox` object.\n#' @return The input invisiblely.\n#' @keywords internal\nmethods::setMethod(\"show\", \"CraftBox\", function(object) {\n print(object)\n})\n\n#' @importFrom methods new\nnew_craftbox <- function(craftsman = NULL, ...,\n plot = NULL, active = NULL, size = NULL,\n schemes = NULL, call = caller_call()) {\n assert_active(active, allow_null = FALSE, call = call)\n if (is.null(size)) {\n size <- unit(NA, \"null\")\n } else {\n size <- check_size(size, call = call)\n }\n new(\n \"CraftBox\",\n # `call`: used to provide error message\n craftsman = ggproto(NULL, craftsman %||% Craftsman, ..., call = call),\n schemes = schemes %||% default_schemes(),\n plot = plot, active = active, size = size\n )\n}\n\n#' @export\nprint.CraftBox <- function(x, ...) {\n cat(x@craftsman$summary(x@plot), sep = \"\\n\")\n invisible(x)\n}\n\n#' @export\nplot.CraftBox <- function(x, ...) {\n cli_abort(sprintf(\"Cannot plot %s object directly\", object_name(x)))\n}\n\n#' @importFrom grid grid.draw\n#' @exportS3Method\ngrid.draw.CraftBox <- plot.CraftBox\n\n#' Add custom objects to ggalign plot\n#' @keywords internal\nmethods::setMethod(\"+\", c(\"CraftBox\", \"ANY\"), function(e1, e2) {\n if (missing(e2)) {\n cli_abort(c(\n \"Cannot use {.code {.Generic}} with a single argument.\",\n \"i\" = \"Did you accidentally put {.code {.Generic}} on a new line?\"\n ))\n }\n\n if (is.null(e2)) return(e1) # styler: off\n\n # Get the name of what was passed in as e2, and pass along so that it\n # can be displayed in error messages\n e2name <- paste(deparse(substitute(e2)), collapse = \" \")\n switch(.Generic, # nolint\n `+` = craftbox_add(e2, e1, e2name),\n stop_incompatible_op(.Generic, e1, e2)\n )\n})\n\n#' @importFrom methods is\nis_craftbox <- function(x) is(x, \"CraftBox\")\n\nis_cross_plot <- function(x) is_craftbox(x) && is_cross(x@craftsman)\n\nis_cross <- function(x) inherits(x, \"CraftCross\")\n\n#######################################################\n#' @importFrom ggplot2 ggproto\nCraftsman <- ggproto(\"Craftsman\",\n call = NULL,\n\n # following fields will be added when added to the layout\n in_linear = NULL,\n layout_name = NULL,\n direction = NULL,\n position = NULL, # for stack_layout() in quad_layout()\n labels = NULL,\n\n # A single boolean value indicates whether we should set facet and coord\n free_facet = FALSE,\n free_coord = FALSE,\n free_limits = FALSE,\n\n # we always prevent user from modifying the object in `$build_plot()` and\n # `$finish_plot()` methods\n locked = TRUE,\n lock = function(self) {\n assign(\"locked\", value = TRUE, envir = self)\n },\n unlock = function(self) {\n assign(\"locked\", value = FALSE, envir = self)\n },\n\n ############################################################\n # when added to the `Layout` object, will call following methods\n\n # we usually, define the `nobs` in `interact_layout`, since we can\n # act with the layout data in `interact_layout` method\n interact_layout = function(self, layout) layout,\n\n # we define the `panel` and `index` method in `setup_design` method\n setup_design = function(self, design) design,\n setup_plot = function(self, plot) plot,\n\n ##############################################################\n # Don't change the facet and coord in following methods\n build_plot = function(self, plot, design, extra_design = NULL,\n previous_design = NULL) {\n plot\n },\n finish_plot = function(self, plot, schemes, theme) {\n plot <- plot_add_schemes(plot, schemes)\n ggremove_margin(plot, self$direction) + theme_recycle()\n },\n\n # utils method to print the object, should return a character vector\n summary = function(self, plot) {\n cls <- class(self)\n cls <- cls[seq_len(which(cls == \"Craftsman\"))]\n sprintf(\"\", paste(cls, collapse = \" \"))\n }\n)\n\n# Used to lock the `Craftsman` object\n#' @export\n`$<-.Craftsman` <- function(x, name, value) {\n if (x$locked) {\n cli_abort(c(\n sprintf(\"Cannot modify %s\", object_name(x)),\n i = sprintf(\"%s is locked\", object_name(x))\n ), call = x$call)\n }\n NextMethod()\n}\n\n#################################################################\ncraftbox_add <- function(object, craftbox, object_name) {\n if (is.null(craftbox@plot)) {\n cli_abort(c(\n sprintf(\n \"Cannot add {.var {object_name}} to %s\",\n object_name(craftbox)\n ),\n i = sprintf(\"no plot found for %s\", object_name(craftbox))\n ))\n }\n UseMethod(\"craftbox_add\")\n}\n\n#' @importFrom ggplot2 ggplot_add\n#' @export\ncraftbox_add.default <- function(object, craftbox, object_name) {\n craftbox@plot <- ggplot_add(\n object,\n ggfun(\"plot_clone\")(craftbox@plot),\n object_name\n )\n craftbox\n}\n\n#' @export\ncraftbox_add.ggalign_scheme <- function(object, craftbox, object_name) {\n name <- ggalign_scheme_name(object)\n craftbox@schemes[name] <- list(update_scheme(\n object, .subset2(craftbox@schemes, name), object_name\n ))\n craftbox\n}\n\n######################################################################\nplot_build <- function(align, ..., schemes, theme) {\n plot <- align$build_plot(plot@plot, ...)\n align$finish_plot(plot, schemes, theme)\n}\n"], ["/ggalign/R/layout-chain-stack-.R", "#' Arrange plots horizontally or vertically\n#'\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' If `limits` is provided, a continuous variable will be required and aligned\n#' in the direction specified (`stack_continuous`). Otherwise, a discrete\n#' variable will be required and aligned (`stack_discrete`).\n#'\n#' Several aliases are provided for convenience:\n#' - `stack_vertical`: A special case of `stack_layout` that sets `direction\n#' = \"v\"`.\n#' - `stack_horizontal`: A special case of `stack_layout` that sets `direction\n#' = \"h\"`.\n#' - `stack_discretev`: A special case of `stack_discrete` that sets `direction\n#' = \"v\"`.\n#' - `stack_discreteh`: A special case of `stack_discrete` that sets `direction\n#' = \"h\"`.\n#' - `stack_continuousv()`: A special case of `stack_free` that sets `direction\n#' = \"v\"`.\n#' - `stack_continuoush()`: A special case of `stack_free` that sets `direction\n#' = \"h\"`.\n#'\n#' For historical reasons, the following aliases are available:\n#' - `stack_align` is an alias for `stack_discrete`.\n#' - `stack_alignv` is an alias for `stack_discretev`.\n#' - `stack_alignh` is an alias for `stack_discreteh`.\n#' - `stack_free` is an alias for `stack_continuous`.\n#' - `stack_freev` is an alias for `stack_continuousv`.\n#' - `stack_freeh` is an alias for `stack_continuoush`.\n#'\n#' @param direction A string indicating the direction of the stack layout,\n#' either `\"h\"`(`horizontal`) or `\"v\"`(`vertical`).\n#' @param data `r rd_layout_data()`:\n#' - If `limits` is not provided, [`fortify_matrix()`] will be used to get a\n#' matrix.\n#' - If `limits` is specified, [`fortify_data_frame()`] will be used to get a\n#' data frame.\n#'\n#' @param ... Additional arguments passed to [`fortify_data_frame()`] or\n#' [`fortify_matrix()`].\n#' @param theme A [`theme()`][ggplot2::theme] object used to customize various\n#' elements of the layout, including `guides`, `title`, `subtitle`, `caption`,\n#' `margins`, `panel.border`, and `background`. By default, the theme will\n#' inherit from the parent `layout`. It also controls the panel spacing for all\n#' plots in the layout.\n#'\n#' @param sizes A numeric value or a [`unit`][grid::unit] object. When used for\n#' the [`quad_layout()`] annotation, it must be of length `1`. When used in the\n#' [`stack_layout()`] with a nested [`quad_layout()`], it should be of length\n#' `3`, specifying the relative heights (for `direction = \"h\"`) or widths (for\n#' `direction = \"v\"`) to be applied to the layout.\n#' @param limits A [`continuous_limits()`] object specifying the left/lower\n#' limit and the right/upper limit of the scale. Used to align the continuous\n#' axis.\n#' @return A `StackLayout` object.\n#' @examples\n#' set.seed(123)\n#' small_mat <- matrix(rnorm(56), nrow = 7L)\n#'\n#' stack_horizontal(small_mat) + align_dendro()\n#'\n#' # this is the same with:\n#' stack_discrete(\"h\", small_mat) + align_dendro()\n#'\n#' stack_discreteh(small_mat) + align_dendro()\n#'\n#' # For vertical layout:\n#' stack_vertical(small_mat) + align_dendro()\n#'\n#' @export\nstack_layout <- function(direction, data = NULL, ...,\n theme = NULL, sizes = NA, limits = waiver()) {\n if (is.waive(limits)) {\n stack_discrete(\n data = data, direction = direction, ...,\n theme = theme, sizes = sizes\n )\n } else {\n stack_continuous(\n data = data, direction = direction, ...,\n theme = theme, sizes = sizes, limits = limits\n )\n }\n}\n\n#' @export\n#' @rdname stack_layout\nstack_horizontal <- function(data = NULL, ..., limits = waiver()) {\n stack_layout(data = data, direction = \"h\", limits = limits, ...)\n}\n\n#' @export\n#' @rdname stack_layout\nstack_vertical <- function(data = NULL, ..., limits = waiver()) {\n stack_layout(data = data, direction = \"v\", limits = limits, ...)\n}\n\n###################################################################\n#' @export\n#' @rdname stack_layout\nstack_discrete <- function(direction, data = NULL, ...,\n theme = NULL, sizes = NA) {\n UseMethod(\"stack_discrete\", data)\n}\n\n#' @usage NULL\n#' @export\n#' @rdname stack_layout\nstack_align <- stack_discrete\n\n#' @export\n#' @rdname stack_layout\nstack_discretev <- function(data = NULL, ...) {\n stack_discrete(data = data, direction = \"v\", ...)\n}\n\n#' @usage NULL\n#' @export\n#' @rdname stack_layout\nstack_alignv <- stack_discretev\n\n#' @export\n#' @rdname stack_layout\nstack_discreteh <- function(data = NULL, ...) {\n stack_discrete(data = data, direction = \"h\", ...)\n}\n\n#' @usage NULL\n#' @export\n#' @rdname stack_layout\nstack_alignh <- stack_discreteh\n\n#' @export\nstack_discrete.default <- function(direction, data = NULL, ...,\n theme = NULL, sizes = NA) {\n direction <- check_direction(direction)\n # the observations are rows, we use matrix to easily\n # reshape it into a long formated data frame for ggplot,\n # and we can easily determine the number of observations\n # from matrix\n data <- data %|w|% NULL\n data <- fortify_matrix(data = data, ...)\n schemes <- default_schemes()\n if (!is.null(data) && !is.function(data)) {\n # if we have provided data, we initialize the `nobs`\n nobs <- vec_size(data)\n\n # for data has dimention but one dimention is 0\n # as.matrix(data.frame(row.names = letters))\n if (nobs == 0L) {\n cli_abort(\"empty data is no allowed\")\n }\n } else {\n nobs <- NULL\n }\n new_stack_layout(\n name = \"stack_discrete\",\n data = data, direction = direction,\n design = discrete_design(nobs = nobs),\n schemes = schemes, theme = theme, sizes = sizes\n )\n}\n\n#' @export\nstack_discrete.function <- function(direction, data = NULL, ...) {\n cli_abort(paste0(\n \"{.arg data} must be a {.cls matrix}, \",\n \"or an object coercible by {.fn fortify_matrix}, or a valid \",\n \"{.cls matrix}-like object coercible by {.fn as.matrix}\"\n ))\n}\n\n#' @export\nstack_discrete.formula <- stack_discrete.function\n\n################################################################\n#' @export\n#' @rdname stack_layout\nstack_continuous <- function(direction, data = NULL, ..., limits = NULL,\n theme = NULL, sizes = NA) {\n UseMethod(\"stack_continuous\", data)\n}\n\n#' @usage NULL\n#' @export\n#' @rdname stack_layout\nstack_free <- stack_continuous\n\n#' @export\n#' @rdname stack_layout\nstack_continuousv <- function(data = NULL, ...) {\n stack_continuous(data = data, direction = \"v\", ...)\n}\n\n#' @usage NULL\n#' @export\n#' @rdname stack_layout\nstack_freev <- stack_continuousv\n\n#' @export\n#' @rdname stack_layout\nstack_continuoush <- function(data = NULL, ...) {\n stack_continuous(data = data, direction = \"h\", ...)\n}\n\n#' @usage NULL\n#' @export\n#' @rdname stack_layout\nstack_freeh <- stack_continuoush\n\n#' @export\nstack_continuous.default <- function(direction, data = NULL, ...,\n limits = NULL, theme = NULL, sizes = NA) {\n assert_limits(limits)\n direction <- check_direction(direction)\n data <- data %|w|% NULL\n data <- fortify_data_frame(data = data, ...)\n schemes <- default_schemes()\n new_stack_layout(\n name = \"stack_continuous\",\n data = data, direction = direction, design = limits,\n schemes = schemes, theme = theme, sizes = sizes\n )\n}\n\n#' @export\nstack_continuous.function <- function(direction, data = NULL, ...) {\n cli_abort(paste0(\n \"{.arg data} must be a {.cls data.frame}, \",\n \"or an object coercible by {.fn fortify_data_frame}, or a valid \",\n \"{.cls data.frame}-like object coercible by {.fn as.data.frame}\"\n ))\n}\n\n#' @export\nstack_continuous.formula <- stack_continuous.function\n\n#' @importFrom methods new\nnew_stack_layout <- function(data, direction, design,\n schemes = NULL, theme = NULL, sizes = NA,\n name = NULL, call = caller_call()) {\n sizes <- check_stack_sizes(sizes, call = call)\n if (!is.null(theme)) assert_s3_class(theme, \"theme\", call = call)\n if (is.null(name)) {\n if (is_continuous_design(design)) {\n name <- \"stack_continuous\"\n } else {\n name <- \"stack_discrete\"\n }\n }\n new(\n \"StackLayout\",\n name = name, data = data,\n direction = direction,\n theme = theme, schemes = schemes, # used by the layout\n sizes = sizes, design = design\n )\n}\n\n############################################################\n# Used to place multiple objects in one axis\n#' @importFrom grid unit\n#' @importFrom ggplot2 waiver\n#' @keywords internal\n#' @include layout-chain-.R\nmethods::setClass(\n \"StackLayout\",\n contains = \"ChainLayout\",\n list(\n direction = \"character\",\n heatmap = \"list\", # used by heatmap annotation\n sizes = \"ANY\" # used by stack layout\n ),\n prototype = list(\n heatmap = list(\n position = NULL,\n free_guides = waiver(),\n # indicate whether or not the data is from the quad-layout matrix\n quad_matrix = FALSE\n )\n )\n)\n"], ["/ggalign/R/layout-quad-add.R", "#' @keywords internal\nquad_layout_add <- function(object, quad, object_name) {\n UseMethod(\"quad_layout_add\")\n}\n\n#############################################################\n#' @export\nquad_layout_add.layout_title <- function(object, quad, object_name) {\n quad@titles <- update_non_waive(quad@titles, object)\n quad\n}\n\n##############################################################\n# Preventing from adding following elements\n#' @export\nquad_layout_add.matrix <- function(object, quad, object_name) {\n cli_abort(sprintf(\"Can't change data of %s\", object_name(quad)))\n}\n\n#' @export\nquad_layout_add.data.frame <- quad_layout_add.matrix\n\n#############################################################\n# Add elements for the main body or the annotation\n#' @importFrom methods slot slot<-\n#' @export\nquad_layout_add.default <- function(object, quad, object_name) {\n if (is.null(position <- quad@active)) {\n quad <- quad_body_add(object, quad, object_name)\n } else if (is.null(stack <- slot(quad, position))) {\n cli_abort(c(\n sprintf(\"Cannot add {.var {object_name}} to %s\", object_name(quad)),\n i = \"the {.field {position}} annotation stack is not initialized\",\n i = \"Try to use {.code quad_anno(initialize = TRUE)} or you can add a {.code stack_layout()} manually\"\n ))\n } else {\n slot(quad, position) <- chain_layout_add(object, stack, object_name)\n }\n quad\n}\n\n#' @export\nquad_layout_add.list <- function(object, quad, object_name) {\n for (o in object) quad <- quad_layout_add(o, quad, object_name)\n quad\n}\n\n#' @export\nquad_layout_add.NULL <- function(object, quad, object_name) {\n quad\n}\n\n#' @export\nquad_layout_add.ggalign_with_quad <- function(object, quad, object_name) {\n old <- quad@active\n contexts <- quad_operated_context(object, old, \"+\") %||%\n list(NULL) # we wrap `NULL` to a list for `for loop`.\n object <- .subset2(object, \"object\")\n object_name <- .subset2(object, \"object_name\")\n for (active in contexts) {\n quad@active <- active\n quad <- quad_layout_add(object, quad, object_name)\n }\n quad@active <- old\n quad\n}\n\n##################################################################\n#' @export\nquad_layout_add.quad_active <- function(object, quad, object_name) {\n if (!is.null(width <- .subset2(object, \"width\"))) {\n quad@width <- width\n }\n if (!is.null(height <- .subset2(object, \"height\"))) {\n quad@height <- height\n }\n quad@active <- NULL\n quad\n}\n\n#' @importFrom methods slot\n#' @export\nquad_layout_add.quad_anno <- function(object, quad, object_name) {\n position <- .subset2(object, \"position\")\n initialize <- .subset2(object, \"initialize\")\n stack <- slot(quad, position)\n if (is.null(stack) && !isFALSE(initialize)) {\n # try to initialize the annotation stack with the layout data\n direction <- to_direction(position)\n layout_design <- slot(quad, direction)\n # for the annotation stack, we try to take the data from the\n # quad layout\n quad_data <- quad@data\n data <- waiver() # use waiver() to indicate data is not initialized\n quad_matrix <- FALSE # the default value for `quad_matrix` in the stack\n if (is_continuous_design(layout_design)) { # the stack need a data frame\n if (!is.data.frame(quad_data)) {\n if (is.null(initialize)) {\n cli_warn(paste(\n \"`data` in {.fn {quad@name}} is\",\n \"{.obj_type_friendly {quad_data}}, but the\",\n \"{.field {position}} annotation stack need a\",\n \"{.cls data.frame}, won't initialize\",\n \"the {.field {position}} annotation stack\"\n ))\n } else {\n data <- NULL\n }\n } else {\n data <- quad_data\n }\n } else if (is.matrix(quad_data)) { # the stack need a matrix\n if (is_horizontal(direction)) {\n data <- quad_data\n } else {\n data <- ggalign_data_restore(t(quad_data), quad_data)\n }\n quad_matrix <- TRUE\n } else {\n if (is.null(initialize)) {\n cli_warn(paste(\n \"`data` in {.fn {quad@name}} is\",\n \"{.obj_type_friendly {quad_data}}, but the\",\n \"{.field {position}} annotation stack need a\",\n \"{.cls data.frame}, won't initialize\",\n \"the {.field {position}} annotation stack\"\n ))\n } else {\n data <- NULL\n }\n }\n if (!is.waive(data)) { # initialize the annotation stack\n stack <- new_stack_layout(\n data = data,\n direction = direction,\n # the layout parameters should be the same with `quad_layout()`\n design = layout_design,\n # we'll inherit the action data function when\n schemes = default_schemes(if (is.null(data)) NULL else waiver())\n )\n stack@heatmap$position <- position\n stack@heatmap$quad_matrix <- quad_matrix\n }\n } else if (!is.null(stack) && isTRUE(initialize)) {\n cli_abort(c(\n \"Cannot initialize the {position} annotation stack\",\n i = \"{position} annotation stack has already been initialized\"\n ))\n }\n\n if (!is.null(stack)) {\n # update parameters\n if (!is.null(size <- .subset2(object, \"size\"))) {\n stack@sizes <- size\n }\n if (!is.waive(free_guides <- .subset2(object, \"free_guides\"))) {\n stack@heatmap[\"free_guides\"] <- list(free_guides)\n }\n stack <- switch_chain_plot(\n stack, .subset2(object, \"what\"), quote(quad_anno())\n )\n slot(quad, position) <- stack\n }\n quad@active <- position\n quad\n}\n\n#' @export\nquad_layout_add.QuadLayout <- function(object, quad, object_name) {\n cli_abort(c(\n sprintf(\"Cannot add {.var {object_name}} to %s\", object_name(quad)),\n i = \"Did you mean to place multiple {.fn quad_layout} elements inside a {.fn stack_layout}?\"\n ))\n}\n\n#' @export\nquad_layout_add.StackLayout <- function(object, quad, object_name) {\n # we check if there is an active annotation\n if (is.null(position <- quad@active)) {\n cli_abort(c(\n sprintf(\"Cannot add {.var {object_name}} to %s\", object_name(quad)),\n i = \"no active annotation stack\",\n i = \"try to activate an annotation stack with {.fn anno_*}\"\n ))\n }\n # check the annotation stack is not initialized\n if (!is.null(slot(quad, position))) {\n cli_abort(c(\n sprintf(\"Cannot add {.var {object_name}} to %s\", object_name(quad)),\n i = \"{position} annotation stack already exists\"\n ))\n }\n # cannot contain nested layout\n if (!all(vapply(object@plot_list, is_craftbox, logical(1L),\n USE.NAMES = FALSE))) { # styler: off\n cli_abort(c(\n sprintf(\"Cannot add {.var {object_name}} to %s\", object_name(quad)),\n i = \"annotation stack cannot contain nested layout\"\n ))\n }\n # check quad layout is compatible with stack layout\n if (!identical(direction <- to_direction(position), object@direction)) {\n cli_abort(c(\n sprintf(\"Cannot add {.var {object_name}} to %s\", object_name(quad)),\n i = \"only {.field {direction}} stack is allowed in {position} annotation\"\n ))\n }\n if (length(object@sizes) > 1L) {\n cli_abort(c(\n sprintf(\"Cannot add {.var {object_name}} to %s\", object_name(quad)),\n i = \"{.arg sizes} must be of length one to use the stack as an annotation\"\n ))\n }\n quad_design <- slot(quad, direction)\n if (is_cross_layout(object) &&\n any(position == c(\"bottom\", \"right\")) &&\n !is_empty(object@cross_points)) {\n # if there are cross points in bottom or right annotation,\n # use the first design\n stack_design <- .subset2(object@odesign, 1L)\n } else {\n stack_design <- object@design\n }\n # check if we can align in this direction\n # `stack_layout()` is free from aligning obervations in this axis\n if (is_continuous_design(stack_design)) {\n if (!is_continuous_design(quad_design)) {\n cli_abort(c(\n sprintf(\n \"Cannot add {.var {object_name}} to %s\",\n object_name(quad)\n ),\n i = sprintf(\n \"%s cannot align continuous variable in {.field {direction}} direction\",\n object_name(quad)\n )\n ))\n }\n layout_design <- stack_design\n } else if (is_discrete_design(quad_design)) {\n layout_design <- melt_discrete_design(\n quad_design, stack_design,\n old_name = object_name(quad),\n new_name = object_name\n )\n } else {\n cli_abort(c(\n sprintf(\"Cannot add {.var {object_name}} to %s\", object_name(quad)),\n i = sprintf(\n \"%s cannot align discrete variable in {.field {direction}} direction\",\n object_name(quad)\n )\n ))\n }\n object@heatmap$position <- position\n slot(quad, position) <- object\n update_design(quad,\n direction = direction,\n design = layout_design,\n object_name = object_name\n )\n}\n\n#' @importFrom methods slot slot<-\n#' @export\nquad_layout_add.CraftBox <- function(object, quad, object_name) {\n if (is.null(position <- quad@active)) {\n cli_abort(c(\n sprintf(\"Cannot add {.var {object_name}} to %s\", object_name(quad)),\n i = \"no active annotation stack\",\n i = \"try to activate an annotation stack with {.fn anno_*}\"\n ))\n }\n if (is.null(stack <- slot(quad, position))) {\n cli_abort(c(\n sprintf(\"Cannot add {.var {object_name}} to %s\", object_name(quad)),\n i = \"the {.field {position}} annotation stack is not initialized\",\n i = \"Try to use {.code quad_anno(initialize = TRUE)} or you can add a {.code stack_layout()} manually\"\n ))\n }\n\n # add annotation -----------------------------\n stack <- chain_layout_add(object, stack, object_name)\n slot(quad, position) <- stack\n\n # if there are cross points in bottom or right annotation, we use\n # the first design\n if (is_cross_layout(stack) &&\n any(position == c(\"bottom\", \"right\")) &&\n !is_empty(stack@cross_points)) {\n new_design <- .subset2(stack@odesign, 1L)\n } else {\n new_design <- stack@design\n }\n\n update_design(\n quad,\n direction = to_direction(position),\n design = new_design,\n object_name = object_name\n )\n}\n\n#######################################################\n# used to add elements for main body\n#' @keywords internal\nquad_body_add <- function(object, quad, object_name) {\n UseMethod(\"quad_body_add\")\n}\n\n#' @importFrom ggplot2 ggplot_add\n#' @export\nquad_body_add.default <- function(object, quad, object_name) {\n quad@plot <- ggplot_add(object, ggfun(\"plot_clone\")(quad@plot), object_name)\n quad\n}\n\n#' @export\nquad_body_add.Coord <- function(object, quad, object_name) {\n if (!inherits(object, \"CoordCartesian\")) {\n cli_warn(c(\n \"only {.field cartesian coordinate} is supported\",\n i = \"will discard {.var {object_name}} directly\"\n ))\n return(quad)\n }\n NextMethod() # call default method\n}\n\n#' @export\nquad_body_add.layout_theme <- function(object, quad, object_name) {\n quad@theme <- update_layout_theme(quad@theme, object)\n quad\n}\n\n#' @export\nquad_body_add.ggalign_scheme <- function(object, quad, object_name) {\n name <- ggalign_scheme_name(object)\n quad@body_schemes[name] <- list(update_scheme(\n object, .subset2(quad@body_schemes, name), object_name\n ))\n quad\n}\n"], ["/ggalign/R/layout-quad-.R", "#' Arrange plots in the quad-side of a main plot\n#'\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' This function arranges plots around the quad-sides of a main plot, aligning\n#' both horizontal and vertical axes, and can handle either discrete or\n#' continuous variables.\n#'\n#' - If `xlim` is provided, a continuous variable will be required and aligned\n#' in the vertical direction. Otherwise, a discrete variable will be required\n#' and aligned.\n#' - If `ylim` is provided, a continuous variable will be required and aligned\n#' in the horizontal direction. Otherwise, a discrete variable will be\n#' required and aligned.\n#'\n#' The `quad_discrete` is a special case where both `xlim` and `ylim` are not\n#' provided.\n#'\n#' The `quad_continuous` is a special case where both `xlim` and `ylim` are\n#' provided.\n#'\n#' For historical reasons, the following aliases are available:\n#' - `quad_alignh`: Align discrete variables in the horizontal direction and\n#' continuous variables in vertical direction.\n#' - `quad_alignv`: Align discrete variables in the vertical direction and\n#' continuous variables in horizontal direction.\n#' - `quad_alignb` is an alias for `quad_discrete`.\n#' - `quad_free` is an alias for `quad_continuous`.\n#'\n#' @param data `r rd_layout_data()`. By default, this will attempt\n#' to inherit from the parent layout.\n#'\n#' If both `xlim` and `ylim` are provided, a `data frame` is required, and\n#' [`fortify_data_frame()`] will be used to convert the data to a data frame.\n#' When inherited by an annotation stack, no transposition will be applied.\n#'\n#' Otherwise, a `matrix` is required, and [`fortify_matrix()`] will be used to\n#' convert the data to a matrix. When inherited by the column annotation\n#' stack, the data will be transposed.\n#' @param mapping Default list of aesthetic mappings to use for main plot in the\n#' layout. If not specified, must be supplied in each layer added to the main\n#' plot.\n#' @param xlim,ylim A [`continuous_limits()`] object specifying the left/lower\n#' limit and the right/upper limit of the scale. Used to align the continuous\n#' axis.\n#' @param width,height The relative width/height of the main plot, can be a\n#' [`unit`][grid::unit] object.\n#' @inheritParams stack_layout\n#' @inheritParams align\n#' @return A `QuadLayout` object.\n#' @section ggplot2 specification:\n#' If either `xlim` or `ylim` is not provided, the data input will be converted\n#' to a matrix using [`fortify_matrix()`], and the data in the underlying main\n#' plot will contain the following columns:\n#'\n#' - `.panel_x` and `.panel_y`: the column and row panel groups.\n#'\n#' - `.x` and `.y`: an integer index of `x` and `y` coordinates\n#'\n#' - `.discrete_x` and `.discrete_y`: a factor of the data labels (only\n#' applicable when `.row_names` and `.column_names` exists).\n#'\n#' - `.row_names` and `.column_names`: A character of the row and column names\n#' of the original matrix (only applicable when names exist).\n#'\n#' - `.row_index` and `.column_index`: the row and column index of the original\n#' matrix.\n#'\n#' - `value`: the actual matrix value.\n#'\n#' Otherwise, the data input will be used for the main plot.\n#'\n#' @export\nquad_layout <- function(data = waiver(), mapping = aes(),\n xlim = waiver(), ylim = waiver(),\n ...,\n theme = NULL, active = NULL,\n width = NA, height = NA) {\n if (is.waive(xlim) && is.waive(ylim)) {\n quad_discrete(\n data = data, mapping = mapping,\n ..., active = active, theme = theme,\n width = width, height = height\n )\n } else if (!is.waive(xlim) && !is.waive(ylim)) {\n quad_continuous(\n data = data, mapping = mapping, xlim = xlim, ylim = ylim,\n ..., active = active, theme = theme,\n width = width, height = height\n )\n } else {\n data <- fortify_matrix(data = data, ...)\n new_quad_layout(\n name = \"quad_layout\",\n data = data, ylim = ylim, xlim = xlim,\n mapping = mapping, active = active, theme = theme,\n width = width, height = height\n )\n }\n}\n\n#' @export\n#' @rdname quad_layout\nquad_alignh <- function(..., ylim = waiver()) {\n quad_layout(..., xlim = NULL, ylim = ylim)\n}\n\n#' @export\n#' @rdname quad_layout\nquad_alignv <- function(..., xlim = waiver()) {\n quad_layout(..., xlim = xlim, ylim = NULL)\n}\n\n##########################################################\n#' @export\n#' @rdname quad_layout\nquad_discrete <- function(data = waiver(), mapping = aes(),\n ...,\n theme = NULL, active = NULL,\n width = NA, height = NA) {\n UseMethod(\"quad_discrete\")\n}\n\n#' @export\n#' @rdname quad_layout\n#' @usage NULL\nquad_alignb <- quad_discrete\n\n#' @export\nquad_discrete.default <- function(data = waiver(), mapping = aes(),\n ...,\n theme = NULL, active = NULL,\n width = NA, height = NA) {\n data <- fortify_matrix(data = data, ...)\n new_quad_layout(\n name = \"quad_discrete\", data = data, xlim = waiver(), ylim = waiver(),\n mapping = mapping, active = active, theme = theme,\n width = width, height = height\n )\n}\n\n#' @export\nquad_discrete.uneval <- function(data, ...) {\n cli_abort(c(\n \"{.arg data} cannot be {.obj_type_friendly {data}}\",\n \"i\" = \"Have you misspelled the {.arg data} argument in {.fn quad_discrete}\"\n ))\n}\n\n#############################################################\n#' @export\n#' @rdname quad_layout\nquad_continuous <- function(data = waiver(), mapping = aes(),\n xlim = NULL, ylim = NULL,\n ...,\n theme = NULL, active = NULL,\n width = NA, height = NA) {\n UseMethod(\"quad_continuous\")\n}\n\n#' @usage NULL\n#' @export\n#' @rdname quad_layout\nggside <- quad_continuous\n\n#' @usage NULL\n#' @export\n#' @rdname quad_layout\nquad_free <- quad_continuous\n\n#' @export\nquad_continuous.default <- function(data = waiver(), mapping = aes(),\n xlim = NULL, ylim = NULL,\n ...,\n theme = NULL, active = NULL,\n width = NA, height = NA) {\n xlim <- xlim %|w|% NULL\n ylim <- ylim %|w|% NULL\n data <- fortify_data_frame(data = data, ...)\n new_quad_layout(\n name = \"quad_continuous\",\n data = data, xlim = xlim, ylim = ylim,\n mapping = mapping, active = active, theme = theme,\n width = width, height = height\n )\n}\n\n#' @export\nquad_continuous.uneval <- function(data, ...) {\n cli_abort(c(\n \"{.arg data} cannot be {.obj_type_friendly {data}}\",\n \"i\" = \"Have you misspelled the {.arg data} argument in {.fn quad_free}\"\n ))\n}\n\n#####################################################\n#' @importFrom ggplot2 ggplot\n#' @importFrom methods new\nnew_quad_layout <- function(name, data, xlim = waiver(), ylim = waiver(),\n mapping = aes(), theme = NULL, active = NULL,\n width = NA, height = NA,\n class = \"QuadLayout\",\n call = caller_call()) {\n if (!is.waive(xlim)) assert_limits(xlim, call = call)\n if (!is.waive(ylim)) assert_limits(ylim, call = call)\n if (is.waive(xlim) || is.waive(ylim)) {\n # If we need align discrete variables, data cannot be `NULL` and\n # must be provided, here, we convert it to waiver() to indicate\n # inherit from the parent layout\n data <- data %||% waiver()\n if (!is.waive(data) && !is.function(data)) {\n nrows <- NROW(data)\n ncols <- ncol(data)\n\n # for data has dimention but one dimention is 0\n # as.matrix(data.frame(row.names = letters))\n if (nrows == 0L || ncols == 0L) {\n cli_abort(\"empty data is no allowed\")\n }\n } else {\n nrows <- NULL\n ncols <- NULL\n }\n }\n horizontal <- ylim %|w|% discrete_design(nobs = nrows)\n vertical <- xlim %|w|% discrete_design(nobs = ncols)\n\n # always remove default axis titles\n # https://stackoverflow.com/questions/72402570/why-doesnt-gplot2labs-overwrite-update-the-name-argument-of-scales-function\n # There are multiple ways to set labels in a plot, which take different\n # priorities. Here are the priorities from highest to lowest.\n # 1. The guide title.\n # 2. The scale name.\n # 3. The `labs()` function.\n # 4. The captured expression in aes().\n plot <- ggplot(mapping = mapping) +\n ggplot2::labs(x = NULL, y = NULL)\n\n if (!is.null(theme)) assert_s3_class(theme, \"theme\", call = call)\n # for `QuadLayout`, we use `NULL` to inherit data from parent layout\n # since `QuadLayout` must have data, and won't be waiver()\n # if inherit from the parent layout data, we'll inherit\n # the action data function\n schemes <- default_schemes(\n if (is.null(data)) waiver() else NULL,\n th = theme_no_strip()\n )\n\n # check arguments -----------------------------------\n width <- check_size(width, call = call)\n height <- check_size(height, call = call)\n assert_active(active, call = call)\n\n # Here we use S4 object to override the double dispatch of `+.gg` method\n new(\n class,\n # used by the layout\n data = data, theme = theme,\n schemes = schemes,\n plot_active = update_active(active, new_active(use = TRUE)),\n name = name,\n # used by the main body\n body_schemes = default_schemes(waiver()),\n # following parameters can be controlled by `quad_switch`\n width = width, height = height,\n # following parameters are used internally\n plot = plot, horizontal = horizontal, vertical = vertical\n )\n}\n\n# Used to create the QuadLayout\n#' @include layout-.R\nmethods::setClass(\n \"QuadLayout\",\n contains = \"LayoutProto\",\n list(\n data = \"ANY\", plot = \"ANY\", body_schemes = \"list\", name = \"character\",\n # parameters for main body\n width = \"ANY\", height = \"ANY\",\n # Used to align axis\n horizontal = \"ANY\", vertical = \"ANY\",\n # top, left, bottom, right must be a StackLayout object.\n top = \"ANY\", left = \"ANY\", bottom = \"ANY\", right = \"ANY\",\n # If we regard `QuadLayout` as a plot, and put it into the stack\n # layout, we need following arguments to control it's behavour\n plot_active = \"ANY\"\n ),\n prototype = list(\n # used by QuadLayout\n top = NULL, left = NULL, bottom = NULL, right = NULL\n )\n)\n\n#' @export\nis_layout_discrete.QuadLayout <- function(x, direction, ...) {\n is_discrete_design(slot(x, direction))\n}\n\n#' @export\nis_layout_continuous.QuadLayout <- function(x, direction, ...) {\n is_continuous_design(slot(x, direction))\n}\n"], ["/ggalign/R/mark.R", "#' Define the links to connect the marked observations\n#'\n#' @description\n#' This function allows users to define links between marked observations and\n#' plot panel (e.g., for creating visual connections for related data), which\n#' could help explain the observations.\n#'\n#' @param .draw A function used to draw the links. The function must return a\n#' [`grob()`][grid::grob] object. If the function does not return a valid\n#' `grob`, nothing will be drawn. The input data for the function must contain\n#' two arguments: a data frame for the panel side coordinates and a data frame\n#' for the marked observation coordinates.\n#' @inheritParams .mark_draw\n#' @seealso\n#' - [`mark_line()`]\n#' - [`mark_tetragon()`]\n#' - [`mark_triangle()`]\n#' - [`.mark_draw()`]\n#' @importFrom rlang is_empty inject\n#' @importFrom grid gTree gList\n#' @export\nmark_draw <- function(.draw, ...) {\n if (!is.function(draw <- allow_lambda(.draw))) {\n cli_abort(\"{.arg .draw} must be a function\")\n }\n new_draw <- function(data) {\n ans <- lapply(data, function(dd) {\n draw(.subset2(dd, \"panel\"), .subset2(dd, \"link\"))\n })\n ans <- ans[vapply(ans, is.grob, logical(1L), USE.NAMES = FALSE)]\n if (!is_empty(ans)) {\n gTree(children = inject(gList(!!!ans)))\n }\n }\n .mark_draw(new_draw, ...)\n}\n\n#' @inherit mark_draw title\n#'\n#' @description\n#' A base version of [`mark_draw`], designed for performance optimization. This\n#' function is used to build other `mark_*` functions that manage the drawing of\n#' links between marked observations.\n#'\n#' @param .draw A function used to draw the links. The function must return a\n#' [`grob()`][grid::grob] object. If the function does not return a valid\n#' `grob`, nothing will be drawn. The input data for the function contains a\n#' list, where each item is a list of two data frames: one for the panel side\n#' coordinates (`\"panel\"`) and one for the marked observations coordinates\n#' (`\"link\"`).\n#'\n#' @inheritParams pair_links\n#' @seealso [`mark_draw()`]\n#' @export\n.mark_draw <- function(.draw, ...) {\n if (override_call(call <- caller_call())) {\n call <- current_call()\n }\n if (!is.function(draw <- allow_lambda(.draw))) {\n cli_abort(\"{.arg .draw} must be a function\", call = call)\n }\n links <- pair_links(...)\n structure(list(draw = draw, links = links), class = \"ggalign_mark_draw\")\n}\n\n#' @export\nprint.ggalign_mark_draw <- function(x, ...) {\n header <- sprintf(\"<%s>\", vec_ptype_full(x))\n cat(header, sep = \"\\n\")\n obj_print_data(.subset2(x, \"links\"))\n invisible(x)\n}\n\n#' Link the observations and the panel with a line\n#'\n#' @inheritParams .mark_draw\n#' @param .element A [`element_line()`][ggplot2::element_line] object.\n#' Vectorized fields will be recycled to match the total number of groups, or\n#' you can wrap the element with [`I()`] to recycle to match the drawing\n#' groups. The drawing groups typically correspond to the number of\n#' observations, as each observation will be linked with the plot panel.\n#' @importFrom ggplot2 element_line\n#' @export\nmark_line <- function(..., .element = NULL) {\n assert_s3_class(.element, \"element_line\", allow_null = TRUE)\n default <- calc_element(\"ggalign.line\", complete_theme(theme_get()))\n if (is.null(.element)) {\n .element <- default\n } else {\n .element <- ggplot2::merge_element(.element, default)\n }\n .mark_draw(.draw = function(data) {\n data <- lapply(data, function(d) {\n panel <- .subset2(d, \"panel\")\n link <- .subset2(d, \"link\")\n data_frame0(\n # there is only one row for panel, it's safe to use\n # vec_interleave directly\n x = vec_interleave(\n (panel$x + panel$xend) / 2L,\n (link$x + link$xend) / 2L\n ),\n y = vec_interleave(\n (panel$y + panel$yend) / 2L,\n (link$y + link$yend) / 2L\n )\n )\n })\n if (inherits(.element, \"AsIs\")) {\n .element <- element_rep_len(.element,\n length.out = sum(list_sizes(data)) / 2L\n )\n } else {\n .element <- element_rep_len(.element, length.out = length(data))\n .element <- element_vec_rep_each(.element,\n times = list_sizes(data) / 2L\n )\n }\n data <- vec_rbind(!!!data)\n element_grob(\n .element,\n x = data$x, y = data$y,\n id.lengths = vec_rep(2L, vec_size(data) / 2L),\n default.units = \"native\"\n )\n }, ...)\n}\n\n#' Link the observations and the panel with a quadrilateral\n#'\n#' @inheritParams .mark_draw\n#' @param .element A [`element_polygon()`] object. Vectorized fields will be\n#' recycled to match the total number of groups, or you can wrap the element\n#' with [`I()`] to recycle to match the drawing groups. The drawing groups\n#' are usually the same as the defined groups, but they will differ when the\n#' defined group of observations is separated and cannot be linked with a\n#' single quadrilateral. In such cases, the number of drawing groups will be\n#' larger than the number of defined groups.\n#' @export\nmark_tetragon <- function(..., .element = NULL) {\n assert_s3_class(.element, \"element_polygon\", allow_null = TRUE)\n default <- calc_element(\"ggalign.polygon\", complete_theme(theme_get()))\n if (is.null(.element)) {\n .element <- default\n } else {\n .element <- ggplot2::merge_element(.element, default)\n }\n .mark_draw(.draw = function(data) {\n data <- lapply(data, function(d) {\n panel <- .subset2(d, \"panel\")\n link <- .subset2(d, \"link\")\n\n # find the consecutive groups\n index <- .subset2(link, \"link_index\")\n oindex <- order(index)\n group <- cumsum(c(0L, diff(index[oindex])) != 1L)\n\n # restore the order\n group <- group[order(oindex)]\n\n # split link into groups\n link <- vec_split(link, group)\n\n # for each group, we draw a quadrilateral\n vec_rbind(!!!lapply(.subset2(link, \"val\"), function(dd) {\n data_frame0(\n x = vec_c(panel$x, panel$xend, max(dd$xend), min(dd$x)),\n y = vec_c(panel$y, panel$yend, max(dd$yend), min(dd$y))\n )\n }))\n })\n if (inherits(.element, \"AsIs\")) {\n .element <- element_rep_len(.element,\n length.out = sum(list_sizes(data)) / 4L\n )\n } else {\n .element <- element_rep_len(.element, length.out = length(data))\n .element <- element_vec_rep_each(.element,\n times = list_sizes(data) / 4L\n )\n }\n data <- vec_rbind(!!!data)\n if (vec_size(data)) {\n element_grob(\n .element,\n x = data$x, y = data$y,\n id.lengths = vec_rep(4L, nrow(data) / 4L),\n default.units = \"native\"\n )\n }\n }, ...)\n}\n\n#' Link the observations and the panel with a triangle\n#'\n#' @inheritParams .mark_draw\n#' @param orientation A single string, either `\"plot\"` or `\"observation\"`,\n#' indicating the base of the triangle.\n#' @param .element An [`element_polygon()`] object. Vectorized fields will be\n#' recycled to match the total number of groups, or you can wrap the element\n#' with [`I()`] to recycle to match the drawing groups.\n#' - When `orientation` is `\"plot\"`, the drawing groups typically correspond\n#' to the number of observations.\n#' - When `orientation` is `\"observation\"`, the drawing groups usually match\n#' the defined groups, but will differ if the defined group of observations\n#' is separated and cannot be linked with a single triangle. In this case,\n#' the number of drawing groups will be larger than the number of defined\n#' groups.\n#' @importFrom rlang arg_match0\n#' @export\nmark_triangle <- function(..., orientation = \"plot\", .element = NULL) {\n assert_s3_class(.element, \"element_polygon\", allow_null = TRUE)\n default <- calc_element(\"ggalign.polygon\", complete_theme(theme_get()))\n if (is.null(.element)) {\n .element <- default\n } else {\n .element <- ggplot2::merge_element(.element, default)\n }\n orientation <- arg_match0(orientation, c(\"plot\", \"observation\"))\n .mark_draw(.draw = function(data) {\n data <- lapply(data, function(d) {\n panel <- .subset2(d, \"panel\")\n link <- .subset2(d, \"link\")\n if (identical(orientation, \"plot\")) {\n # for each link, we draw a triangle\n triangle_list <- lapply(vec_seq_along(link), function(i) {\n dd <- vec_slice(link, i)\n data_frame0(\n x = vec_c(panel$x, panel$xend, (dd$x + dd$xend) / 2L),\n y = vec_c(panel$y, panel$yend, (dd$y + dd$yend) / 2L),\n )\n })\n } else {\n # find the consecutive groups\n index <- .subset2(link, \"link_index\")\n oindex <- order(index)\n group <- cumsum(c(0L, diff(index[oindex])) != 1L)\n\n # restore the order\n group <- group[order(oindex)]\n\n # split link into groups\n link <- vec_split(link, group)\n\n # for each group, we draw a triangle\n triangle_list <- lapply(.subset2(link, \"val\"), function(dd) {\n data_frame0(\n x = vec_c(\n (panel$x + panel$xend) / 2L,\n max(dd$xend), min(dd$x)\n ),\n y = vec_c(\n (panel$y + panel$yend) / 2L,\n max(dd$yend), min(dd$y)\n )\n )\n })\n }\n vec_rbind(!!!triangle_list)\n })\n if (inherits(.element, \"AsIs\")) {\n .element <- element_rep_len(.element,\n length.out = sum(list_sizes(data)) / 3L\n )\n } else {\n .element <- element_rep_len(.element, length.out = length(data))\n .element <- element_vec_rep_each(.element,\n times = list_sizes(data) / 3L\n )\n }\n data <- vec_rbind(!!!data)\n if (vec_size(data)) {\n element_grob(\n .element,\n x = data$x, y = data$y,\n id.lengths = vec_rep(3L, nrow(data) / 3L),\n default.units = \"native\"\n )\n }\n }, ...)\n}\n\n#####################################################\n#' @export\n`[.ggalignMarkGtable` <- function(x, i, j) {\n # subset will violate the `ggalignMarkGtable` `shape`\n # we always use the next method\n x <- remove_class(x, \"ggalignMarkGtable\")\n x$ggalign_link_data <- NULL\n NextMethod()\n}\n\n#' @importFrom ggplot2 ggproto\n#' @export\nalignpatch.ggalign_mark_plot <- function(x) {\n ggproto(NULL, PatchAlignMark, plot = x)\n}\n\n#' @importFrom ggplot2 ggproto ggproto_parent\n#' @include alignpatch-ggplot2.R\nPatchAlignMark <- ggproto(\n \"PatchAlignMark\", PatchGgplot,\n patch_gtable = function(self, theme, guides, plot = self$plot) {\n ans <- ggproto_parent(PatchGgplot, self)$patch_gtable(plot = plot)\n # re-define the draw method, we assign new class\n ans <- add_class(ans, \"ggalignMarkGtable\")\n ans$ggalign_link_data <- plot$ggalign_link_data\n ans\n },\n add_plot = function(self, gt, plot, t, l, b, r, name, z = 2L) {\n gtable_add_grob(\n gt,\n grobs = plot,\n # t = 8, l = 6, b = 14, r = 12\n # t = t + 7L, l = l + 5L, b = b - 6L, r = r - 5L,\n t = t + TOP_BORDER, l = l + LEFT_BORDER,\n name = name, z = z\n )\n },\n add_background = function(self, gt, bg, t, l, b, r, name, z = 1L) {\n gtable_add_grob(\n gt,\n grobs = bg,\n t = t + TOP_BORDER, l = l + LEFT_BORDER,\n name = name, z = z\n )\n },\n get_sizes = function(self, free = NULL, gt = self$gt) {\n ggproto_parent(PatchGgplot, self)$get_sizes(.tlbr, gt = gt)\n },\n align_border = function(self, t = NULL, l = NULL, b = NULL, r = NULL,\n gt = self$gt) {\n gt # free from alignment\n }\n)\n\n# preDraw:\n# - makeContext\n# - pushvpgp\n# - preDrawDetails: by default, do noting\n# makeContent:\n# drawDetails:\n# postDraw:\n# - postDrawDetails: by default, do noting\n# - popgrobvp\n#' @importFrom grid makeContent unit convertHeight convertWidth viewport\n#' @importFrom stats reorder\n#' @export\nmakeContent.ggalignMarkGtable <- function(x) {\n # Grab viewport information\n width <- convertWidth(unit(1, \"npc\"), \"mm\", valueOnly = TRUE)\n height <- convertHeight(unit(1, \"npc\"), \"mm\", valueOnly = TRUE)\n\n # Grab grob metadata\n plot_widths <- compute_null_width(.subset2(x, \"widths\"),\n valueOnly = TRUE\n )\n plot_widths <- scales::rescale(plot_widths, c(0, 1), from = c(0, width))\n plot_heights <- compute_null_height(.subset2(x, \"heights\"),\n valueOnly = TRUE\n )\n plot_heights <- scales::rescale(plot_heights, c(0, 1), from = c(0, height))\n\n panel_loc <- find_panel(x)\n data <- .subset2(x, \"ggalign_link_data\")\n full_data1 <- .subset2(data, \"full_data1\")\n full_data2 <- .subset2(data, \"full_data2\")\n direction <- .subset2(data, \"direction\")\n link_index_list <- .subset2(data, \"link_index\")\n data_index_list <- .subset2(data, \"data_index\")\n obs_size <- .subset2(data, \"obs_size\")\n\n # prepare output for current for loop\n coords <- vector(\"list\", 2L)\n names(coords) <- c(\"hand1\", \"hand2\")\n for (link in names(coords)) {\n link_index <- lapply(link_index_list, .subset2, link)\n data_index <- lapply(data_index_list, .subset2, link)\n # early exit and step into next cycle if no link\n if (all(vapply(link_index, is.null, logical(1L), USE.NAMES = FALSE))) {\n coords[link] <- list(link_index)\n next\n }\n full_breaks <- switch(link,\n hand1 = full_data1,\n hand2 = full_data2\n )\n\n spacing <- .subset2(data, switch(link,\n hand1 = \"spacing1\",\n hand2 = \"spacing2\"\n ))\n\n # each value represent an `observation`, for panel space, we use `NA`\n # obs arranged from left to top, and from bottom to top\n points <- unlist(vec_interleave(full_breaks, list(NA)), FALSE, FALSE)\n # remove the last panel space, shouldn't exist\n points <- points[-length(points)]\n sizes <- numeric(length(points))\n n_spacing <- length(full_breaks) - 1L\n\n # then, we define the link grobs\n if (is_horizontal(direction)) { # the link should be in left or right\n spacing <- convertHeight(spacing, \"mm\", valueOnly = TRUE)\n spacing <- scales::rescale(spacing, c(0, 1), from = c(0, height))\n sizes[is.na(points)] <- spacing\n obs_height <- (1 - spacing * n_spacing) / sum(!is.na(points))\n sizes[!is.na(points)] <- obs_height # nobs\n yend <- cumsum(sizes)\n link_x <- switch(link,\n hand1 = 0,\n hand2 = 1\n )\n # by default, the height for each observation is `1`,\n # if we define obs size, we just re-scale it\n removed <- (1 - obs_size) * obs_height\n link_coord <- data_frame0(\n x = link_x, xend = link_x,\n y = yend - sizes + removed / 2L,\n yend = yend - removed / 2L\n )\n link_coord <- vec_slice(link_coord, !is.na(points))\n\n # from bottom to the top, following the ordering of the `breaks`\n panel_index <- seq(\n from = .subset2(panel_loc, \"b\"),\n to = .subset2(panel_loc, \"t\"),\n length.out = length(link_index)\n )\n l_border <- plot_widths[seq_len(.subset2(panel_loc, \"l\") - 1L)]\n r_border <- plot_widths[-seq_len(.subset2(panel_loc, \"r\"))]\n\n # for a gtable, heights are from top to the bottom,\n # we reverse the heights\n # we have reversed the `plot_cum_heights`, so the ordering index\n # should also be reversed\n panel_index <- nrow(x) - panel_index + 1L\n panel_yend <- cumsum(rev(plot_heights))\n panel_x <- switch(link,\n hand1 = sum(l_border),\n hand2 = 1 - sum(r_border)\n )\n panel_coord <- data_frame0(\n x = panel_x,\n xend = panel_x,\n y = (panel_yend - rev(plot_heights))[panel_index],\n yend = panel_yend[panel_index]\n )\n } else { # the link should be in top or bottom\n spacing <- convertWidth(spacing, \"mm\", valueOnly = TRUE)\n spacing <- scales::rescale(spacing, c(0, 1), from = c(0, width))\n sizes[is.na(points)] <- spacing\n obs_width <- (1 - spacing * n_spacing) / sum(!is.na(points))\n sizes[!is.na(points)] <- obs_width\n xend <- cumsum(sizes)\n link_y <- switch(link,\n hand1 = 1,\n hand2 = 0\n )\n # by default, the width for each observation is `1`,\n # if we define obs size, we just re-scale it\n removed <- (1 - obs_size) * obs_width\n link_coord <- data_frame0(\n x = xend - sizes + removed / 2L,\n xend = xend - removed / 2L,\n y = link_y, yend = link_y\n )\n link_coord <- vec_slice(link_coord, !is.na(points))\n\n panel_index <- seq(\n from = .subset2(panel_loc, \"l\"),\n to = .subset2(panel_loc, \"r\"),\n length.out = length(link_index)\n )\n t_border <- plot_heights[seq_len(.subset2(panel_loc, \"t\") - 1L)]\n b_border <- plot_heights[-seq_len(.subset2(panel_loc, \"b\"))]\n panel_xend <- cumsum(plot_widths)\n panel_y <- switch(link,\n hand1 = 1 - sum(t_border),\n hand2 = sum(b_border)\n )\n panel_coord <- data_frame0(\n x = (panel_xend - plot_widths)[panel_index],\n xend = panel_xend[panel_index],\n y = panel_y, yend = panel_y\n )\n }\n hand <- switch(link,\n hand1 = switch_direction(direction, \"left\", \"top\"),\n hand2 = switch_direction(direction, \"right\", \"bottom\")\n )\n nms <- names(link_index)\n link_panels <- vec_rep_each(names(full_breaks), list_sizes(full_breaks))\n coords[[link]] <- lapply(seq_along(link_index), function(i) {\n l_index <- .subset2(link_index, i)\n if (is.null(l_index)) return(NULL) # styler: off\n d_index <- .subset2(data_index, i)\n link <- vec_slice(link_coord, l_index)\n link$link_id <- nms[i]\n link$link_panel <- reorder(\n vec_slice(link_panels, l_index), l_index,\n order = FALSE\n )\n link$link_index <- l_index\n link$.hand <- hand\n link$.index <- d_index\n panel <- vec_slice(panel_coord, i)\n list(panel = panel, link = link)\n })\n }\n coords <- vec_interleave(\n .subset2(coords, \"hand1\"),\n .subset2(coords, \"hand2\")\n )\n coords <- list_drop_empty(coords)\n draw <- .subset2(data, \"draw\")\n if (is.gList(grob <- draw(coords))) {\n grob <- gTree(children = grob)\n }\n\n if (is.grob(grob)) {\n layout <- .subset2(x, \"layout\")\n panels <- layout[\n grepl(\"^panel\", .subset2(layout, \"name\")), ,\n drop = FALSE\n ]\n x <- gtable_add_grob(\n x,\n grobs = grob,\n t = 1L, l = 1L, b = -1L, r = -1L,\n # always draw with panel area\n z = min(panels$z)\n )\n }\n NextMethod()\n}\n"], ["/ggalign/R/fortify-matrix-matrix.R", "#' Build a matrix\n#'\n#' @param data A matrix object.\n#' @inheritParams rlang::args_dots_empty\n#' @inheritParams fortify_matrix\n#' @section shape:\n#' - `upset`: [`fortify_matrix.matrix_upset()`]\n#' - `oncoplot`: [`fortify_matrix.matrix_oncoplot()`]\n#' @family fortify_matrix\n#' @export\nfortify_matrix.matrix <- fortify_matrix.waiver\n\n#' Convert the shape of a matrix for fortify method\n#'\n#' @param data A matrix.\n#' @param shape A string of `r oxford_or(c(\"upset\", \"oncoplot\"))`.\n#' @seealso\n#' - [`fortify_matrix.matrix()`]\n#' - [`fortify_matrix.matrix_upset()`]\n#' - [`fortify_matrix.matrix_oncoplot()`]\n#' @family tune\n#' @importFrom rlang arg_match0\n#' @export\ntune.matrix <- function(data, shape) {\n shape <- arg_match0(shape, c(\"upset\", \"oncoplot\"))\n if (identical(shape, \"oncoplot\")) {\n if (!is.character(data)) {\n cli_abort(\n \"{.arg data} must be a character matrix to use {shape} shape\"\n )\n }\n }\n new_tune(data, class = sprintf(\"matrix_%s\", shape))\n}\n\n#' @inherit fortify_matrix.list_upset title\n#' @description\n#' Converts a matrix suitable for creating an UpSet plot. [`tune.matrix()`]\n#' helps convert `matrix` object to a `matrix_upset` object.\n#' @param data A matrix where each row represents an element, and each column\n#' defines a set. The values in the matrix indicate whether the element is part\n#' of the set. Any non-missing value signifies that the element exists in the\n#' set.\n#' @inheritParams fortify_matrix.list_upset\n#' @inheritDotParams fortify_matrix.list_upset\n#' @inheritSection fortify_matrix.list_upset ggalign attributes\n#' @seealso [`tune.matrix()`]\n#' @family fortify_matrix\n#' @export\nfortify_matrix.matrix_upset <- function(data, ..., data_arg = NULL,\n call = NULL) {\n call <- call %||% current_call()\n data <- !is.na(tune_data(data))\n elements <- vec_seq_along(data)\n fortify_matrix.list_upset(\n lapply(seq_len(ncol(data)), function(i) {\n .subset(elements, data[, i, drop = TRUE])\n }),\n ...,\n data_arg = data_arg,\n call = call\n )\n}\n\n#' Build a Matrix for OncoPrint\n#'\n#' @description\n#' Converts a matrix suitable for creating an OncoPrint. [`tune.matrix()`]\n#' helps convert `matrix` object to a `matrix_oncoplot` object.\n#'\n#' @param data A matrix where each row represents an genes, and each column\n#' represents samples. The values in the matrix indicate whether the element is\n#' part of the set.\n#' @inheritParams fortify_matrix.MAF\n#' @section ggalign attributes:\n#' - `gene_summary`: An integer vector of the altered samples for each gene.\n#' - `sample_summary`: An integer vector of the altered genes for each sample.\n#' - `n_genes`: Total number of genes.\n#' - `n_samples`: Total number of samples.\n#'\n#' @seealso [`tune.matrix()`]\n#' @family fortify_matrix\n#' @export\nfortify_matrix.matrix_oncoplot <- function(data, ...,\n genes = NULL, n_top = NULL,\n remove_empty_genes = TRUE,\n remove_empty_samples = TRUE,\n missing_genes = \"error\",\n data_arg = NULL,\n call = NULL) {\n call <- call %||% current_call()\n rlang::check_dots_empty(call = call)\n\n # check arguments\n missing_genes <- arg_match0(\n missing_genes, c(\"error\", \"remove\"),\n error_call = call\n )\n\n data <- tune_data(data)\n alt <- !is.na(data)\n storage.mode(alt) <- \"integer\"\n gene_summary <- rowSums(alt)\n sample_summary <- colSums(alt)\n n_genes <- nrow(data)\n n_samples <- ncol(data)\n\n # filter by genes --------------------------------------\n if (!is.null(genes)) {\n genes <- vec_cast(genes, character())\n if (vec_any_missing(genes)) {\n cli_abort(\n \"{.arg genes} cannot contain missing values\",\n call = call\n )\n }\n if (vec_duplicate_any(genes)) {\n cli_abort(\n \"{.arg genes} cannot contain duplicated values\",\n call = call\n )\n }\n if (identical(missing_genes, \"remove\")) {\n genes <- genes[genes %in% rownames(data)]\n }\n if (is_empty(genes)) {\n cli_abort(\n \"No {.arg genes} remain after removing missing genes\",\n call = call\n )\n }\n index <- vec_as_location(\n genes,\n n = vec_size(data),\n names = rownames(data),\n missing = \"error\"\n )\n data <- vec_slice(data, index)\n alt <- vec_slice(alt, index)\n gene_summary <- vec_slice(gene_summary, index)\n }\n\n if (!is.null(n_top)) {\n n_top <- min(n_top, vec_size(alt))\n index <- vec_slice(\n order(rowSums(alt), decreasing = TRUE),\n seq_len(n_top)\n )\n data <- vec_slice(data, index)\n alt <- vec_slice(alt, index)\n gene_summary <- vec_slice(gene_summary, index)\n }\n\n # filter empty genes\n if (remove_empty_genes) {\n keep <- rowSums(alt) > 0L\n data <- vec_slice(data, keep)\n gene_summary <- vec_slice(gene_summary, keep)\n }\n\n # filter empty samples\n if (remove_empty_samples) {\n keep <- colSums(alt) > 0L\n data <- data[, keep, drop = FALSE]\n sample_summary <- vec_slice(sample_summary, keep)\n }\n\n ggalign_data_set(data,\n sample_summary = sample_summary,\n gene_summary = gene_summary,\n n_samples = n_samples,\n n_genes = n_genes\n )\n}\n"], ["/ggalign/R/craft-align-order.R", "#' Order observations based on weights\n#'\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' Ordering observations based on summary weights or a specified ordering\n#' character or integer index.\n#'\n#' @param weights A summary function which accepts a data and returns the\n#' weights for each observations. Alternatively, you can provide an ordering\n#' index as either an integer or a character. Since characters have been\n#' designated as character indices, if you wish to specify a function name as a\n#' string, you must enclose it with [`I()`].\n#' @param ... <[dyn-dots][rlang::dyn-dots]> Additional arguments passed to\n#' function provided in `weights` argument.\n#' @param reverse A boolean value. Should the sort order be in reverse?\n#' @param strict A boolean value indicates whether the order should be strict.\n#' If previous groups has been established, and strict is `FALSE`, this will\n#' reorder the observations in each group.\n#' @param data A `matrix`, `data frame`, or atomic vector used as the input for\n#' the `weights` function. Alternatively, you can specify a `function`\n#' (including purrr-like lambda syntax) that will be applied to the layout\n#' matrix, transforming it as necessary for weight calculations. By default, it\n#' will inherit from the layout matrix.\n#' @inheritParams align\n#' @inheritSection align Discrete Axis Alignment\n#' @examples\n#' ggheatmap(matrix(rnorm(81), nrow = 9)) +\n#' anno_left() +\n#' align_order(I(\"rowMeans\"))\n#' @importFrom ggplot2 waiver\n#' @importFrom rlang list2\n#' @export\nalign_order <- function(weights = rowMeans, ...,\n reverse = FALSE, strict = TRUE, data = NULL,\n active = NULL) {\n if (is.numeric(weights) ||\n (is.character(weights) && !inherits(weights, \"AsIs\"))) {\n # vec_duplicate_any is slight faster than `anyDuplicated`\n if (vec_any_missing(weights) || vec_duplicate_any(weights)) {\n cli_abort(paste(\n \"{.arg weights} must be an ordering numeric or character\",\n \"without missing value or ties\"\n ))\n } else if (is.numeric(weights)) {\n weights <- vec_cast(weights, integer())\n }\n if (vec_size(weights) == 0L) {\n cli_abort(\"{.arg weights} cannot be empty\")\n }\n if (!is.null(data)) {\n cli_warn(c(\n \"{.arg data} won't be used\",\n i = \"{.arg weights} is not a {.cls function}\"\n ))\n }\n } else {\n weights <- rlang::as_function(weights)\n data <- data %||% waiver()\n }\n assert_bool(strict)\n assert_bool(reverse)\n assert_active(active)\n active <- update_active(active, new_active(use = FALSE))\n align(\n align = AlignOrder,\n weights = weights,\n params = list2(...),\n reverse = reverse,\n strict = strict,\n active = active,\n data = data\n )\n}\n\n#' @importFrom ggplot2 ggproto\n#' @importFrom rlang inject is_atomic\nAlignOrder <- ggproto(\"AlignOrder\", CraftAlign,\n interact_layout = function(self, layout) {\n if (is.function(self$weights)) {\n layout <- ggproto_parent(AlignOrder2, self)$interact_layout(layout)\n } else {\n layout <- ggproto_parent(CraftAlign, self)$interact_layout(layout)\n if (is.null(layout_nobs <- .subset2(layout@design, \"nobs\"))) {\n layout@design[\"nobs\"] <- list(vec_size(self$weights))\n } else {\n assert_mismatch_nobs(\n self, layout_nobs, vec_size(self$weights),\n arg = \"weights\"\n )\n }\n self$labels <- vec_names(layout@data)\n }\n layout\n },\n compute = function(self, panel, index) {\n if (is.function(self$weights)) {\n ans <- inject(self$weights(self$data, !!!self$params))\n if (!is_atomic(ans)) {\n cli_abort(\n \"{.arg weights} must return an atomic weights\",\n call = self$call\n )\n }\n assert_mismatch_nobs(\n self, vec_size(ans), vec_size(ans),\n arg = \"weights\"\n )\n ans\n }\n },\n align = function(self, panel, index) {\n if (is.function(self$weights)) {\n index <- order(self$statistics)\n } else {\n index <- vec_as_location(\n self$weights,\n n = vec_size(self$weights),\n names = self$labels,\n missing = \"error\",\n call = self$call\n )\n }\n if (self$reverse) index <- rev(index)\n assert_reorder(self, panel, index, self$strict)\n list(panel, index)\n },\n summary_align = function(self) c(TRUE, FALSE)\n)\n"], ["/ggalign/R/link.R", "#' Define the links to connect a pair of observations\n#'\n#' @description\n#' This function allows users to define links between a pair of observations,\n#' facilitating the visualization of connections between related data points.\n#'\n#' @param .draw A function used to draw the links. The function must return a\n#' [`grob()`][grid::grob] object. If the function does not return a valid\n#' `grob`, no drawing will occur. The input data for the function should\n#' include a data frame with the coordinates of the pair of observations to\n#' be linked.\n#' @inheritParams .link_draw\n#' @seealso\n#' - [`link_line()`]\n#' - [`.link_draw()`]\n#' @importFrom rlang is_empty inject\n#' @importFrom grid gTree gList\n#' @export\nlink_draw <- function(.draw, ...) {\n if (!is.function(draw <- allow_lambda(.draw))) {\n cli_abort(\"{.arg .draw} must be a function\")\n }\n new_draw <- function(data) {\n ans <- lapply(data, draw)\n ans <- ans[vapply(ans, is.grob, logical(1L), USE.NAMES = FALSE)]\n if (!is_empty(ans)) inject(gList(!!!ans))\n }\n .link_draw(new_draw, ...)\n}\n\n#' @inherit link_draw title\n#'\n#' @description\n#' A base version of [`link_draw()`], optimized for performance. This function\n#' serves as the foundation for building other `link_*` functions that manage\n#' the drawing of links between pairs of observations.\n#'\n#' @param .draw A function used to draw the links. The function must return a\n#' [`grob()`][grid::grob] object. If the function does not return a valid\n#' `grob`, no drawing will occur. The input data for the function should be\n#' a list, where each item is a data frame containing the coordinates of\n#' the pair of observations.\n#' @inheritParams pair_links\n#' @seealso [`link_draw()`]\n#' @export\n.link_draw <- function(.draw, ...) {\n if (override_call(call <- caller_call())) {\n call <- current_call()\n }\n if (!is.function(draw <- allow_lambda(.draw))) {\n cli_abort(\"{.arg .draw} must be a function\", call = call)\n }\n links <- pair_links(...)\n structure(list(draw = draw, links = links), class = \"ggalign_link_draw\")\n}\n\n#' @export\nprint.ggalign_link_draw <- function(x, ...) {\n header <- sprintf(\"<%s>\", vec_ptype_full(x))\n cat(header, sep = \"\\n\")\n obj_print_data(.subset2(x, \"links\"))\n invisible(x)\n}\n\n#' Link the paired observations with a line\n#'\n#' @inheritParams .link_draw\n#' @param .element A [`element_line()`][ggplot2::element_line] object.\n#' Vectorized fields will be recycled to match the total number of groups, or\n#' you can wrap the element with [`I()`] to recycle to match the drawing\n#' groups. The drawing groups typically correspond to the product of the\n#' number of observations from both sides, as each pair of observations will\n#' be linked with a single line.\n#' @importFrom ggplot2 element_line\n#' @export\nlink_line <- function(..., .element = NULL) {\n assert_s3_class(.element, \"element_line\", allow_null = TRUE)\n default <- calc_element(\"ggalign.line\", complete_theme(theme_get()))\n if (is.null(.element)) {\n .element <- default\n } else {\n .element <- ggplot2::merge_element(.element, default)\n }\n ans <- .link_draw(.draw = function(data) {\n data <- lapply(data, function(d) {\n # if the link is only in one side, we do nothing\n if (vec_unique_count(.subset2(d, \".hand\")) < 2L) {\n return(NULL)\n }\n both <- .subset2(vec_split(d, .subset2(d, \".hand\")), \"val\")\n data <- cross_join(.subset2(both, 1L), .subset2(both, 2L))\n data_frame0(\n x = vec_interleave(\n (data$x.x + data$xend.x) / 2L,\n (data$x.y + data$xend.y) / 2L\n ),\n y = vec_interleave(\n (data$y.x + data$yend.x) / 2L,\n (data$y.y + data$yend.y) / 2L\n )\n )\n })\n if (inherits(.element, \"AsIs\")) {\n .element <- element_rep_len(.element,\n length.out = sum(list_sizes(data)) / 2L\n )\n } else {\n .element <- element_rep_len(.element, length.out = length(data))\n .element <- element_vec_rep_each(.element,\n times = list_sizes(data) / 2L\n )\n }\n data <- vec_rbind(!!!data)\n if (vec_size(data)) {\n element_grob(\n .element,\n x = data$x, y = data$y,\n id.lengths = vec_rep(2L, vec_size(data) / 2L),\n default.units = \"native\"\n )\n }\n }, ...)\n add_class(ans, \"ggalign_link_line\")\n}\n\n#' Link the paired observations with a quadrilateral\n#'\n#' @inheritParams .link_draw\n#' @inheritParams mark_tetragon\n#' @export\nlink_tetragon <- function(..., .element = NULL) {\n assert_s3_class(.element, \"element_polygon\", allow_null = TRUE)\n default <- calc_element(\"ggalign.polygon\", complete_theme(theme_get()))\n if (is.null(.element)) {\n .element <- default\n } else {\n .element <- ggplot2::merge_element(.element, default)\n }\n .link_draw(.draw = function(data) {\n data <- lapply(data, function(d) {\n # if the link is only in one side, we do nothing\n if (vec_unique_count(.subset2(d, \".hand\")) < 2L) {\n return(NULL)\n }\n both <- .subset2(vec_split(d, .subset2(d, \".hand\")), \"val\")\n both <- lapply(both, function(link) {\n # find the consecutive groups\n index <- .subset2(link, \"link_index\")\n oindex <- order(index)\n group <- cumsum(c(0L, diff(index[oindex])) != 1L)\n\n # restore the order\n group <- group[order(oindex)]\n\n # split link into groups\n .subset2(vec_split(link, group), \"val\")\n })\n both <- vec_expand_grid(\n hand1 = .subset2(both, 1L),\n hand2 = .subset2(both, 2L)\n )\n ans <- .mapply(function(hand1, hand2) {\n data_frame0(\n x = vec_c(\n min(hand1$x), max(hand1$xend),\n max(hand2$xend), min(hand2$x)\n ),\n y = vec_c(\n min(hand1$y), max(hand1$yend),\n max(hand2$yend), min(hand2$y)\n )\n )\n }, both, NULL)\n vec_rbind(!!!ans)\n })\n if (inherits(.element, \"AsIs\")) {\n .element <- element_rep_len(.element,\n length.out = sum(list_sizes(data)) / 4L\n )\n } else {\n .element <- element_rep_len(.element, length.out = length(data))\n .element <- element_vec_rep_each(.element,\n times = list_sizes(data) / 4L\n )\n }\n data <- vec_rbind(!!!data)\n if (vec_size(data)) {\n element_grob(\n .element,\n x = data$x, y = data$y,\n id.lengths = vec_rep(4L, vec_size(data) / 4L),\n default.units = \"native\"\n )\n }\n }, ...)\n}\n\n# preDraw:\n# - makeContext\n# - pushvpgp\n# - preDrawDetails: by default, do noting\n# makeContent:\n# drawDetails:\n# postDraw:\n# - postDrawDetails: by default, do noting\n# - popgrobvp\n#' @importFrom grid makeContent convertHeight convertWidth gList setChildren\n#' @export\nmakeContent.ggalignLinkTree <- function(x) {\n # Grab viewport information\n width <- convertWidth(unit(1, \"npc\"), \"mm\", valueOnly = TRUE)\n height <- convertHeight(unit(1, \"npc\"), \"mm\", valueOnly = TRUE)\n\n # Grab grob metadata\n full_data1 <- .subset2(x, \"full_data1\")\n full_data2 <- .subset2(x, \"full_data2\")\n direction <- .subset2(x, \"direction\")\n link_index_list <- .subset2(x, \"link_index\")\n data_index_list <- .subset2(x, \"data_index\")\n obs_size <- .subset2(x, \"obs_size\")\n\n # prepare output for current for loop\n coords <- vector(\"list\", 2L)\n names(coords) <- c(\"hand1\", \"hand2\")\n for (link in names(coords)) {\n link_index <- lapply(link_index_list, .subset2, link)\n data_index <- lapply(data_index_list, .subset2, link)\n # early exit and step into next cycle if no link\n if (all(vapply(link_index, is.null, logical(1L), USE.NAMES = FALSE))) {\n coords[link] <- list(link_index)\n next\n }\n full_breaks <- switch(link,\n hand1 = full_data1,\n hand2 = full_data2\n )\n\n spacing <- .subset2(x, switch(link,\n hand1 = \"spacing1\",\n hand2 = \"spacing2\"\n ))\n\n # each value represent an `observation`, for panel space, we use `NA`\n # obs arranged from left to top, and from bottom to top\n points <- unlist(vec_interleave(full_breaks, list(NA)), FALSE, FALSE)\n # remove the last panel space, shouldn't exist\n points <- points[-length(points)]\n sizes <- numeric(length(points))\n n_spacing <- length(full_breaks) - 1L\n\n # then, we define the link grobs\n if (is_horizontal(direction)) { # the link should be in left or right\n spacing <- convertHeight(spacing, \"mm\", valueOnly = TRUE)\n spacing <- scales::rescale(spacing, c(0, 1), from = c(0, height))\n sizes[is.na(points)] <- spacing\n obs_height <- (1 - spacing * n_spacing) / sum(!is.na(points))\n sizes[!is.na(points)] <- obs_height # nobs\n yend <- cumsum(sizes)\n link_x <- switch(link,\n hand1 = 0,\n hand2 = 1\n )\n # by default, the height for each observation is `1`,\n # if we define obs size, we just re-scale it\n removed <- (1 - obs_size) * obs_height\n link_coord <- data_frame0(\n x = link_x, xend = link_x,\n y = yend - sizes + removed / 2L,\n yend = yend - removed / 2L\n )\n link_coord <- vec_slice(link_coord, !is.na(points))\n } else { # the link should be in top or bottom\n spacing <- convertWidth(spacing, \"mm\", valueOnly = TRUE)\n spacing <- scales::rescale(spacing, c(0, 1), from = c(0, width))\n sizes[is.na(points)] <- spacing\n obs_width <- (1 - spacing * n_spacing) / sum(!is.na(points))\n sizes[!is.na(points)] <- obs_width\n xend <- cumsum(sizes)\n link_y <- switch(link,\n hand1 = 1,\n hand2 = 0\n )\n # by default, the width for each observation is `1`,\n # if we define obs size, we just re-scale it\n removed <- (1 - obs_size) * obs_width\n link_coord <- data_frame0(\n x = xend - sizes + removed / 2L,\n xend = xend - removed / 2L,\n y = link_y, yend = link_y\n )\n link_coord <- vec_slice(link_coord, !is.na(points))\n }\n hand <- switch(link,\n hand1 = switch_direction(direction, \"left\", \"top\"),\n hand2 = switch_direction(direction, \"right\", \"bottom\")\n )\n nms <- names(link_index)\n link_panels <- vec_rep_each(names(full_breaks), list_sizes(full_breaks))\n coords[[link]] <- lapply(seq_along(link_index), function(i) {\n l_index <- .subset2(link_index, i)\n if (is.null(l_index)) return(NULL) # styler: off\n d_index <- .subset2(data_index, i)\n link <- vec_slice(link_coord, l_index)\n link$link_id <- nms[i]\n link$link_panel <- reorder(\n vec_slice(link_panels, l_index), l_index,\n order = FALSE\n )\n link$link_index <- l_index\n link$.hand <- hand\n link$.index <- d_index\n link\n })\n }\n\n # hand1 - hand2\n data <- .mapply(vec_rbind, coords, NULL)\n draw <- .subset2(x, \"draw\")\n if (is.grob(grob <- draw(data))) { # wrap single grob to a gList\n grob <- gList(grob)\n }\n if (is.gList(grob)) {\n setChildren(x, grob)\n } else {\n x\n }\n}\n"], ["/ggalign/R/layout-quad-switch.R", "#' Determine the Active Context of Quad-Layout\n#'\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' - `quad_active`: Sets the active context to the `r rd_quad()` itself.\n#' - `quad_anno`: Sets the active context to the specified annotation stack\n#' based on the `position` argument.\n#' - `anno_top`: A special case of `quad_anno` with `position = \"top\"`.\n#' - `anno_left`: A special case of `quad_anno` with `position = \"left\"`.\n#' - `anno_bottom`: A special case of `quad_anno` with `position = \"bottom\"`.\n#' - `anno_right`: A special case of `quad_anno` with `position = \"right\"`.\n#'\n#' @inheritParams quad_layout\n#' @return An object that can be added to `r rd_quad()`.\n#' @export\n#' @rdname quad_active\nquad_active <- function(width = NULL, height = NULL) {\n if (!is.null(width)) width <- check_size(width)\n if (!is.null(height)) height <- check_size(height)\n structure(\n list(width = width, height = height),\n class = c(\"quad_active\", \"quad_switch\")\n )\n}\n\n#' @details\n#' By default, `quad_anno()` attempts to initialize the annotation stack layout\n#' using data from `r rd_quad()`. However, in situations where you want to use\n#' different data for the annotation stack, you can set `initialize = FALSE`\n#' and then provide a custom `stack_layout()`.\n#'\n#' @param position `r rd_quad_position(\"activated\")`.\n#' @param size A numeric value or an [`unit`][grid::unit] object to set the\n#' total `height`/`width` of the annotation stack.\n#' - If `position` is `\"top\"` or `\"bottom\"`, `size` sets the total height of\n#' the annotation.\n#' - If `position` is `\"left\"` or `\"right\"`, `size` sets the total width of the\n#' annotation.\n#' @param free_guides Override the `guides` collection behavior specified in the\n#' `r rd_quad()` for the annotation stack.\n#' @param initialize A boolean indicating whether the annotation stack should be\n#' initialized if it is not already. By default, the annotation stack layout\n#' will attempt to initialize when the data is compatible. If set to `TRUE`, and\n#' the data in `r rd_quad()` is incompatible with the annotation stack, no\n#' data will be used in the stack.\n#' @param what What should get activated in the annotation stack?\n#' `r rd_chain_what()`.\n#' @seealso [`quad_switch()`]\n#' @export\n#' @rdname quad_active\nquad_anno <- function(position, size = NULL, free_guides = waiver(),\n initialize = NULL, what = waiver()) {\n if (is.null(position)) {\n cli_abort(c(\n paste(\n \"{.arg position} must be a single string of\",\n \"{oxford_or(.TLBR)}, not `NULL`\"\n ),\n i = \"Do you want to set the active context to the `quad_layout()` with {.fn quad_active}?\"\n ))\n }\n position <- match.arg(position, .TLBR)\n quad_switch_anno(\n size = size, free_guides = free_guides,\n initialize = initialize, what = what,\n position = position\n )\n}\n\n#' @export\n#' @rdname quad_active\nanno_top <- function(size = NULL, free_guides = waiver(), initialize = NULL,\n what = waiver()) {\n quad_switch_anno(\n size = size, free_guides = free_guides,\n initialize = initialize, what = what,\n position = \"top\"\n )\n}\n\n#' @export\n#' @rdname quad_active\nanno_left <- function(size = NULL, free_guides = waiver(), initialize = NULL,\n what = waiver()) {\n quad_switch_anno(\n size = size, free_guides = free_guides,\n initialize = initialize, what = what,\n position = \"left\"\n )\n}\n\n#' @export\n#' @rdname quad_active\nanno_bottom <- function(size = NULL, free_guides = waiver(), initialize = NULL,\n what = waiver()) {\n quad_switch_anno(\n size = size, free_guides = free_guides,\n initialize = initialize, what = what,\n position = \"bottom\"\n )\n}\n\n#' @export\n#' @rdname quad_active\nanno_right <- function(size = NULL, free_guides = waiver(), initialize = NULL,\n what = waiver()) {\n quad_switch_anno(\n size = size, free_guides = free_guides,\n initialize = initialize, what = what,\n position = \"right\"\n )\n}\n\nquad_switch_anno <- function(position, size, free_guides, initialize, what,\n call = caller_call()) {\n if (!is.null(size)) size <- check_size(size, call = call)\n assert_layout_position(free_guides, call = call)\n if (!is.waive(what)) what <- check_stack_context(what, call = call)\n assert_bool(initialize, allow_null = TRUE)\n structure(\n list(\n position = position, size = size,\n free_guides = free_guides, what = what,\n initialize = initialize\n ),\n class = c(\"quad_anno\", \"quad_switch\")\n )\n}\n\n#' Initialize Quad-Layout Annotation\n#'\n#' @description\n#' `r lifecycle::badge(\"deprecated\")`\n#'\n#' This function was deprecated, you can add `stack_layout()` directly.\n#'\n#' @export\n#' @keywords internal\nquad_init <- function(position, data = waiver(), ...) {\n lifecycle::deprecate_stop(\"0.0.6\", \"quad_init()\", \"stack_layout()\")\n}\n\n#' @inherit quad_active title return\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' `quad_switch()` integrates [`quad_active()`] and [`quad_anno()`] into one\n#' function for ease of use. This function allows you to quickly change the\n#' active context of the [`quad_layout()`] and its annotations.\n#'\n#' `hmanno` is an alias for `quad_switch`, with additional arguments for\n#' backward compatibility\n#'\n#' @param position `r rd_quad_position(\"activated\")`. If `NULL`, it sets the\n#' active context to the `r rd_quad()` itself.\n#' @inheritParams rlang::args_dots_empty\n#' @inheritParams quad_active\n#' @examples\n#' ggheatmap(matrix(rnorm(81), nrow = 9)) +\n#' anno_top() +\n#' align_dendro()\n#' @importFrom ggplot2 waiver\n#' @seealso [`quad_active()`]/[`quad_anno()`]\n#' @export\nquad_switch <- function(position = NULL, size = NULL,\n width = NULL, height = NULL, free_guides = waiver(),\n initialize = NULL, what = waiver()) {\n if (is.null(position)) {\n quad_active(width = width, height = height)\n } else {\n position <- match.arg(position, .TLBR)\n quad_switch_anno(\n size = size,\n free_guides = free_guides, what = what,\n initialize = initialize,\n position = position\n )\n }\n}\n\n#' @inheritParams heatmap_layout\n#' @export\n#' @rdname quad_switch\nhmanno <- quad_switch\n"], ["/ggalign/R/alignpatch-align_plots.R", "#' Arrange multiple plots into a grid\n#'\n#' @param ... <[dyn-dots][rlang::dyn-dots]> A list of plots, ususally the\n#' ggplot object. Use `NULL` to indicate an empty spacer.\n#' @param ncol,nrow The dimensions of the grid to create - if both are `NULL` it\n#' will use the same logic as [`facet_wrap()`][ggplot2::facet_wrap] to set the\n#' dimensions\n#' @param byrow If `FALSE` the plots will be filled in in column-major order.\n#' @param widths,heights The relative widths and heights of each column and row\n#' in the grid. Will get repeated to match the dimensions of the grid. The\n#' special value of `NA` will behave as `1null` unit unless a fixed aspect plot\n#' is inserted in which case it will allow the dimension to expand or contract\n#' to match the aspect ratio of the content.\n#' @param area Specification of the location of areas in the layout. Can\n#' either be specified as a text string or by concatenating calls to\n#' [`area()`] together.\n#' @param guides A string with one or more of `r oxford_and(c(.tlbr, \"i\"))`\n#' indicating which side of guide legends should be collected. Defaults to\n#' [`waiver()`][ggplot2::waiver()], which inherits from the parent layout. If\n#' there is no parent layout, or if `NULL` is provided, no guides will be\n#' collected.\n#' @param theme A [`theme()`][ggplot2::theme] object used to customize various\n#' elements of the layout. By default, the theme will inherit from the parent\n#' `layout`.\n#' @param design An alias for `area`, retained for backward compatibility.\n#' @return An `AlignPatches` object.\n#' @seealso\n#' - [layout_design()]\n#' - [layout_title()]\n#' - [layout_theme()]\n#' @examples\n#' # directly copied from patchwork\n#' p1 <- ggplot(mtcars) +\n#' geom_point(aes(mpg, disp))\n#' p2 <- ggplot(mtcars) +\n#' geom_boxplot(aes(gear, disp, group = gear))\n#' p3 <- ggplot(mtcars) +\n#' geom_bar(aes(gear)) +\n#' facet_wrap(~cyl)\n#' p4 <- ggplot(mtcars) +\n#' geom_bar(aes(carb))\n#' p5 <- ggplot(mtcars) +\n#' geom_violin(aes(cyl, mpg, group = cyl))\n#'\n#' # Either add the plots as single arguments\n#' align_plots(p1, p2, p3, p4, p5)\n#'\n#' # Or use bang-bang-bang to add a list\n#' align_plots(!!!list(p1, p2, p3), p4, p5)\n#'\n#' # Match plots to areas by name\n#' area <- \"#BB\n#' AA#\"\n#' align_plots(B = p1, A = p2, area = area)\n#'\n#' # Compare to not using named plot arguments\n#' align_plots(p1, p2, area = area)\n#' @export\nalign_plots <- function(..., ncol = NULL, nrow = NULL, byrow = TRUE,\n widths = NA, heights = NA, area = NULL,\n guides = waiver(), theme = NULL, design = NULL) {\n plots <- rlang::dots_list(..., .ignore_empty = \"all\", .named = NULL)\n nms <- names(plots)\n area <- area %||% design\n if (!is.null(nms) && is.character(area)) {\n area_names <- unique(trimws(.subset2(strsplit(area, \"\"), 1L)))\n area_names <- sort(vec_set_difference(area_names, c(\"\", \"#\")))\n if (all(nms %in% area_names)) {\n plot_list <- vector(\"list\", length(area_names))\n names(plot_list) <- area_names\n plot_list[nms] <- plots\n plots <- plot_list\n }\n }\n\n for (plot in plots) {\n if (!has_method(plot, \"alignpatch\", default = FALSE)) {\n cli_abort(\"Cannot align {.obj_type_friendly {plot}}\")\n }\n }\n\n # setup layout parameters\n layout <- layout_design(\n ncol = ncol, nrow = nrow, byrow = byrow,\n widths = widths, heights = heights, area = area,\n guides = guides\n )\n AlignPatches(plots = plots, layout = layout, theme = theme)\n}\n\n#' @importFrom ggplot2 is_theme\n#' @importFrom S7 new_object S7_object prop prop<-\nAlignPatches <- S7::new_class(\"AlignPatches\",\n properties = list(\n plots = S7::new_property(\n S7::class_list,\n setter = function(self, value) {\n if (!is.null(prop(self, \"plots\"))) {\n cli_abort(\"'@plots' is read-only\")\n }\n prop(self, \"plots\", check = FALSE) <- value\n self\n }\n ),\n layout = S7::new_property(\n S7::class_list,\n setter = function(self, value) {\n if (!inherits(value, \"layout_design\")) {\n cli_abort(\"'@layout' must be a {.fn layout_design} object\")\n }\n old <- prop(self, \"layout\") %||% list(\n ncol = NULL, nrow = NULL, byrow = TRUE,\n widths = NA, heights = NA, area = NULL,\n guides = waiver()\n )\n guides <- .subset2(value, \"guides\")\n value$guides <- NULL # guides need special consideration\n old <- update_non_waive(old, value)\n if (is.null(guides) || is.waive(guides)) {\n old[\"guides\"] <- list(guides)\n } else if (!identical(guides, NA)) {\n old[\"guides\"] <- list(setup_guides(guides))\n }\n prop(self, \"layout\", check = FALSE) <- old\n self\n }\n ),\n titles = S7::new_property(\n S7::class_list,\n setter = function(self, value) {\n if (!inherits(value, \"layout_title\")) {\n cli_abort(\"'@titles' must be a {.fn layout_title} object'\")\n }\n old <- prop(self, \"titles\") %||%\n list(title = NULL, subtitle = NULL, caption = NULL)\n prop(self, \"titles\", check = FALSE) <- update_non_waive(\n old, value\n )\n self\n }\n ),\n theme = S7::new_property(\n S7::class_any,\n setter = function(self, value) {\n if (!is.null(value) && !is_theme(value)) {\n cli_abort(\"'@theme' must be a {.cls theme} object'\")\n }\n if (is.null(prop(self, \"theme\")) || is.null(value)) {\n prop(self, \"theme\", check = FALSE) <- value\n } else {\n prop(self, \"theme\", check = FALSE) <- prop(self, \"theme\") +\n value\n }\n self\n },\n default = NULL\n )\n ),\n constructor = function(plots = list(), layout = NULL,\n titles = NULL, theme = NULL) {\n out <- new_object(\n S7_object(),\n plots = plots,\n layout = layout %||% layout_design(),\n titles = titles %||% layout_title(),\n theme = theme\n )\n # for backward compatibility\n add_class(out, \"alignpatches\")\n }\n)\n\n#' @importFrom rlang caller_env\nlocal(\n S7::method(`+`, list(AlignPatches, S7::class_any)) <-\n function(e1, e2) {\n # Get the name of what was passed in as e2, and pass along so that\n # it can be displayed in error messages\n if (missing(e2)) {\n cli_abort(c(\n \"Cannot use {.code +} with a single argument.\",\n \"i\" = \"Did you accidentally put {.code +} on a new line?\"\n ))\n }\n e2name <- deparse(substitute(e2, env = caller_env(2)))\n alignpatches_add(e2, e1, e2name)\n }\n)\n\n#' @importFrom S7 S7_dispatch\nalignpatches_add <- S7::new_generic(\n \"alignpatches_add\", \"object\",\n function(object, patches, objectname) S7_dispatch()\n)\n\nS7::method(alignpatches_add, S7::class_any) <-\n function(object, patches, objectname) {\n if (is.null(object)) return(patches) # styler: off\n cli_abort(c(\n \"Cannot add {objectname}\",\n \"x\" = \"Only other layout elements or compatible objects can be added.\"\n ))\n }\n\n#############################################################\n#' Define the grid to compose plots in\n#'\n#' To control how different plots are laid out, you need to add a layout design\n#' specification. If you are nesting grids, the layout is scoped to the current\n#' nesting level.\n#' @inheritParams align_plots\n#' @return A `layout_design` object.\n#' @examples\n#' p1 <- ggplot(mtcars) +\n#' geom_point(aes(mpg, disp))\n#' p2 <- ggplot(mtcars) +\n#' geom_boxplot(aes(gear, disp, group = gear))\n#' p3 <- ggplot(mtcars) +\n#' geom_bar(aes(gear)) +\n#' facet_wrap(~cyl)\n#' align_plots(p1, p2, p3) +\n#' layout_design(nrow = 1L)\n#' align_plots(p1, p2, p3) +\n#' layout_design(ncol = 1L)\n#' @importFrom ggplot2 waiver\n#' @export\nlayout_design <- function(ncol = waiver(), nrow = waiver(), byrow = waiver(),\n widths = waiver(), heights = waiver(),\n area = waiver(), guides = NA, design = waiver()) {\n if (!is.waive(ncol)) {\n assert_number_whole(ncol, min = 1, allow_na = TRUE, allow_null = TRUE)\n }\n if (!is.waive(nrow)) {\n assert_number_whole(nrow, min = 1, allow_na = TRUE, allow_null = TRUE)\n }\n if (!is.waive(byrow)) assert_bool(byrow)\n area <- area %|w|% design\n if (!is.waive(area)) area <- as_areas(area)\n if (!identical(guides, NA) && !is.waive(guides) && !is.null(guides)) {\n assert_guides(guides)\n }\n structure(\n list(\n ncol = ncol,\n nrow = nrow,\n byrow = byrow,\n widths = widths,\n heights = heights,\n area = area,\n guides = guides\n ),\n class = c(\"layout_design\", \"plot_layout\")\n )\n}\n\nS3_layout_design <- S7::new_S3_class(\"layout_design\")\n\nS7::method(alignpatches_add, S3_layout_design) <-\n function(object, patches, objectname) {\n patches@layout <- object\n patches\n }\n\nS7::method(alignpatches_add, S7::new_S3_class(\"plot_layout\")) <-\n function(object, patches, objectname) {\n object$area <- object$design # pathwork use `design`\n object <- .subset(object, names(layout_design()))\n if (is.waive(object$guides)) {\n object$guides <- NA\n } else if (identical(object$guides, \"auto\")) {\n object$guides <- waiver()\n } else if (identical(object$guides, \"collect\")) {\n object$guides <- \"tlbr\"\n } else if (identical(object$guides, \"keep\")) {\n object[\"guides\"] <- list(NULL)\n }\n alignpatches_add(add_class(object, \"layout_design\"), patches)\n }\n\n##############################################################\n#' Annotate the whole layout\n#'\n#' @inheritParams ggplot2::labs\n#' @return A `layout_title` object.\n#' @examples\n#' p1 <- ggplot(mtcars) +\n#' geom_point(aes(mpg, disp))\n#' p2 <- ggplot(mtcars) +\n#' geom_boxplot(aes(gear, disp, group = gear))\n#' p3 <- ggplot(mtcars) +\n#' geom_bar(aes(gear)) +\n#' facet_wrap(~cyl)\n#' align_plots(p1, p2, p3) +\n#' layout_title(title = \"I'm title\")\n#' @importFrom ggplot2 waiver\n#' @export\nlayout_title <- function(title = waiver(), subtitle = waiver(),\n caption = waiver()) {\n if (!is.waive(title)) assert_string(title, allow_null = TRUE)\n if (!is.waive(subtitle)) assert_string(subtitle, allow_null = TRUE)\n if (!is.waive(caption)) assert_string(caption, allow_null = TRUE)\n structure(\n list(title = title, subtitle = subtitle, caption = caption),\n class = c(\"layout_title\", \"plot_annotation\")\n )\n}\n\nS3_layout_title <- S7::new_S3_class(\"layout_title\")\n\nS7::method(alignpatches_add, S3_layout_title) <-\n function(object, patches, objectname) {\n patches@titles <- object\n patches\n }\n\n##############################################################\n#' Modify theme of the layout\n#'\n#' @inherit ggplot2::theme\n#' @param ... A [`theme()`][ggplot2::theme] object or additional element\n#' specifications not part of base ggplot2. In general, these should also be\n#' defined in the `element tree` argument. [`Splicing`][rlang::splice] a list\n#' is also supported.\n#'\n#' @details\n#' A [`theme()`][ggplot2::theme] object used to customize various elements of\n#' the layout, including `guides`, `title`, `subtitle`, `caption`, `margins`,\n#' `panel.border`, and `background`. By default, the theme will inherit from the\n#' parent `layout`.\n#'\n#' - `guides`, `panel.border`, and `background` will always be used even for the\n#' nested `alignpatches` object.\n#'\n#' - `title`, `subtitle`, `caption`, and `margins` will be added for the\n#' top-level `alignpatches` object only.\n#'\n#' @examples\n#' p1 <- ggplot(mtcars) +\n#' geom_point(aes(mpg, disp))\n#' p2 <- ggplot(mtcars) +\n#' geom_boxplot(aes(gear, disp, group = gear))\n#' p3 <- ggplot(mtcars) +\n#' geom_bar(aes(gear)) +\n#' facet_wrap(~cyl)\n#' align_plots(\n#' p1 + theme(plot.background = element_blank()),\n#' p2 + theme(plot.background = element_blank()),\n#' p3 + theme(plot.background = element_blank())\n#' ) +\n#' layout_theme(plot.background = element_rect(fill = \"red\"))\n#' @importFrom ggplot2 theme\n#' @export\nlayout_theme <- rlang::new_function(\n # We utilize editor completion by listing all `theme()` arguments here.\n # By placing `...` at the beginning, we can check if the first\n # following argument is a `theme()` object rather than individual theme\n # elements.\n c(\n rlang::exprs(... = ),\n .subset(\n rlang::fn_fmls(theme),\n vec_set_difference(names(rlang::fn_fmls(theme)), \"...\")\n )\n ),\n quote({\n elements <- ggfun(\"find_args\")(..., complete = NULL, validate = NULL)\n ans <- theme(!!!elements)\n th <- NULL\n for (i in seq_len(...length())) {\n if (inherits(t <- ...elt(i), \"theme\")) {\n th <- ggfun(\"add_theme\")(th, t)\n }\n }\n add_class(ggfun(\"add_theme\")(th, ans), \"layout_theme\")\n })\n)\n\nS3_layout_theme <- S7::new_S3_class(\"layout_theme\")\n\nS7::method(alignpatches_add, S3_layout_theme) <-\n function(object, patches, objectname) {\n patches@theme <- object\n patches\n }\n\nS7::method(alignpatches_add, S7::new_S3_class(\"plot_annotation\")) <-\n function(object, patches, objectname) {\n patches@titles <- .subset(object, names(layout_title()))\n patches@theme <- .subset2(object, \"theme\")\n patches\n }\n\nupdate_layout_theme <- function(old, new) {\n if (is.null(old) || is.null(new)) return(new) # styler: off\n old + new\n}\n\n#' Add layout annotation (internal use)\n#'\n#' This function is a placeholder for future extensions.\n#' If you're trying to apply a theme, use [layout_theme()] instead.\n#'\n#' @param ... Currently unused. May accept a theme in the future.\n#' @param theme A theme object. If not `waiver()`, an error will be raised.\n#'\n#' @return None. This function is used for input validation.\n#' @importFrom ggplot2 is_theme\n#' @export\n#' @keywords internal\nlayout_annotation <- function(..., theme = waiver()) {\n if (is_theme(...elt(1)) || !is.waive(theme)) {\n cli_abort(\"Please use {.fn layout_theme} instead; {.fn layout_annotation} is reserved for future extensions.\")\n }\n}\n"], ["/ggalign/R/ggmark.R", "#' Add a plot to annotate selected observations\n#'\n#' @param mark A [`mark_draw()`] object to define how to draw the links. Like\n#' [`mark_line()`], [`mark_tetragon()`]. Note the names of the pair links will\n#' be used to define the panel names so must be unique.\n#' @inheritParams ggalign\n#' @param group1,group2 A single boolean value indicating whether to use the\n#' panel group information from the layout as the paired groups. By default,\n#' if no specific observations are selected in `mark`, `ggmark()` will\n#' automatically connect all observations and group them according to the\n#' layout's defined groups.\n#' @param obs_size A single numeric value that indicates the size of a single\n#' observation, ranging from `(0, 1]`.\n#' @section ggplot2 specification:\n#' `ggmark` initializes a ggplot object. The underlying data is created using\n#' [`fortify_data_frame()`]. Please refer to it for more details.\n#'\n#' In addition, the following columns will be added to the data frame:\n#'\n#' - `.panel`: the panel for the aligned axis. It means `x-axis` for vertical\n#' stack layout (including top and bottom annotation), `y-axis` for\n#' horizontal stack layout (including left and right annotation).\n#'\n#' - `.names` ([`vec_names()`][vctrs::vec_names]) and `.index`\n#' ([`vec_size()`][vctrs::vec_size()]/[`NROW()`]): a character names (only\n#' applicable when names exists) and an integer of index of the original\n#' data.\n#'\n#' - `.hand`: A factor with levels `c(\"left\", \"right\")` for horizontal stack\n#' layouts, or `c(\"top\", \"bottom\")` for vertical stack layouts, indicating\n#' the position of the linked observations.\n#'\n#' @examples\n#' set.seed(123)\n#' small_mat <- matrix(rnorm(56), nrow = 7)\n#' rownames(small_mat) <- paste0(\"row\", seq_len(nrow(small_mat)))\n#' colnames(small_mat) <- paste0(\"column\", seq_len(ncol(small_mat)))\n#'\n#' # mark_line\n#' ggheatmap(small_mat) +\n#' theme(axis.text.x = element_text(hjust = 0, angle = -60)) +\n#' anno_right() +\n#' align_kmeans(3L) +\n#' ggmark(mark_line(I(1:3) ~ NULL)) +\n#' geom_boxplot(aes(.names, value)) +\n#' theme(plot.margin = margin(l = 0.1, t = 0.1, unit = \"npc\"))\n#'\n#' # mark_tetragon\n#' ggheatmap(small_mat) +\n#' theme(axis.text.x = element_text(hjust = 0, angle = -60)) +\n#' anno_right() +\n#' align_kmeans(3L) +\n#' ggmark(mark_tetragon(I(1:3) ~ NULL)) +\n#' geom_boxplot(aes(.names, value)) +\n#' theme(plot.margin = margin(l = 0.1, t = 0.1, unit = \"npc\"))\n#' @importFrom rlang list2\n#' @export\nggmark <- function(mark, data = waiver(), mapping = aes(), ...,\n group1 = NULL, group2 = NULL,\n obs_size = 1, size = NULL, active = NULL) {\n if (!inherits(mark, \"ggalign_mark_draw\")) {\n cli_abort(\"{.arg mark} must be a {.fn mark_draw} object\")\n }\n assert_obs_size(obs_size)\n assert_active(active)\n active <- update_active(active, new_active(use = TRUE))\n assert_bool(group1, allow_null = TRUE)\n assert_bool(group2, allow_null = TRUE)\n new_craftbox(\n MarkGg,\n # fields added to `MarkGg`\n input_data = allow_lambda(data), # used by AlignGg\n params = list2(...), # used by AlignGg\n mark = mark, # used by MarkGg\n group1 = group1, group2 = group2,\n obs_size = obs_size,\n\n # slot\n plot = ggplot(mapping = mapping),\n size = size,\n schemes = default_schemes(data, th = theme_panel_border()),\n active = active\n )\n}\n\n#' @importFrom ggplot2 ggproto ggplot margin element_rect\nMarkGg <- ggproto(\"MarkGg\", Craftsman,\n free_facet = TRUE,\n free_limits = TRUE,\n interact_layout = function(self, layout) {\n layout_name <- self$layout_name\n if (!self$in_linear) { # only used for linear coordinate\n cli_abort(c(\n sprintf(\n \"Cannot add %s to %s\",\n object_name(self), layout_name\n ),\n i = sprintf(\n \"%s can only be used in linear layout\",\n object_name(self)\n )\n ))\n }\n if (is_layout_continuous(layout)) { # only used for discrete variable\n # ggmark special for discrete variables\n cli_abort(c(\n sprintf(\"Cannot add %s to %s\", object_name(self), layout_name),\n i = sprintf(\"%s cannot align discrete variables\", layout_name)\n ))\n }\n ans <- ggproto_parent(AlignGg, self)$interact_layout(layout)\n self$labels0 <- self$labels # CrossMark uses `labels0`\n ans\n },\n build_plot = function(self, plot, design, extra_design = NULL,\n previous_design = NULL) {\n if (is.null(.subset2(design, \"nobs\"))) {\n cli_abort(sprintf(\n \"you must initialize %s before drawing %s\",\n self$layout_name, object_name(self)\n ), call = self$call)\n }\n mark <- self$mark\n\n # parse links --------------------------------------------\n links <- .subset2(mark, \"links\")\n group1 <- self$group1\n group2 <- self$group2\n position <- self$position\n if (is_empty(links) && is.null(group1) && is.null(group2)) {\n # guess group1 and group2 from position\n if (is.null(position)) { # a normal stack layout\n group1 <- TRUE\n } else if (any(position == c(\"top\", \"left\"))) {\n group2 <- TRUE\n } else {\n group1 <- TRUE\n }\n }\n full_data <- split(\n seq_len(.subset2(design, \"nobs\")),\n .subset2(design, \"panel\")\n )\n if (isTRUE(group1) && isTRUE(group2)) {\n extra_links <- mapply(function(l1, l2) {\n new_pair_link(I(l1), I(l2))\n }, full_data, full_data, SIMPLIFY = FALSE)\n } else if (isTRUE(group1)) {\n extra_links <- lapply(full_data, function(l) {\n new_pair_link(hand1 = I(l))\n })\n } else if (isTRUE(group2)) {\n extra_links <- lapply(full_data, function(l) {\n new_pair_link(hand2 = I(l))\n })\n } else {\n extra_links <- NULL\n }\n\n # unlock the object\n self$unlock()\n self$mark$links <- vec_c(extra_links, links)\n on.exit(self$mark <- mark, add = TRUE) # restore the original `mark`\n on.exit(self$lock(), add = TRUE)\n\n # setup the plot\n plot <- ggproto_parent(CrossMark, self)$build_plot(\n plot,\n design,\n extra_design,\n previous_design %||% design\n )\n plot_data <- plot$data\n\n # prepare data for the plot ------------------------------\n if (!is.null(data <- self$data)) {\n plot_data <- inner_join(plot_data, data, by = \".index\")\n }\n gguse_data(plot, ggalign_data_restore(plot_data, data))\n },\n finish_plot = function(self, plot, schemes, theme) {\n ggproto_parent(CrossMark, self)$finish_plot(plot, schemes, theme)\n },\n summary = function(self, plot) {\n header <- ggproto_parent(Craftsman, self)$summary(plot)\n c(header, \" Add plot to annotate observations\")\n }\n)\n"], ["/ggalign/R/craft-align-dendrogram.R", "#' Plot dendrogram tree\n#'\n#' @param ... <[dyn-dots][rlang::dyn-dots]> Additional arguments passed to\n#' [`geom_segment()`][ggplot2::geom_segment].\n#' @param plot_dendrogram A boolean value indicates whether plot the dendrogram\n#' tree.\n#' @param plot_cut_height A boolean value indicates whether plot the cut height.\n#' @section ggplot2 specification:\n#' `align_dendro` initializes a ggplot `data` and `mapping`.\n#'\n#' The internal `ggplot` object will always use a default mapping of\n#' `aes(x = .data$x, y = .data$y)`.\n#'\n#' The default ggplot data is the `node` coordinates with `edge` data attached\n#' in [`ggalign`][ggalign_attr()] attribute, in addition, a\n#' [`geom_segment`][ggplot2::geom_segment] layer with a data frame of the `edge`\n#' coordinates will be added when `plot_dendrogram = TRUE`.\n#'\n#' See [`fortify_data_frame.dendrogram()`] for details.\n#' @param merge_dendrogram A single boolean value, indicates whether we should\n#' merge multiple dendrograms, only used when previous groups have been\n#' established. Default: `FALSE`.\n#' @inheritParams align_hclust\n#' @inheritParams fortify_data_frame.dendrogram\n#' @inheritParams ggalign\n#' @inheritSection align Discrete Axis Alignment\n#' @examples\n#' # align_dendro will always add a plot area\n#' ggheatmap(matrix(rnorm(81), nrow = 9)) +\n#' anno_top() +\n#' align_dendro()\n#' ggheatmap(matrix(rnorm(81), nrow = 9)) +\n#' anno_top() +\n#' align_dendro(k = 3L)\n#'\n#' @importFrom ggplot2 aes\n#' @importFrom rlang list2\n#' @export\nalign_dendro <- function(mapping = aes(), ...,\n distance = \"euclidean\",\n method = \"complete\",\n use_missing = \"pairwise.complete.obs\",\n reorder_dendrogram = FALSE,\n merge_dendrogram = FALSE,\n reorder_group = FALSE,\n k = NULL, h = NULL, cutree = NULL,\n plot_dendrogram = TRUE,\n plot_cut_height = NULL, root = NULL,\n center = FALSE, type = \"rectangle\",\n size = NULL, data = NULL,\n no_axes = NULL, active = NULL) {\n assert_bool(plot_cut_height, allow_null = TRUE)\n assert_bool(merge_dendrogram)\n\n # setup the default value for `plot_cut_height`\n plot_cut_height <- plot_cut_height %||% (\n # we by default don't draw the height of the user-provided cutree\n # since function like `dynamicTreeCut` will merge tree\n (!is.null(k) || !is.null(h)) && is.null(cutree)\n )\n plot <- ggplot(mapping = mapping)\n if (plot_dendrogram) {\n plot <- plot + ggplot2::geom_segment(\n mapping = aes(\n x = .data$x, y = .data$y,\n xend = .data$xend, yend = .data$yend\n ),\n ...,\n stat = \"identity\",\n data = function(data) ggalign_attr(data, \"edge\")\n )\n }\n assert_active(active)\n active <- update_active(active, new_active(use = TRUE))\n .align_hclust(\n align = AlignDendro,\n distance = distance,\n method = method,\n use_missing = use_missing,\n merge_dendro = merge_dendrogram,\n plot_cut_height = plot_cut_height,\n type = type, root = root, center = center,\n reorder_dendrogram = reorder_dendrogram,\n reorder_group = reorder_group,\n schemes = default_schemes(th = theme_no_strip()),\n k = k, h = h, cutree = cutree, data = data, active = active,\n size = size, no_axes = no_axes, plot = plot\n )\n}\n\n#' @importFrom ggplot2 aes ggplot\n#' @importFrom rlang inject\n#' @include craft-align-hclust.R\nAlignDendro <- ggproto(\"AlignDendro\", AlignHclust,\n setup_plot = function(self, plot) {\n ggadd_default(plot, aes(x = .data$x, y = .data$y)) + switch_direction(\n self$direction,\n ggplot2::labs(x = \"height\"),\n ggplot2::labs(y = \"height\")\n )\n },\n build_plot = function(self, plot, design, extra_design = NULL,\n previous_design = NULL) {\n plot_cut_height <- self$plot_cut_height\n center <- self$center\n type <- self$type\n root <- self$root\n panel <- .subset2(design, \"panel\")\n index <- .subset2(design, \"index\")\n\n statistics <- .subset2(self, \"statistics\")\n direction <- self$direction\n priority <- switch_direction(direction, \"left\", \"right\")\n dendrogram_panel <- self$panel[index]\n if (!is.null(dendrogram_panel) &&\n # we allow to change the panel level name, but we prevent\n # from changing the underlying factor level (the underlying\n # ordering)\n !all(as.integer(dendrogram_panel) == as.integer(panel))) {\n cli_abort(\"you cannot do sub-splitting in dendrogram groups\")\n }\n\n if (self$multiple_tree) {\n branches <- levels(panel)\n data <- vector(\"list\", length(statistics))\n start <- 0L\n for (i in seq_along(data)) {\n tree <- .subset2(statistics, i)\n n <- stats::nobs(tree)\n end <- start + n\n data[[i]] <- fortify_data_frame(\n tree,\n priority = priority,\n center = center,\n type = type,\n leaf_pos = seq(start + 1L, end),\n leaf_braches = rep_len(.subset(branches, i), n),\n reorder_branches = FALSE,\n root = root,\n double = TRUE,\n call = self$call\n )\n start <- end\n }\n data <- lapply(\n list(\n node = data,\n edge = lapply(data, ggalign_attr, \"edge\")\n ),\n function(dat) {\n ans <- vec_rbind(!!!dat, .names_to = \"parent\")\n ans$.panel <- factor(.subset2(ans, \".panel\"), branches)\n ans\n }\n )\n edge <- .subset2(data, \"edge\")\n node <- .subset2(data, \"node\")\n } else {\n if (nlevels(panel) > 1L && type == \"triangle\" && self$in_linear) {\n cli_warn(c(paste(\n \"{.arg type} of {.arg triangle}\",\n \"is not well support for facet dendrogram\"\n ), i = \"will use {.filed rectangle} dendrogram instead\"))\n type <- \"rectangle\"\n }\n data <- fortify_data_frame(\n statistics,\n priority = priority,\n center = center,\n type = type,\n leaf_braches = as.character(panel),\n # panel has been reordered by the dendrogram index\n reorder_branches = FALSE,\n root = root,\n double = TRUE,\n call = self$call\n )\n edge <- ggalign_attr(data, \"edge\")\n node <- data\n }\n\n # add names\n if (!is.null(self$labels)) {\n node$.names <- .subset(self$labels, .subset2(node, \".index\"))\n }\n if (is_horizontal(direction)) {\n edge <- rename(\n edge,\n c(x = \"y\", xend = \"yend\", y = \"x\", yend = \"xend\")\n )\n node <- rename(node, c(x = \"y\", y = \"x\"))\n }\n\n # we do some tricks, since ggplot2 won't remove the attributes\n # we attach the `edge` data\n plot <- gguse_data(plot, ggalign_data_set(node, edge = edge))\n\n if (plot_cut_height && !is.null(height <- .subset2(self, \"height\"))) {\n plot <- plot +\n switch_direction(\n direction,\n ggplot2::geom_vline(\n xintercept = height, linetype = \"dashed\"\n ),\n ggplot2::geom_hline(\n yintercept = height, linetype = \"dashed\"\n )\n )\n }\n position <- .subset2(self, \"position\")\n if (!self$in_linear || # for circular layout\n # for bottom annotation, reverse y-axis\n (!is.null(position) && position == \"bottom\")) {\n plot <- reverse_continuous_axis(plot, \"y\")\n } else if (!is.null(position) && position == \"left\") {\n # for left annotation, reverse x-axis\n plot <- reverse_continuous_axis(plot, \"x\")\n }\n\n # always turn off clip, this is what dendrogram dependends on\n old_coord <- plot$coordinates\n if (!identical(old_coord$clip, \"off\")) {\n # to prevent from changing the input of user.\n plot$coordinates <- ggproto(NULL, old_coord, clip = \"off\")\n }\n plot\n }\n)\n\ntree_one_node <- function(index, label) {\n structure(\n index,\n class = \"dendrogram\",\n leaf = TRUE,\n height = 0,\n label = label,\n members = 1L\n )\n}\n\n# this function won't set the right `midpoint`, but `dendrogram_data` function\n# won't use it, so, it has no hurt to use.\nmerge_dendrogram <- function(parent, children) {\n if (is.null(parent)) { # if no parent, call the merge function from `stats`\n return(Reduce(function(x, y) {\n merge(x, y, adjust = \"none\")\n }, children))\n }\n children_heights <- vapply(\n children, attr, numeric(1L), \"height\",\n USE.NAMES = FALSE\n )\n parent_branch_heights <- tree_branch_heights(parent)\n cutoff_height <- max(children_heights) + min(parent_branch_heights) * 0.5\n .merge_dendrogram <- function(dend) {\n if (stats::is.leaf(dend)) { # base version, leaf should be the index\n .subset2(children, dend)\n } else { # for a branch, we should update the members, height\n attrs <- attributes(dend)\n # we recursively run for each node of current branch\n dend <- lapply(dend, .merge_dendrogram)\n heights <- vapply(dend, attr, numeric(1L), \"height\",\n USE.NAMES = FALSE\n )\n n_members <- vapply(dend, attr, integer(1L), \"members\",\n USE.NAMES = FALSE\n )\n # we update height and members\n attrs$height <- .subset2(attrs, \"height\") + max(heights)\n attrs$members <- sum(n_members)\n attributes(dend) <- attrs\n dend\n }\n }\n ans <- .merge_dendrogram(parent)\n attr(ans, \"cutoff_height\") <- cutoff_height\n ans\n}\n\n#' @importFrom stats reorder\nreorder_dendrogram <- function(dend, wts) {\n if (inherits(dend, \"hclust\")) dend <- stats::as.dendrogram(dend)\n reorder(x = dend, wts = wts, agglo.FUN = mean)\n}\n\ntree_branch_heights <- function(dend) {\n if (stats::is.leaf(dend)) {\n return(NULL)\n } else {\n c(\n attr(dend, \"height\"),\n unlist(lapply(dend, tree_branch_heights), FALSE, FALSE)\n )\n }\n}\n"], ["/ggalign/R/alignpatch-inset.R", "#' Create a ggplot inset\n#'\n#' @inheritParams ggwrap\n#' @return A `patch_inset` object, which can be added in ggplot.\n#' @inherit patch seealso\n#' @examples\n#' library(grid)\n#' p1 <- ggplot(mtcars) +\n#' geom_point(aes(mpg, disp))\n#' p2 <- ggplot(mtcars) +\n#' geom_boxplot(aes(gear, disp, group = gear))\n#' p1 + inset(p2, vp = viewport(0.6, 0.6,\n#' just = c(0, 0), width = 0.4, height = 0.4\n#' ))\n#' @export\ninset <- function(\n plot,\n ...,\n align = \"panel\",\n on_top = TRUE,\n clip = TRUE,\n vp = NULL) {\n make_inset(\n plot = plot,\n ...,\n align = align,\n on_top = on_top,\n clip = clip,\n vp = vp\n )\n}\n\n#' @importFrom grid editGrob\n#' @importFrom rlang arg_match0\nmake_inset <- function(\n plot,\n ...,\n align,\n on_top,\n clip,\n vp,\n call = caller_call()) {\n assert_bool(on_top, call = call)\n align <- arg_match0(align, c(\"panel\", \"plot\", \"full\"), error_call = call)\n assert_bool(clip, call = call)\n assert_s3_class(vp, \"viewport\", allow_null = TRUE, call = call)\n if (!is.grob(grob <- patch(x = plot, ...))) {\n cli_abort(\"{.fn patch} must return a {.cls grob}\", call = call)\n }\n if (!is.null(vp)) grob <- editGrob(grob, vp = vp)\n structure(\n list(\n grob = grob,\n align = align,\n clip = if (clip) \"on\" else \"off\",\n on_top = on_top\n ),\n class = \"patch_inset\"\n )\n}\n\n#' @importFrom grid grid.draw\n#' @export\ngrid.draw.patch_inset <- function(x, recording = TRUE) {\n grid.draw(.subset2(x, \"grob\"))\n}\n\n#' @importFrom ggplot2 ggplot_add\n#' @export\nggplot_add.patch_inset <- function(object, plot, object_name, ...) {\n make_wrap(plot, object)\n}\n"], ["/ggalign/R/layout-quad-build.R", "#' @importFrom grid unit.c\n#' @export\nggalign_build.QuadLayout <- function(x) {\n x <- default_layout(x)\n patches <- quad_build(x)\n plots <- .subset2(patches, \"plots\")\n sizes <- .subset2(patches, \"sizes\")\n design <- list(\n top = area(1, 2),\n left = area(2, 1),\n main = area(2, 2),\n bottom = area(3, 2),\n right = area(2, 3)\n )\n sizes <- imap(list(\n height = c(\"top\", \"main\", \"bottom\"),\n width = c(\"left\", \"main\", \"right\")\n ), function(x, name) {\n out <- .subset(sizes, x)\n out$main <- .subset2(.subset2(out, \"main\"), name)\n out <- .subset(\n out,\n !vapply(.subset(plots, x), is.null, logical(1L), USE.NAMES = FALSE)\n )\n do.call(unit.c, out)\n })\n keep <- !vapply(plots, is.null, logical(1L), USE.NAMES = FALSE)\n design <- trim_area(vec_c(!!!vec_set_names(vec_slice(design, keep), NULL)))\n titles <- x@titles\n align_plots(\n !!!.subset(plots, keep),\n design = design,\n heights = .subset2(sizes, \"height\"),\n widths = .subset2(sizes, \"width\"),\n guides = .subset2(.subset2(x@schemes, \"scheme_align\"), \"guides\"),\n theme = x@theme\n ) + layout_title(\n title = .subset2(titles, \"title\"),\n subtitle = .subset2(titles, \"subtitle\"),\n caption = .subset2(titles, \"caption\")\n )\n}\n\nquad_build <- function(quad, schemes = NULL, theme = NULL,\n direction = NULL) {\n UseMethod(\"quad_build\")\n}\n\n#######################################################################\n#' @param schemes,theme Parameters from parent layout\n#' @importFrom ggplot2 aes\n#' @importFrom rlang is_empty\n#' @importFrom grid unit is.unit unit.c\n#' @export\n#' @noRd\nquad_build.QuadLayout <- function(quad, schemes = NULL, theme = NULL,\n direction = NULL) {\n data <- quad@data\n row_design <- setup_design(quad@horizontal)\n column_design <- setup_design(quad@vertical)\n if (is.function(data)) {\n cli_abort(c(\n \"{.arg data} cannot be a {.cls function}\",\n i = sprintf(\n \"Did you want to add %s to a {.fn stack_layout}?\",\n object_name(quad)\n )\n ))\n }\n if (is_discrete_design(row_design) &&\n is.null(.subset2(row_design, \"nobs\"))) {\n cli_abort(sprintf(\n \"you must initialize %s before drawing the main plot\",\n object_name(quad),\n ))\n }\n if (is_discrete_design(column_design) &&\n is.null(.subset2(column_design, \"nobs\"))) {\n cli_abort(sprintf(\n \"you must initialize %s before drawing the main plot\",\n object_name(quad),\n ))\n }\n schemes <- inherit_parent_layout_schemes(quad, schemes)\n if (is.null(direction)) {\n spacing <- NULL\n } else if (is_horizontal(direction)) {\n spacing <- \"y\"\n } else {\n spacing <- \"x\"\n }\n theme <- inherit_parent_layout_theme(quad, theme, spacing = spacing)\n\n # prepare action for vertical and horizontal stack layout\n vertical_align <- horizontal_align <- the_align <-\n .subset2(schemes, \"scheme_align\")\n if (!is.null(layout_labs <- .subset2(the_align, \"free_labs\")) &&\n !is.waive(layout_labs)) {\n # prepare labs for child stack layout\n horizontal_align$free_labs <- gsub(\"[lr]\", \"\", layout_labs)\n vertical_align$free_labs <- gsub(\"[tb]\", \"\", layout_labs)\n if (!nzchar(horizontal_align$free_labs)) {\n horizontal_align[\"free_labs\"] <- list(NULL)\n }\n if (!nzchar(vertical_align$free_labs)) {\n vertical_align[\"free_labs\"] <- list(NULL)\n }\n }\n\n # inherit from the parent stack layout\n if (!is.null(layout_spaces <- .subset2(the_align, \"free_spaces\")) &&\n !is.waive(layout_spaces)) {\n horizontal_align$free_spaces <- gsub(\"[lr]\", \"\", layout_spaces)\n vertical_align$free_spaces <- gsub(\"[tb]\", \"\", layout_spaces)\n if (!nzchar(horizontal_align$free_spaces)) {\n horizontal_align[\"free_spaces\"] <- list(NULL)\n }\n if (!nzchar(vertical_align$free_spaces)) {\n vertical_align[\"free_spaces\"] <- list(NULL)\n }\n }\n\n # plot annotations ----------------------------\n stack_list <- lapply(.TLBR, function(position) {\n if (is_empty(stack <- slot(quad, position))) {\n return(list(plot = NULL, size = NULL))\n }\n pschemes <- schemes\n # inherit from horizontal align or vertical align\n if (is_horizontal(to_direction(position))) {\n extra_design <- column_design\n pschemes$scheme_align <- horizontal_align\n } else {\n extra_design <- row_design\n pschemes$scheme_align <- vertical_align\n }\n plot <- stack_build(\n stack,\n schemes = pschemes,\n theme = theme,\n extra_design = extra_design\n )\n if (is.null(plot)) {\n size <- NULL\n } else {\n size <- stack@sizes\n }\n list(plot = plot, size = size)\n })\n names(stack_list) <- .TLBR\n stack_list <- list_transpose(stack_list)\n plots <- .subset2(stack_list, 1L) # the annotation plot itself\n sizes <- .subset2(stack_list, 2L) # annotation size\n\n # read the plot ---------------------------------------\n p <- quad@plot\n\n # setup the facet -----------------------------------\n do_row_facet <- is_discrete_design(row_design) &&\n nlevels(.subset2(row_design, \"panel\")) > 1L\n do_column_facet <- is_discrete_design(column_design) &&\n nlevels(.subset2(column_design, \"panel\")) > 1L\n\n if (do_row_facet && do_column_facet) {\n default_facet <- ggplot2::facet_grid(\n rows = ggplot2::vars(.data$.panel_y),\n cols = ggplot2::vars(.data$.panel_x),\n scales = \"free\", space = \"free\",\n drop = FALSE, as.table = FALSE\n )\n free_row <- FALSE\n free_column <- FALSE\n } else if (do_row_facet) {\n default_facet <- ggplot2::facet_grid(\n rows = ggplot2::vars(.data$.panel_y),\n scales = \"free_y\", space = \"free\",\n drop = FALSE, as.table = FALSE\n )\n free_row <- FALSE\n free_column <- is_continuous_design(column_design)\n } else if (do_column_facet) {\n default_facet <- ggplot2::facet_grid(\n cols = ggplot2::vars(.data$.panel_x),\n scales = \"free_x\", space = \"free\",\n drop = FALSE, as.table = FALSE\n )\n free_row <- is_continuous_design(row_design)\n free_column <- FALSE\n } else {\n default_facet <- facet_quad(object_name(quad))\n free_row <- is_continuous_design(row_design)\n free_column <- is_continuous_design(column_design)\n }\n\n # set the facets and coord ---------------------------\n # we don't align observations for `quad_free()`\n # add default data ----------------------------------\n p <- gguse_data(p, quad_build_data(data, row_design, column_design))\n p <- gguse_linear_coord(p, object_name(quad))\n p <- ggmelt_facet(p, default_facet,\n free_row = free_row, free_column = free_column\n )\n p <- p +\n ggalign_design(\n x = column_design, y = row_design,\n xlabels = .subset(\n colnames(data),\n .subset2(column_design, \"index\")\n ),\n ylabels = .subset(\n vec_names(data),\n .subset2(row_design, \"index\")\n )\n )\n\n # add action ----------------------------------------\n p <- plot_add_schemes(p, inherit_schemes(quad@body_schemes, schemes))\n if (do_row_facet) {\n p <- p + theme(panel.spacing.y = calc_element(\"panel.spacing.y\", theme))\n }\n if (do_column_facet) {\n p <- p + theme(panel.spacing.x = calc_element(\"panel.spacing.x\", theme))\n }\n p <- p + theme_recycle()\n\n # collect all plots and sizes ----------------------\n plots <- append(plots, list(main = p), 2L)\n sizes <- append(\n sizes,\n list(main = list(width = quad@width, height = quad@height)),\n 3L\n )\n list(plots = plots, sizes = sizes)\n}\n\n#' @importFrom stats reorder\nquad_build_data <- function(data, row_design, column_design) {\n if (is.null(data) ||\n (is_continuous_design(row_design) &&\n is_continuous_design(column_design))) {\n return(data)\n }\n if (is_discrete_design(row_design)) {\n row_panel <- .subset2(row_design, \"panel\")\n row_index <- .subset2(row_design, \"index\")\n row_data <- data_frame0(\n .panel_y = row_panel,\n .index_y = row_index,\n .y = seq_along(row_index)\n )\n }\n if (is_discrete_design(column_design)) {\n column_panel <- .subset2(column_design, \"panel\")\n column_index <- .subset2(column_design, \"index\")\n column_data <- data_frame0(\n .panel_x = column_panel,\n .index_x = column_index,\n .x = seq_along(column_index)\n )\n }\n if (is_discrete_design(row_design) && is_discrete_design(column_design)) {\n panel_data <- cross_join(row_data, column_data)\n by.x <- c(\".column_index\", \".row_index\")\n by.y <- c(\".index_x\", \".index_y\")\n } else if (is_discrete_design(column_design)) {\n panel_data <- column_data\n by.x <- \".column_index\"\n by.y <- \".index_x\"\n } else {\n panel_data <- row_data\n by.x <- \".row_index\"\n by.y <- \".index_y\"\n }\n ans <- fortify_data_frame.matrix(data)\n ans <- full_join(ans, panel_data, by.x = by.x, by.y = by.y)\n if (!is.null(.subset2(ans, \".row_names\")) &&\n is_discrete_design(row_design)) {\n ans$.discrete_y <- reorder(\n .subset2(ans, \".row_names\"),\n .subset2(ans, \".y\"),\n order = FALSE\n )\n }\n if (!is.null(.subset2(ans, \".column_names\")) &&\n is_discrete_design(column_design)) {\n ans$.discrete_x <- reorder(\n .subset2(ans, \".column_names\"),\n .subset2(ans, \".x\"),\n order = FALSE\n )\n }\n ggalign_data_restore(ans, data)\n}\n"], ["/ggalign/R/utils.R", "# `vec_rep`\nrecycle_whole <- function(x, len) {\n out <- x %% len\n if (out == 0L) len else out\n}\n\n# `vec_rep_each`\nrecycle_each <- function(x, len) {\n (x - 1L) %/% len + 1L\n}\n\n#' @importFrom utils modifyList\nupdate_non_waive <- function(old, new, keep_null = TRUE) {\n modifyList(old,\n new[!vapply(new, is.waive, logical(1L), USE.NAMES = FALSE)],\n keep.null = keep_null\n )\n}\n\nis_s3 <- function(x) is.object(x) && !isS4(x) && !inherits(x, \"R6\")\n\n#' @importFrom rlang names2\nnames_or_index <- function(x) {\n nms <- names2(x)\n empty <- nms == \"\"\n nms[empty] <- seq_along(x)[empty]\n nms\n}\n\n#################################################################\n#' Read Example Data\n#'\n#' This function reads example data from the file. If no file is specified, it\n#' returns a list of available example files.\n#'\n#' @param file A string representing the name of the example file to be read. If\n#' `NULL`, the function will return a list of available example file names.\n#' @return If `file` is `NULL`, returns a character vector of available example\n#' file names. Otherwise, returns the contents of the specified example file,\n#' read as an R object.\n#' @examples\n#' read_example()\n#' @export\nread_example <- function(file = NULL) {\n if (is.null(file)) {\n dir(pkg_extdata())\n } else {\n readRDS(pkg_extdata(file, mustWork = TRUE))\n }\n}\n\nwith_options <- function(code, ...) {\n opts <- options(...)\n on.exit(options(opts))\n force(code)\n}\n\n#' @param ans Whether to assign the final results into the 'ans' variable.\n#' @noRd\nfn_body_append <- function(fn, ..., ans = FALSE) {\n args <- rlang::fn_fmls(fn)\n body <- rlang::fn_body(fn)\n body <- as.list(body)\n if (ans) body[[length(body)]] <- rlang::expr(ans <- !!body[[length(body)]])\n body <- as.call(c(body, rlang::enexprs(...)))\n rlang::new_function(args, body)\n}\n\n# This will work with most things but be aware that it might fail with some\n# complex objects. For example, according to `?S3Methods`, calling foo on\n# matrix(1:4, 2, 2) would try `foo.matrix`, then `foo.numeric`, then\n# `foo.default`; whereas this code will just look for `foo.matrix` and\n# `foo.default`.\n#' @importFrom utils getS3method\n#' @importFrom methods extends\nhas_method <- function(x, f, inherit = TRUE, default = inherit) {\n x_class <- class(x)\n if (inherit) {\n if (isS4(x)) x_class <- extends(x_class)\n if (default) x_class <- c(x_class, \"default\")\n } else {\n x_class <- .subset(x_class, 1L)\n }\n for (cls in x_class) {\n if (!is.null(getS3method(f, cls, optional = TRUE))) {\n return(TRUE)\n }\n }\n return(FALSE)\n}\n\n#' For functions with a `call` argument, we check if the call originates from\n#' the current package. If it does, we use the caller's call; if not, we use the\n#' current call directly. Used by `align()` and `free()`\n#' @noRd\n#' @importFrom utils packageName\noverride_call <- function(call = NULL) {\n # if no caller call\n if (is.null(call) || is.function(f <- .subset2(call, 1L))) {\n return(TRUE)\n }\n # if call from the current package\n !identical(\n packageName(environment(eval(f))),\n pkg_nm()\n )\n}\n\n# library(data.table)\n# library(vctrs)\n# `%nest_unique%` <- function(x, y) {\n# ans <- new_data_frame(list(x = x, y = y))\n# ans <- unique(ans)\n# !anyDuplicated(ans$x)\n# }\n# `%nest_vctrs%` <- function(x, y) {\n# ans <- new_data_frame(list(x = x, y = y))\n# ans <- vec_unique(ans)\n# !vec_duplicate_any(.subset2(ans, \"x\"))\n# }\n# `%nest_vctrs_loc%` <- function(x, y) {\n# # we don't check the inputs for performance\n# loc <- vec_unique_loc(new_data_frame(list(x = x, y = y)))\n# !vec_duplicate_any(vec_slice(x, loc))\n# }\n# `%nest_data_table%` <- function(x, y) {\n# ans <- data.table(x = x, y = y)\n# ans <- unique(ans)\n# !anyDuplicated(.subset2(ans, \"x\"))\n# }\n# `%nest_split%` <- function(x, y) {\n# all(lengths(lapply(split(y, x), unique)) == 1L)\n# }\n# `%nest_table%` <- function(x, y) {\n# all(rowSums(table(x, y) > 0L) == 1L)\n# }\n# foo <- rep(seq(10^4L / 2L), each = 4)\n# bar <- rep(seq(10^4L), each = 2)\n# bench::mark(\n# nest_unique = bar %nest_unique% foo,\n# nest_vctrs = bar %nest_vctrs% foo,\n# nest_vctrs_loc = bar %nest_vctrs_loc% foo,\n# nest_data_table = bar %nest_data_table% foo,\n# nest_split = bar %nest_split% foo,\n# nest_table = bar %nest_table% foo,\n# )\n#> Warning: Some expressions had a GC in every iteration; so filtering is\n#> disabled.\n#> # A tibble: 6 x 6\n#> expression min median `itr/sec` mem_alloc `gc/sec`\n#> \n#> 1 nest_unique 5.37ms 7.49ms 134. 1.33MB 69.2\n#> 2 nest_vctrs 200.3us 214.57us 3591. 754.7KB 6.00\n#> 3 nest_vctrs_loc 193.99us 207.29us 4490. 706.95KB 6.00\n#> 4 nest_data_table 402.71us 459.55us 1918. 985.25KB 4.00\n#> 5 nest_split 11.87ms 14.08ms 69.8 1.15MB 54.3\n#> 6 nest_table 183.52ms 189.87ms 5.20 576.35MB 8.67\n`%nest%` <- function(x, y) {\n # we don't check the inputs for performance\n loc <- vec_unique_loc(new_data_frame(list(x = x, y = y)))\n !vec_duplicate_any(vec_slice(x, loc))\n}\n\nsave_png <- function(code, width = 400L, height = 400L) {\n path <- tempfile(fileext = \".png\")\n grDevices::png(path, width = width, height = height)\n on.exit(grDevices::dev.off())\n print(code)\n path\n}\n\nadd_class <- function(x, ...) {\n if (is.null(x)) return(x) # styler: off\n class(x) <- vec_unique(c(..., class(x)))\n x\n}\n\nremove_class <- function(x, ...) {\n oldClass(x) <- vec_set_difference(oldClass(x), c(...))\n x\n}\n\n###########################################################\nswitch_position <- function(position, x, y) {\n switch(position,\n top = ,\n bottom = x,\n left = ,\n right = y\n )\n}\n\nto_direction <- function(position) {\n switch_position(position, \"vertical\", \"horizontal\")\n}\n\nis_vertical <- function(direction) direction == \"vertical\"\n\nis_horizontal <- function(direction) direction == \"horizontal\"\n\nswitch_direction <- function(direction, h, v) {\n if (is_horizontal(direction)) {\n h\n } else {\n v\n }\n}\n\nto_coord_axis <- function(direction) {\n switch_direction(direction, \"y\", \"x\")\n}\n\nto_matrix_axis <- function(direction) {\n switch_direction(direction, \"row\", \"column\")\n}\n\n##########################################################\ndata_frame0 <- function(...) data_frame(..., .name_repair = \"minimal\")\n\nas_data_frame0 <- function(data, ...) {\n as.data.frame(\n x = data, ...,\n make.names = FALSE,\n stringsAsFactors = FALSE,\n fix.empty.names = FALSE\n )\n}\n\nquickdf <- function(x) {\n class(x) <- \"data.frame\"\n attr(x, \"row.names\") <- .set_row_names(length(.subset2(x, 1L)))\n x\n}\n\nfct_rev <- function(x) {\n ans <- as.factor(x)\n factor(ans, levels = rev(levels(ans)))\n}\n\nreverse_trans <- function(x) sum(range(x, na.rm = TRUE)) - x\n\nfclass <- function(x) .subset(class(x), 1L)\n\nis_scalar <- function(x) length(x) == 1L\n\nis_scalar_numeric <- function(x) length(x) == 1L && is.numeric(x)\n"], ["/ggalign/R/layout-chain-circle-build.R", "#' @export\nggalign_build.CircleLayout <- function(x) {\n x <- default_layout(x)\n circle_build(x)\n}\n\n#' @importFrom utils packageVersion\n#' @importFrom ggplot2 find_panel calc_element ggproto ggplotGrob theme\n#' @importFrom gtable gtable_add_grob gtable_add_padding is.gtable\n#' @importFrom grid unit viewport editGrob\n#' @importFrom rlang is_empty arg_match0\ncircle_build <- function(circle, schemes = NULL, theme = NULL) {\n schemes <- inherit_parent_layout_schemes(circle, schemes)\n theme <- inherit_parent_layout_theme(circle, theme)\n # for empty plot\n base <- ggplot() +\n theme +\n ggplot2::labs(\n title = .subset2(circle@titles, \"title\"),\n subtitle = .subset2(circle@titles, \"subtitle\"),\n caption = .subset2(circle@titles, \"caption\")\n )\n if (is_empty(plot_list <- circle@plot_list)) {\n return(ggplotGrob(base))\n }\n\n # we remove the plot without actual plot area\n keep <- vapply(plot_list, function(plot) {\n !is.null(plot@plot)\n }, logical(1L), USE.NAMES = FALSE)\n plot_list <- .subset(plot_list, keep)\n if (is_empty(plot_list)) return(ggplotGrob(base)) # styler: off\n\n # we reorder the plots based on the `order` slot\n plot_order <- vapply(plot_list, function(plot) {\n .subset2(plot@active, \"order\")\n }, integer(1L), USE.NAMES = FALSE)\n plot_list <- .subset(plot_list, make_order(plot_order))\n\n # plot coordinate\n if (is.null(input_radial <- circle@radial)) {\n radial <- coord_circle(theta = \"x\", r.axis.inside = TRUE)\n } else {\n radial <- ggproto(NULL, input_radial, theta = \"x\", r_axis_inside = TRUE)\n }\n\n sizes <- vapply(plot_list, function(plot) {\n # for circular layout, we only support relative size\n if (is.na(size <- as.numeric(plot@size))) {\n size <- 1\n }\n size\n }, numeric(1L), USE.NAMES = FALSE)\n\n # For each plot track, relative to the total radius (1):\n # 1. total radius: 1\n # 2. total radius for the plot area (for each plot track): 1 - inner_radius\n if (inherits(radial, \"CoordCircle\")) {\n inner_radius <- radial$inner_radius[1L] / 0.5\n outer_radius <- radial$inner_radius[2L] / 0.5\n } else {\n # For `CoordRadial`\n # `0.4` is coord_radial used for scale size in ggplot2 to add extra\n # spaces for axis labels\n # https://github.com/tidyverse/ggplot2/issues/6284\n inner_radius <- radial$inner_radius[1L] / 0.4\n outer_radius <- radial$inner_radius[2L] / 0.4\n }\n plot_track <- sizes / sum(sizes) * (outer_radius - inner_radius)\n\n # For each plot, the plot size is calculated by adding the space for the\n # inner radius of each track.\n N <- length(plot_list)\n index <- seq_len(N)\n direction <- circle@direction\n if (identical(direction, \"outward\")) {\n plot_sizes <- inner_radius + cumsum(plot_track)\n } else {\n plot_sizes <- outer_radius -\n cumsum(c(0, utils::head(plot_track, -1L)))\n # The plots are always build outward, so the order is reversed.\n index <- rev(index)\n }\n\n # For each plot, the inner radius is calculated as the difference between\n # the plot size and its track size.\n plot_inner <- plot_sizes - plot_track\n guides <- vector(\"list\", N)\n plot_table <- NULL\n design <- setup_design(circle@design)\n for (i in index) {\n plot_size <- plot_sizes[[i]]\n plot <- .subset2(plot_list, i)\n craftsman <- plot@craftsman # `Craftsman` object\n plot_schemes <- inherit_schemes(plot@schemes, schemes)\n # the actual plot\n plot <- plot@plot\n\n # we always use `null` facet\n # we won't respect `free_facet` and `free_coord`\n plot_coord <- gguse_circle_coord(\n plot,\n coord = radial,\n # https://github.com/tidyverse/ggplot2/issues/6284\n # Use `0.5` to remove the extra spaces for axis label\n inner_radius = c(\n plot_inner[[i]] / plot_size,\n # for the outmost plot, we respect the outer radius defined by\n # the users, for others, we alway use 1 to remove any spacing\n # between two tracks\n if (i == N) outer_radius else 1\n ) * 0.5,\n layout_name = craftsman$layout_name\n )\n if (!craftsman$free_facet) {\n if (is_discrete_design(design)) {\n if (nlevels(.subset2(design, \"panel\")) > 1L) {\n plot <- plot + facet_sector(\n ggplot2::vars(.data$.panel),\n sector_spacing = circle@sector_spacing %||% (pi / 180),\n drop = FALSE\n )\n } else {\n plot <- ggmelt_facet(plot, ggplot2::facet_null())\n }\n } else {\n if (inherits(plot$facet, \"FacetSector\")) {\n plot <- ggfacet_modify(plot,\n sector_spacing = circle@sector_spacing %||% (pi / 180),\n drop = FALSE\n )\n } else {\n plot <- ggmelt_facet(plot, ggplot2::facet_null())\n }\n }\n }\n plot$coordinates <- plot_coord\n\n # set limits and default scales\n if (!craftsman$free_limits) {\n plot <- plot + ggalign_design(\n x = design,\n xlabels = .subset(craftsman$labels, .subset2(design, \"index\"))\n )\n }\n\n # let `Craftsman` add other components\n plot <- craftsman$build_plot(plot, design = design)\n plot <- craftsman$finish_plot(\n plot,\n schemes = plot_schemes, theme = theme\n )\n plot <- plot + ggplot2::labs(x = NULL, y = NULL) +\n theme(panel.border = element_blank())\n plot <- chain_decorate(circle, plot)\n\n # copied from `ggplot2:::ggplot_gtable`\n data <- ggplot2::ggplot_build(plot)\n plot <- data$plot\n plot_layout <- data$layout\n data <- data$data\n plot_theme <- complete_theme(plot$theme)\n\n geom_grobs <- ggfun(\"by_layer\")(\n function(l, d) l$draw_geom(d, plot_layout),\n plot$layers, data,\n \"converting geom to grob\"\n )\n gt <- plot_layout$render(geom_grobs, data, plot_theme, plot$labels)\n\n # for each inner gtable, we insert it to the panel area of the\n # outter gtable\n #\n # For bbox, `ggplot2::polar_bbox` always take (0.5, 0.5) as origin\n bbox <- ggfun(\"polar_bbox\")(\n plot_layout$coord$arc, margin = c(0, 0, 0, 0),\n inner_radius = plot_layout$coord$inner_radius\n )\n origin <- c(\n scales::rescale(0.5, from = bbox$x),\n scales::rescale(0.5, from = bbox$y)\n )\n spacing <- calc_element(\"panel.spacing.r\", plot_theme)\n\n if (is.null(plot_table)) {\n plot_table <- gt\n } else {\n # define the panel size of the inner track\n rescale_factor <- last_plot_size / plot_size\n\n # the spacer between two plots\n if (identical(direction, \"outward\")) {\n spacer <- last_spacing\n } else {\n spacer <- spacing\n }\n if (inherits(spacer, \"element_blank\") || is.null(spacer)) {\n spacer <- unit(0, \"mm\")\n }\n plot_table <- editGrob(plot_table, vp = viewport(\n width = unit(rescale_factor, \"npc\") - spacer,\n height = unit(rescale_factor, \"npc\") - spacer,\n x = origin[1L], y = origin[2L], just = just,\n default.units = \"native\", clip = \"off\"\n ))\n\n # add the inner track to the panel area of the outter track\n panel_loc <- find_panel(gt)\n plot_table <- gtable_add_grob(\n gt, plot_table,\n t = .subset2(panel_loc, \"t\"),\n l = .subset2(panel_loc, \"l\"),\n b = .subset2(panel_loc, \"b\"),\n r = .subset2(panel_loc, \"r\"),\n name = \"inner-track\"\n )\n }\n\n # build legends\n guides[i] <- list(plot$guides$assemble(plot_theme))\n\n # assign value for next loop\n just <- origin\n last_plot_size <- plot_size # the last plot panel size\n last_spacing <- spacing\n }\n\n # attach the guide legends\n guides <- collect_guides_list(guides, zeroGrob())\n theme$legend.spacing <- theme$legend.spacing %||% unit(0.5, \"lines\")\n theme$legend.spacing.y <- calc_element(\"legend.spacing.y\", theme)\n theme$legend.spacing.x <- calc_element(\"legend.spacing.x\", theme)\n theme$legend.box.spacing <- calc_element(\n \"legend.box.spacing\", theme\n ) %||% unit(0.2, \"cm\")\n legend_box <- .mapply(\n function(guides, guide_pos) assemble_guides(guides, guide_pos, theme),\n list(guides = guides, guide_pos = names(guides)),\n NULL\n )\n names(legend_box) <- names(guides)\n plot_table <- ggfun(\"table_add_legends\")(plot_table, legend_box, theme)\n\n # Title\n title <- element_render(\n theme, \"plot.title\", .subset2(circle@titles, \"title\"),\n margin_y = TRUE, margin_x = TRUE\n )\n title_height <- grobHeight(title)\n\n # Subtitle\n subtitle <- element_render(\n theme, \"plot.subtitle\", .subset2(circle@titles, \"subtitle\"),\n margin_y = TRUE, margin_x = TRUE\n )\n subtitle_height <- grobHeight(subtitle)\n\n # whole plot annotation\n caption <- element_render(\n theme, \"plot.caption\", .subset2(circle@titles, \"caption\"),\n margin_y = TRUE, margin_x = TRUE\n )\n caption_height <- grobHeight(caption)\n\n # positioning of title and subtitle is governed by plot.title.position\n # positioning of caption is governed by plot.caption.position\n # \"panel\" means align to the panel(s)\n # \"plot\" means align to the entire plot (except margins and tag)\n title_pos <- arg_match0(\n theme$plot.title.position %||% \"panel\",\n c(\"panel\", \"plot\"),\n arg_nm = \"plot.title.position\",\n error_call = quote(theme())\n )\n\n caption_pos <- arg_match0(\n theme$plot.caption.position %||% \"panel\",\n values = c(\"panel\", \"plot\"),\n arg_nm = \"plot.caption.position\",\n error_call = quote(theme())\n )\n\n pans <- plot_table$layout[\n grepl(\"^panel\", plot_table$layout$name), ,\n drop = FALSE\n ]\n if (title_pos == \"panel\") {\n title_l <- min(pans$l)\n title_r <- max(pans$r)\n } else {\n title_l <- 1\n title_r <- ncol(plot_table)\n }\n if (caption_pos == \"panel\") {\n caption_l <- min(pans$l)\n caption_r <- max(pans$r)\n } else {\n caption_l <- 1\n caption_r <- ncol(plot_table)\n }\n\n plot_table <- gtable_add_rows(plot_table, subtitle_height, pos = 0)\n plot_table <- gtable_add_grob(plot_table, subtitle,\n name = \"subtitle\",\n t = 1, b = 1, l = title_l, r = title_r, clip = \"off\"\n )\n\n plot_table <- gtable_add_rows(plot_table, title_height, pos = 0)\n plot_table <- gtable_add_grob(plot_table, title,\n name = \"title\",\n t = 1, b = 1, l = title_l, r = title_r, clip = \"off\"\n )\n\n plot_table <- gtable_add_rows(plot_table, caption_height, pos = -1)\n plot_table <- gtable_add_grob(plot_table, caption,\n name = \"caption\",\n t = -1, b = -1, l = caption_l, r = caption_r, clip = \"off\"\n )\n plot_table <- ggfun(\"table_add_tag\")(plot_table, NULL, theme)\n\n # Margins\n plot_margin <- calc_element(\"plot.margin\", theme) %||% margin()\n plot_table <- gtable_add_padding(plot_table, plot_margin)\n\n if (inherits(theme$plot.background, \"element\")) {\n plot_table <- gtable_add_grob(plot_table,\n element_render(theme, \"plot.background\"),\n t = 1, l = 1, b = -1, r = -1, name = \"background\", z = -Inf\n )\n plot_table$layout <- plot_table$layout[\n c(nrow(plot_table$layout), 1:(nrow(plot_table$layout) - 1)),\n ]\n plot_table$grobs <- plot_table$grobs[\n c(nrow(plot_table$layout), 1:(nrow(plot_table$layout) - 1))\n ]\n }\n\n # add alt-text as attribute\n # attr(plot_table, \"alt-label\") <- plot$labels$alt\n strip_pos <- find_strip_pos(plot_table)\n\n # always add strips columns and/or rows\n plot_table <- add_strips(plot_table, strip_pos)\n setup_patch_titles(plot_table, patch_titles = list(\n top = NULL, left = NULL, bottom = NULL, right = NULL\n ), theme = theme)\n}\n"], ["/ggalign/R/fortify-matrix-list.R", "#' Convert the shape of a list for fortify method\n#'\n#' @param data A list\n#' @param shape Not used currently.\n#' @seealso [`fortify_matrix.list_upset()`]\n#' @family tune\n#' @export\ntune.list <- function(data, shape = NULL) {\n if (!is.null(shape)) {\n cli_abort(\"{.arg shape} cannot be used currently for {.cls list} object\")\n }\n new_tune(data, class = \"list_upset\")\n}\n\n#' Build a Matrix for UpSet plot\n#'\n#' @description\n#' `r lifecycle::badge('experimental')`\n#'\n#' This function converts a list into a matrix format suitable for creating an\n#' UpSet plot. It always returns a matrix for a `horizontal` UpSet plot.\n#' @inheritParams rlang::args_dots_empty\n#' @param data A list of sets.\n#' @param mode A string of `r oxford_or(c(\"distinct\", \"intersect\", \"union\"))`\n#' indicates the mode to define the set intersections. Check\n#' \n#' for details.\n#' @inheritParams fortify_matrix\n#' @section ggalign attributes:\n#' - `intersection_sizes`: An integer vector indicating the size of each\n#' intersection.\n#' - `set_sizes`: An integer vector indicating the size of each set.\n#' @seealso [`tune.list()`]\n#' @family fortify_matrix\n#' @aliases fortify_matrix.list\n#' @export\nfortify_matrix.list_upset <- function(data, mode = \"distinct\", ...,\n data_arg = NULL, call = NULL) {\n call <- call %||% current_call()\n rlang::check_dots_empty(call = call)\n mode <- arg_match0(mode, c(\"distinct\", \"intersect\", \"union\"),\n error_call = call\n )\n data <- lapply(tune_data(data), function(x) {\n vec_unique(vec_slice(x, !vec_detect_missing(x)))\n })\n data <- list_drop_empty(data)\n if (length(data) == 0L) {\n cli::cli_abort(\n \"No valid data: All input lists are either empty or contain only missing values.\",\n call = call\n )\n }\n\n # Based on the explanation from\n # https://jokergoo.github.io/ComplexHeatmap-reference/book/upset-plot.html\n action <- switch(mode,\n distinct = function(data, intersection) {\n out <- NULL\n for (i in which(intersection)) {\n if (is.null(out)) {\n out <- .subset2(data, i)\n } else if (vec_size(out) == 0L) { # early exit for empty items\n return(out)\n } else {\n out <- vec_set_intersect(out, .subset2(data, i))\n }\n }\n for (i in which(!intersection)) {\n if (vec_size(out) == 0L) { # early exit for empty items\n return(out)\n }\n out <- vec_set_difference(out, .subset2(data, i))\n }\n return(out)\n },\n intersect = function(data, intersection) {\n out <- NULL\n for (i in which(intersection)) {\n if (is.null(out)) {\n out <- .subset2(data, i)\n } else if (vec_size(out) == 0L) { # early exit for empty items\n return(out)\n } else {\n out <- vec_set_intersect(out, .subset2(data, i))\n }\n }\n out\n },\n union = function(data, intersection) {\n Reduce(vec_set_union, .subset(data, intersection))\n }\n )\n\n intersection <- logical(vec_size(data)) # template\n intersection_and_size <- lapply(\n seq_len(vec_size(intersection)),\n function(n) {\n # generate all possible intersections\n utils::combn(vec_size(intersection), n, function(index) {\n intersection[index] <- TRUE\n list(\n intersection = intersection,\n # for each intersection, we define the size\n size = vec_size(action(data, intersection))\n )\n }, simplify = FALSE)\n }\n )\n\n # https://en.wikipedia.org/wiki/UpSet_plot\n # UpSets can be used horizontally and vertically.\n # In a vertical UpSet plot, the columns of the matrix correspond to the\n # sets, the rows correspond to the intersections.\n # we by default use `horizontal` upset, the rows of the matrix correspond\n # to the sets, the columns correspond to the intersections.\n ans <- list_transpose(unlist(intersection_and_size, FALSE, FALSE))\n intersections <- inject(cbind(!!!.subset2(ans, \"intersection\")))\n rownames(intersections) <- names(data)\n intersection_sizes <- unlist(.subset2(ans, \"size\"), FALSE, FALSE)\n keep <- intersection_sizes > 0L # remove intersection without items\n intersections <- intersections[, keep, drop = FALSE]\n intersection_sizes <- intersection_sizes[keep]\n ggalign_data_set(intersections,\n intersection_sizes = intersection_sizes,\n set_sizes = list_sizes(data),\n upset_mode = mode\n )\n}\n"], ["/ggalign/R/craft-cross-mark.R", "#' Add a plot to annotate observations\n#'\n#' @inheritParams cross_none\n#' @inheritParams ggmark\n#'\n#' @section ggplot2 Specification:\n#' The `cross_mark` function initializes a `ggplot` object. The underlying data\n#' contains following columns:\n#'\n#' - `.panel`: the panel for the aligned axis. It means `x-axis` for vertical\n#' stack layout (including top and bottom annotation), `y-axis` for\n#' horizontal stack layout (including left and right annotation).\n#'\n#' - `.names` ([`vec_names()`][vctrs::vec_names]) and `.index`\n#' ([`vec_size()`][vctrs::vec_size()]/[`NROW()`]): a character names (only\n#' applicable when names exists) and an integer of index of the original\n#' data.\n#'\n#' - `.hand`: A factor with levels `c(\"left\", \"right\")` for horizontal stack\n#' layouts, or `c(\"top\", \"bottom\")` for vertical stack layouts, indicating\n#' the position of the linked observations.\n#'\n#' You can use [`scheme_data()`] to modify the internal data if needed.\n#'\n#' @export\ncross_mark <- function(mark, data = waiver(), ...,\n obs_size = 1, inherit_index = NULL, inherit_panel = NULL,\n inherit_nobs = NULL,\n size = NULL, active = NULL) {\n if (!inherits(mark, \"ggalign_mark_draw\")) {\n cli_abort(\"{.arg mark} must be a {.fn mark_draw} object\")\n }\n assert_obs_size(obs_size)\n assert_active(active)\n active <- update_active(active, new_active(use = TRUE))\n cross(CrossMark,\n data = data, data_params = list2(...),\n mark = mark, obs_size = obs_size,\n plot = ggplot(), size = size,\n schemes = default_schemes(th = theme_panel_border()),\n active = active,\n inherit_nobs = inherit_nobs,\n inherit_panel = inherit_panel,\n inherit_index = inherit_index\n )\n}\n\n#' @importFrom ggplot2 ggproto ggproto_parent\n#' @include craft-cross-.R\nCrossMark <- ggproto(\"CrossMark\", CraftCross,\n interact_layout = function(self, layout) {\n if (!self$in_linear) { # only used for linear coordinate\n cli_abort(c(\n sprintf(\n \"Cannot add %s to %s\",\n object_name(self), layout_name\n ),\n i = sprintf(\n \"%s can only be used in linear layout\",\n object_name(self)\n )\n ))\n }\n ggproto_parent(CraftCross, self)$interact_layout(layout)\n },\n build_plot = function(self, plot, design, extra_design = NULL,\n previous_design = NULL) {\n if (is.null(.subset2(previous_design, \"nobs\"))) {\n cli_abort(\n sprintf(\n \"layout {.field nobs} for %s before %s is not initialized \",\n self$layout_name, object_name(self)\n )\n )\n }\n if (is.null(.subset2(design, \"nobs\"))) {\n cli_abort(\n sprintf(\n \"layout {.field nobs} for %s after %s is not initialized \",\n self$layout_name, object_name(self)\n )\n )\n }\n direction <- self$direction\n\n # parse links --------------------------------------------\n mark <- self$mark\n design1 <- previous_design\n design2 <- design\n full_data1 <- split(\n seq_len(.subset2(design1, \"nobs\")),\n .subset2(design1, \"panel\")\n )\n full_data2 <- split(\n seq_len(.subset2(design2, \"nobs\")),\n .subset2(design2, \"panel\")\n )\n link_index <- make_links_data(\n .subset2(mark, \"links\"),\n design1 = design1, design2 = design2,\n labels1 = self$labels0, labels2 = self$labels\n )\n if (vec_duplicate_any(nms <- names(link_index))) { # nolint\n cli_abort(\n c(\n \"panel names must be unique in {.arg mark}\",\n i = \"duplicated names: {.val {nms[vec_duplicate_detect(nms)]}}\"\n ),\n call = self$call\n )\n }\n data_index <- lapply(link_index, function(link) {\n if (is.null(link)) {\n return(NULL)\n }\n hand1 <- .subset2(link, \"hand1\")\n hand2 <- .subset2(link, \"hand2\")\n list(\n hand1 = .subset2(design1, \"index\")[hand1],\n hand2 = .subset2(design2, \"index\")[hand2]\n )\n })\n\n # prepare data for the plot\n plot_data <- lapply(data_index, function(index) {\n if (is.null(index)) {\n return(NULL)\n }\n hand1 <- .subset2(index, \"hand1\")\n hand2 <- .subset2(index, \"hand2\")\n hand <- switch_direction(\n direction,\n c(\"left\", \"right\"),\n c(\"top\", \"bottom\")\n )\n data_frame0(\n .hand = vec_rep_each(hand, c(length(hand1), length(hand2))),\n .names = vec_c(self$labels0[hand1], self$labels[hand2]),\n .index = vec_c(hand1, hand2)\n )\n })\n plot_data <- vec_rbind(!!!plot_data, .names_to = \".panel\")\n plot_data$.panel <- factor(plot_data$.panel, names(data_index))\n plot_data$.hand <- factor(plot_data$.hand, switch_direction(\n direction, c(\"left\", \"right\"), c(\"bottom\", \"top\")\n ))\n\n # prepare data for the plot ------------------------------\n plot <- gguse_data(plot, plot_data)\n\n # set up facets\n if (nlevels(plot_data$.panel) > 1L) {\n if (inherits(plot$facet, \"FacetGrid\")) {\n facet <- switch_direction(\n direction,\n ggplot2::facet_grid(\n rows = ggplot2::vars(.data$.panel),\n scales = \"free_y\", space = \"free\",\n drop = FALSE, as.table = FALSE\n ),\n ggplot2::facet_grid(\n cols = ggplot2::vars(.data$.panel),\n scales = \"free_x\", space = \"free\",\n drop = FALSE, as.table = FALSE\n )\n )\n } else {\n facet <- switch_direction(\n direction,\n ggplot2::facet_wrap(\n facets = ggplot2::vars(.data$.panel),\n ncol = 1L, as.table = FALSE\n ),\n ggplot2::facet_wrap(\n facets = ggplot2::vars(.data$.panel),\n nrow = 1L, as.table = FALSE\n )\n )\n }\n } else {\n facet <- facet_stack(direction, object_name(self))\n }\n # `free_row` and `free_column` have nothing with `facet_stack`\n # it's safe to use it directly\n plot <- ggmelt_facet(plot, facet, free_row = TRUE, free_column = TRUE)\n plot$ggalign_link_data <- list(\n full_data1 = full_data1,\n full_data2 = full_data2,\n link_index = link_index,\n data_index = data_index,\n direction = direction,\n draw = .subset2(mark, \"draw\"),\n obs_size = self$obs_size\n )\n add_class(plot, \"ggalign_mark_plot\", \"patch_ggplot\")\n },\n finish_plot = function(self, plot, schemes, theme) {\n plot <- plot_add_schemes(plot, schemes)\n\n # save spacing for usage\n spacing <- calc_element(\n switch_direction(\n self$direction,\n \"panel.spacing.y\",\n \"panel.spacing.x\"\n ),\n theme\n ) %||% unit(0, \"mm\")\n\n # save spacing for usage\n plot$ggalign_link_data$spacing1 <-\n plot$ggalign_link_data$spacing2 <- spacing\n\n plot + theme_recycle()\n },\n summary = function(self, plot) {\n header <- ggproto_parent(CraftCross, self)$summary(plot)\n c(header, \" Add plot to annotate observations\")\n }\n)\n\nmark_use_facet <- function(plot, facet) {\n\n}\n"], ["/ggalign/R/alignpatch-alignpatches.R", "#' @importFrom ggplot2 ggproto\n#' @export\nalignpatch.alignpatches <- function(x) {\n ggproto(NULL, PatchAlignpatches, plot = x)\n}\n\n#' @noRd\nPatchAlignpatches <- ggproto(\"PatchAlignpatches\", Patch,\n set_guides = function(self, guides) guides,\n #' @importFrom gtable gtable gtable_add_grob\n #' @importFrom grid unit\n #' @importFrom ggplot2 wrap_dims calc_element zeroGrob theme_get\n #' @importFrom S7 prop\n patch_gtable = function(self, theme = theme_get(), guides = NULL,\n top_level = FALSE, plot = self$plot) {\n patches <- lapply(prop(plot, \"plots\"), alignpatch)\n layout <- prop(plot, \"layout\")\n\n # get the design areas and dims ------------------\n panel_widths <- .subset2(layout, \"widths\")\n panel_heights <- .subset2(layout, \"heights\")\n if (is.null(area <- .subset2(layout, \"area\"))) {\n if (is.null(layout$ncol) && length(panel_widths) > 1L) {\n layout$ncol <- length(panel_widths)\n }\n if (is.null(layout$nrow) && length(panel_heights) > 1L) {\n layout$nrow <- length(panel_heights)\n }\n dims <- wrap_dims(\n length(patches),\n .subset2(layout, \"nrow\"),\n .subset2(layout, \"ncol\")\n )\n area <- create_area(\n dims[2L], dims[1L],\n .subset2(layout, \"byrow\")\n )\n } else {\n dims <- c(max(field(area, \"b\")), max(field(area, \"r\")))\n }\n\n # filter `plots` based on the design areas --------------------\n if (vec_size(area) < vec_size(patches)) {\n cli_warn(\n \"Too few patch areas to hold all plots. Dropping plots\"\n )\n plots <- vec_slice(patches, vec_seq_along(area))\n } else {\n area <- vec_slice(area, seq_along(patches))\n }\n\n # remove NULL patch -----------------------------------\n keep <- !vapply(patches, is.null, logical(1L), USE.NAMES = FALSE)\n patches <- vec_slice(patches, keep)\n\n # if no plots, we return empty gtable -----------------\n if (is_empty(patches)) return(make_patch_table()) # styler: off\n self$patches <- patches\n\n # add borders to patch --------------------------------\n area <- vec_slice(area, keep)\n for (i in seq_along(patches)) {\n patches[[i]]$borders <- c(\n if (field(area, \"t\")[i] == 1L) \"top\" else NULL,\n if (field(area, \"l\")[i] == 1L) \"left\" else NULL,\n if (field(area, \"b\")[i] == .subset(dims, 1L)) {\n \"bottom\"\n } else {\n NULL\n },\n if (field(area, \"r\")[i] == .subset(dims, 2L)) {\n \"right\"\n } else {\n NULL\n }\n )\n }\n\n # we inherit parameters from the parent --------------------\n # by default, we won't collect any guide legends\n parent_guides <- guides\n guides <- .subset2(layout, \"guides\") %|w|% parent_guides\n\n # by default, we use ggplot2 default theme\n if (!is.null(prop(plot, \"theme\"))) theme <- theme + prop(plot, \"theme\")\n self$theme <- theme\n\n #######################################################\n # 1. patch_gtable: create the gtable for the patch, will set internal\n # `gt`\n # 2. `collect_guides`, can change the internal `gt`\n # 3. set_sizes:\n # - (To-Do) align_panel_spaces: can change the internal `gt`\n # - align_panel_sizes, can change the internal `gt`\n # - get_sizes, the widths and heights for the internal `gt`\n # 4. set_grobs: will call `align_border` and `split_gt`, return the\n # final gtable\n # setup gtable list ----------------------------------\n # Let each patch to determine whether to collect guides\n collected <- lapply(patches, function(patch) patch$set_guides(guides))\n collected_guides <- vector(\"list\", length(patches))\n\n # Always ensure that plots placed in a border collect their guides, if\n # any guides are to be collected in that border. This prevents overlap,\n # unless the guides will be collected by the parent layout.\n border_with_guides <- unique(unlist(collected, FALSE, FALSE))\n border_with_guides <- setdiff(border_with_guides, parent_guides)\n for (i in seq_along(patches)) {\n patch <- .subset2(patches, i)\n g <- union(\n .subset2(collected, i),\n intersect(border_with_guides, patch$borders)\n )\n patch$gt <- patch$patch_gtable(theme = theme, guides = g)\n collected_guides[i] <- list(patch$collect_guides(g))\n }\n\n # collect guides ---------------------------------------\n self$collected_guides <- collect_guides_list(collected_guides)\n\n # prepare the output ----------------------------------\n gt <- gtable(\n unit(rep(0L, TABLE_COLS * dims[2L]), \"null\"),\n unit(rep(0L, TABLE_ROWS * dims[1L]), \"null\")\n )\n\n # setup sizes for each row/column -----------------------\n gt <- self$set_sizes(\n area, dims, panel_widths, panel_heights,\n patches = patches, gt = gt\n )\n\n # add the panel position --------------------------------\n panel_pos <- list(\n t = TOP_BORDER + 1L,\n l = LEFT_BORDER + 1L,\n b = TABLE_ROWS * dims[1L] - BOTTOM_BORDER,\n r = TABLE_COLS * dims[2L] - RIGHT_BORDER\n )\n\n # add guides into the final gtable ----------------------\n if (top_level) {\n gt <- self$attach_guide_list(\n guide_list = self$collected_guides,\n theme = theme,\n panel_pos = panel_pos,\n gt = gt\n )\n }\n\n # setup grobs -------------------------------------------\n # For z in the gtable layout\n # 0L: layout background\n # 1L: background of the plot\n # 2L: plot table\n # 3L: foreground of the panel area\n # 4L: legends\n gt <- self$set_grobs(area, patches = patches, gt = gt)\n\n # add panel area ---------------------------------------\n gt <- gtable_add_grob(\n gt, list(zeroGrob()),\n t = .subset2(panel_pos, \"t\"),\n l = .subset2(panel_pos, \"l\"),\n b = .subset2(panel_pos, \"b\"),\n r = .subset2(panel_pos, \"r\"),\n z = 0L,\n name = \"panel-area\"\n )\n gt <- gtable_add_grob(\n gt,\n # foreground\n list(element_render(theme, \"panel.border\", fill = NA)),\n t = .subset2(panel_pos, \"t\"),\n l = .subset2(panel_pos, \"l\"),\n b = .subset2(panel_pos, \"b\"),\n r = .subset2(panel_pos, \"r\"),\n z = 3L,\n name = \"panel-foreground\"\n )\n\n # add background -----------------------------------\n if (!top_level && inherits(theme$plot.background, \"element\")) {\n gt <- gtable_add_grob(gt,\n element_render(theme, \"plot.background\"),\n t = 1L, l = 1L, b = -1L, r = -1L,\n name = \"background\", z = 0L\n )\n }\n\n # arrange the grobs\n idx <- order(.subset2(.subset2(gt, \"layout\"), \"z\"))\n gt$layout <- vec_slice(.subset2(gt, \"layout\"), idx)\n gt$grobs <- .subset(.subset2(gt, \"grobs\"), idx)\n gt\n },\n align_border = function(self, t = NULL, l = NULL, b = NULL, r = NULL,\n gt = self$gt, patches = self$patches) {\n if (is.null(t) && is.null(l) && is.null(b) && is.null(r)) {\n return(gt)\n }\n gt <- Patch$align_border(t = t, l = l, b = b, r = r, gt = gt)\n self$recurse_lapply(function(patch, grob, t, l, b, r) {\n # For each plot grob, we reuse it's method to set the border\n # sizes we only set the border sizes for plot in the border\n patch$align_border(t = t, l = l, b = b, r = r, gt = grob)\n }, t = t, l = l, b = b, r = r, gt = gt, patches = patches)\n },\n collect_guides = function(self, guides, gt = self$gt) {\n collected_guides <- self$collected_guides\n # for guides not collected by the top-level alignpatches, we attach the\n # guides\n self$gt <- self$attach_guide_list(\n collected_guides[\n vec_set_difference(names(collected_guides), guides)\n ],\n gt = gt\n )\n # return guides to be collected\n .subset(collected_guides, guides)\n },\n #' @importFrom grid is.unit unit\n set_sizes = function(self, area, dims,\n panel_widths, panel_heights,\n patches, gt = self$gt) {\n panel_widths <- rep(panel_widths, length.out = dims[2L])\n panel_heights <- rep(panel_heights, length.out = dims[1L])\n if (!is.unit(panel_widths)) panel_widths <- unit(panel_widths, \"null\")\n if (!is.unit(panel_heights)) {\n panel_heights <- unit(panel_heights, \"null\")\n }\n\n # For gtable with fixed aspect ratio -------------\n # if it cannot be fixed and aligned, the strip, axis and labs will be\n # attached into the panel\n # the plot to be fixed must in only one square of the area\n need_fix <- field(area, \"l\") == field(area, \"r\") &\n field(area, \"t\") == field(area, \"b\") &\n vapply(\n patches,\n function(patch) patch$respect(),\n logical(1L),\n USE.NAMES = FALSE\n )\n\n # here we respect the aspect ratio when necessary -----\n # if the width or height is NA, we will guess the panel widths or\n # heights based on the fixed aspect ratio\n guess_widths <- which(is.na(as.numeric(panel_widths)))\n guess_heights <- which(is.na(as.numeric(panel_heights)))\n cols <- field(area, \"l\")\n rows <- field(area, \"t\")\n patch_index <- order(\n # we first set the widths for the fixed plot with heights set by\n # user\n cols %in% guess_widths & !rows %in% guess_heights,\n # we then set the heights for the fixed plot with widths set by user\n !cols %in% guess_widths & rows %in% guess_heights,\n # we set widths and heights for remaning plots\n # based on the number of plots in each row/column in the descending\n # order\n c(table(rows[need_fix]))[as.character(rows)],\n c(table(cols[need_fix]))[as.character(cols)],\n decreasing = TRUE\n )\n respect_dims <- vector(\"list\", length(patches))\n\n # For plot cannot be fixed, we always attach strips, axes and labels\n # into the panel area\n for (i in patch_index) {\n row <- .subset(rows, i)\n col <- .subset(cols, i)\n # we always build a standard gtable layout from the gtable\n panel_sizes <- .subset2(patches, i)$align_panel_sizes(\n panel_width = panel_widths[col],\n panel_height = panel_heights[row]\n )\n panel_widths[col] <- .subset2(panel_sizes, \"width\")\n panel_heights[row] <- .subset2(panel_sizes, \"height\")\n if (.subset2(panel_sizes, \"respect\")) {\n respect_dims[[i]] <- matrix(c(\n (row - 1L) * TABLE_ROWS + TOP_BORDER + 1L,\n (col - 1L) * TABLE_COLS + LEFT_BORDER + 1L\n ), nrow = 1L)\n }\n }\n if (!is.null(respect_dims <- do.call(base::rbind, respect_dims))) {\n respect <- matrix(\n 0L, TABLE_ROWS * dims[1L],\n TABLE_COLS * dims[2L]\n )\n respect[respect_dims] <- 1L\n gt$respect <- respect\n }\n\n # we set the widths/heights with no fixed plots to be 1 null\n if (any(guess_widths <- is.na(as.numeric(panel_widths)))) {\n panel_widths[guess_widths] <- unit(1L, \"null\")\n }\n if (any(guess_heights <- is.na(as.numeric(panel_heights)))) {\n panel_heights[guess_heights] <- unit(1L, \"null\")\n }\n\n # setup sizes for non-panel rows/columns --------------\n sizes <- table_sizes(\n lapply(patches, function(patch) patch$get_sizes()),\n area, dims[2L], dims[1L]\n )\n widths <- .subset2(sizes, \"widths\")\n heights <- .subset2(sizes, \"heights\")\n\n # restore the panel sizes ----------------------------\n width_ind <- seq(LEFT_BORDER + 1L,\n by = TABLE_COLS, length.out = dims[2L]\n )\n height_ind <- seq(TOP_BORDER + 1L,\n by = TABLE_ROWS, length.out = dims[1L]\n )\n widths[width_ind] <- panel_widths\n heights[height_ind] <- panel_heights\n\n # setup the widths and heights -----------------------\n gt$widths <- widths\n gt$heights <- heights\n gt\n },\n\n #' @importFrom gtable gtable_add_grob\n set_grobs = function(self, area, patches, gt = self$gt) {\n widths <- .subset2(gt, \"widths\")\n heights <- .subset2(gt, \"heights\")\n for (i in seq_along(patches)) {\n loc <- vec_slice(area, i)\n # We must align the borders for the gtable grob with the\n # final plot area sizes\n l <- (field(loc, \"l\") - 1L) * TABLE_COLS + 1L\n l_widths <- widths[seq(l, l + LEFT_BORDER - 1L)]\n r <- field(loc, \"r\") * TABLE_COLS\n r_widths <- widths[seq(r - RIGHT_BORDER + 1L, r)]\n t <- (field(loc, \"t\") - 1L) * TABLE_ROWS + 1L\n t_heights <- heights[seq(t, t + TOP_BORDER - 1L)]\n b <- field(loc, \"b\") * TABLE_ROWS\n b_heights <- heights[seq(b - BOTTOM_BORDER + 1L, b)]\n patch <- .subset2(patches, i)\n\n grobs <- patch$split_gt(patch$align_border(\n t = t_heights, l = l_widths,\n b = b_heights, r = r_widths\n ))\n\n # then we add the plot ---------------------------------\n gt <- patch$add_plot(\n gt, .subset2(grobs, \"plot\"), t, l, b, r,\n name = paste(\"plot\", i, sep = \"-\")\n )\n\n # add background grob ----------------------------------\n if (!is.null(bg <- .subset2(grobs, \"bg\"))) {\n # we always add background in the beginning --------\n gt <- patch$add_background(\n gt, bg, t, l, b, r,\n name = paste(\"plot\", i, \"background\", sep = \"-\")\n )\n }\n\n # remove the grob from the patch, we wont' use it anymore\n patch$gt <- NULL\n }\n gt\n },\n attach_guide_list = function(self, guide_list, theme = self$theme,\n panel_pos = find_panel(gt),\n gt = self$gt) {\n if (length(guide_list)) {\n # https://github.com/tidyverse/ggplot2/blob/57ba97fa04dadc6fd73db1904e39a09d57a4fcbe/R/guides-.R#L512\n theme$legend.spacing <- theme$legend.spacing %||% unit(0.5, \"lines\")\n theme$legend.spacing.y <- calc_element(\"legend.spacing.y\", theme)\n theme$legend.spacing.x <- calc_element(\"legend.spacing.x\", theme)\n theme$legend.box.spacing <- calc_element(\n \"legend.box.spacing\", theme\n ) %||% unit(0.2, \"cm\")\n for (guide_pos in names(guide_list)) {\n gt <- self$attach_guides(\n guide_pos = guide_pos,\n guides = .subset2(guide_list, guide_pos),\n theme = theme, panel_pos = panel_pos,\n clip = \"off\", z = 4L, gt = gt\n )\n }\n }\n gt\n },\n #' @importFrom gtable gtable_width gtable_height\n #' @importFrom grid unit.c grobWidth grobHeight\n #' @importFrom ggplot2 find_panel zeroGrob\n attach_guides = function(self, guide_pos, guides, theme,\n panel_pos = find_panel(gt), ...,\n gt = self$gt) {\n guide_box <- assemble_guides(guides, guide_pos, theme = theme)\n name <- sprintf(\"guide-box-collected-%s\", guide_pos)\n if (guide_pos == \"inside\") {\n gt <- gtable_add_grob(\n x = gt,\n grobs = guide_box,\n t = panel_pos$t,\n l = panel_pos$l,\n b = panel_pos$b,\n r = panel_pos$r,\n name = name,\n ...\n )\n return(gt)\n }\n spacing <- .subset2(theme, \"legend.box.spacing\")\n if (guide_pos == \"left\") {\n if (is.gtable(guide_box)) {\n legend_width <- gtable_width(guide_box)\n widths <- unit.c(spacing, legend_width)\n } else {\n legend_width <- grobWidth(guide_box)\n widths <- unit(c(0, 0), \"mm\")\n }\n gt <- gtable_add_grob(\n x = gt,\n grobs = guide_box,\n t = panel_pos$t,\n l = panel_pos$l - 6L,\n b = panel_pos$b,\n name = name,\n ...\n )\n gt$widths[.subset2(panel_pos, \"l\") - 5:6] <- widths\n } else if (guide_pos == \"right\") {\n if (is.gtable(guide_box)) {\n legend_width <- gtable_width(guide_box)\n widths <- unit.c(spacing, legend_width)\n } else {\n legend_width <- grobWidth(guide_box)\n widths <- unit(c(0, 0), \"mm\")\n }\n gt <- gtable_add_grob(\n x = gt,\n grobs = guide_box,\n t = panel_pos$t,\n l = panel_pos$r + 6L,\n b = panel_pos$b,\n name = name,\n ...\n )\n gt$widths[.subset2(panel_pos, \"r\") + 5:6] <- widths\n } else if (guide_pos == \"bottom\") {\n location <- .subset2(theme, \"legend.location\") %||% \"panel\"\n place <- switch(location,\n panel = panel_pos,\n list(l = 1L, r = ncol(gt))\n )\n if (is.gtable(guide_box)) {\n legend_height <- gtable_height(guide_box)\n heights <- unit.c(spacing, legend_height)\n } else {\n legend_height <- grobHeight(guide_box)\n heights <- unit(c(0, 0), \"mm\")\n }\n gt <- gtable_add_grob(\n x = gt,\n grobs = guide_box,\n t = panel_pos$b + 6L,\n l = place$l,\n r = place$r,\n name = name,\n ...\n )\n gt$heights[.subset2(panel_pos, \"b\") + 5:6] <- heights\n } else if (guide_pos == \"top\") {\n location <- .subset2(theme, \"legend.location\") %||% \"panel\"\n place <- switch(location,\n panel = panel_pos,\n list(l = 1L, r = ncol(gt))\n )\n if (is.gtable(guide_box)) {\n legend_height <- gtable_height(guide_box)\n heights <- unit.c(spacing, legend_height)\n } else {\n legend_height <- grobHeight(guide_box)\n heights <- unit(c(0, 0), \"mm\")\n }\n gt <- gtable_add_grob(\n x = gt,\n grobs = guide_box,\n t = panel_pos$t - 6L,\n l = place$l,\n r = place$r,\n name = name,\n ...\n )\n gt$heights[.subset2(panel_pos, \"t\") - 5:6] <- heights\n }\n gt\n },\n\n #' @importFrom rlang is_empty\n free_border = function(self, borders, gt = self$gt,\n patches = self$patches) {\n gt <- self$recurse_lapply(\n function(patch, grob, t, l, b, r) {\n borders <- intersect(borders, c(t, l, b, r))\n if (is_empty(borders)) return(grob) # styler: off\n patch$free_border(borders = borders, gt = grob)\n },\n t = \"top\", l = \"left\", b = \"bottom\", r = \"right\",\n gt = gt, patches = patches\n )\n # for the collected guides, we should also liberate them\n guide_index <- sprintf(\"guide-box-collected-%s\", borders) %in%\n .subset2(.subset2(gt, \"layout\"), \"name\")\n if (any(guide_index)) {\n gt <- PatchGgplot$free_border(\n borders = borders[guide_index], gt = gt\n )\n }\n gt\n },\n align_free_border = function(self, borders,\n t = NULL, l = NULL, b = NULL, r = NULL,\n gt = self$gt, patches = self$patches) {\n gt <- self$recurse_lapply(\n function(patch, grob, t, l, b, r) {\n patch$align_free_border(\n borders = borders,\n t = t, l = l, b = b, r = r, gt = grob\n )\n },\n t = t, l = l, b = b, r = r,\n gt = gt, patches = patches\n )\n PatchGgplot$align_free_border(\n borders = borders,\n t = t, l = l, b = b, r = r, gt = gt\n )\n },\n\n #' @importFrom rlang is_empty\n free_lab = function(self, labs, gt = self$gt, patches = self$patches) {\n self$recurse_lapply(\n function(patch, grob, t, l, b, r) {\n labs <- intersect(labs, c(t, l, b, r))\n if (is_empty(labs)) return(grob) # styler: off\n patch$free_lab(labs = labs, gt = grob)\n },\n t = \"top\", l = \"left\", b = \"bottom\", r = \"right\",\n gt = gt, patches = patches\n )\n },\n # we apply function in each plot gtable in `gt`.\n #' @importFrom rlang is_empty\n recurse_lapply = function(self, .fn, t, l, b, r,\n gt = self$gt, patches = self$patches) {\n # if no plot provided, we'll do nothing\n if (is_empty(patches)) return(gt) # styler: off\n patch_index <- seq_along(patches)\n grobs <- .subset2(gt, \"grobs\")\n layout_index <- match(\n paste0(\"plot-\", patch_index),\n .subset2(.subset2(gt, \"layout\"), \"name\")\n )\n # For each grob, we reuse the method from the patch\n gt$grobs[layout_index] <- .mapply(function(layout_idx, patch_idx) {\n patch <- .subset2(patches, patch_idx)\n borders <- .subset2(patch, \"borders\")\n .fn(\n patch = patch,\n grob = .subset2(grobs, layout_idx),\n t = if (any(borders == \"top\")) t else NULL,\n l = if (any(borders == \"left\")) l else NULL,\n b = if (any(borders == \"bottom\")) b else NULL,\n r = if (any(borders == \"right\")) r else NULL\n )\n }, list(layout_idx = layout_index, patch_idx = patch_index), NULL)\n gt\n }\n)\n\n#' @importFrom grid convertHeight convertWidth unit\ntable_sizes <- function(sizes, area, ncol, nrow) {\n # `null` unit of the panel area will be converted into 0\n # we'll set the panel width and height afterward\n widths <- lapply(sizes, function(size) {\n convertWidth(.subset2(size, \"widths\"), \"mm\", valueOnly = TRUE)\n })\n widths <- vapply(seq_len(ncol * TABLE_COLS), function(i) {\n area_col <- (i - 1L) %/% TABLE_COLS + 1L\n col_loc <- i %% TABLE_COLS\n if (col_loc == 0L) col_loc <- TABLE_COLS\n area_side <- if (col_loc <= LEFT_BORDER + 1L) \"l\" else \"r\"\n idx <- field(area, area_side) == area_col\n if (any(idx)) {\n max(\n vapply(.subset(widths, idx), .subset, numeric(1L), col_loc),\n 0L\n )\n } else {\n 0L\n }\n }, numeric(1L), USE.NAMES = FALSE)\n heights <- lapply(sizes, function(size) {\n convertHeight(.subset2(size, \"heights\"), \"mm\", valueOnly = TRUE)\n })\n heights <- vapply(seq_len(nrow * TABLE_ROWS), function(i) {\n area_row <- recycle_each(i, TABLE_ROWS)\n row_loc <- recycle_whole(i, TABLE_ROWS)\n area_side <- if (row_loc <= TOP_BORDER + 1L) \"t\" else \"b\"\n idx <- field(area, area_side) == area_row\n if (any(idx)) {\n max(\n vapply(\n .subset(heights, idx), .subset, numeric(1L),\n row_loc,\n USE.NAMES = FALSE\n ),\n 0L\n )\n } else {\n 0L\n }\n }, numeric(1L), USE.NAMES = FALSE)\n list(widths = unit(widths, \"mm\"), heights = unit(heights, \"mm\"))\n}\n"], ["/ggalign/R/alignpatch-title.R", "#' Add patch titles to plot borders\n#'\n#' This function extends ggplot2's title functionality, allowing you to add\n#' titles to each border of the plot: top, left, bottom, and right.\n#'\n#' @details\n#'\n#' The appearance and alignment of these patch titles can be customized using\n#' [theme()][ggplot2::theme]:\n#' - `plot.patch_title`/`plot.patch_title.*`: Controls the text appearance of\n#' patch titles. By default, `plot.patch_title` inherit from `plot.title`, and\n#' settings for each border will inherit from `plot.patch_title`, with the\n#' exception of the `angle` property, which is not inherited.\n#' - `plot.patch_title.position`/`plot.patch_title.position.*`: Determines the\n#' alignment of the patch titles. By default, `plot.patch_title.position`\n#' inherit from `plot.title.position`, and settings for each border will\n#' inherit from `plot.patch_title`. The value `\"panel\"` aligns the patch\n#' titles with the plot panels. Setting this to `\"plot\"` aligns the patch\n#' title with the entire plot (excluding margins and plot tags).\n#'\n#' @param top,left,bottom,right A string specifying the title to be added to the\n#' top, left, bottom, and right border of the plot.\n#' @return A [`labels`][ggplot2::labs] object to be added to ggplot.\n#' @examples\n#' ggplot(mtcars) +\n#' geom_point(aes(mpg, disp)) +\n#' patch_titles(\n#' top = \"I'm top patch title\",\n#' left = \"I'm left patch title\",\n#' bottom = \"I'm bottom patch title\",\n#' right = \"I'm right patch title\"\n#' )\n#' @export\n#' @importFrom ggplot2 waiver\npatch_titles <- function(top = waiver(), left = waiver(), bottom = waiver(),\n right = waiver()) {\n structure(\n list(top = top, left = left, bottom = bottom, right = right),\n class = \"ggalign_patch_labels\"\n )\n}\n\n#' @importFrom ggplot2 find_panel calc_element zeroGrob element_grob merge_element\n#' @importFrom rlang arg_match0\n#' @importFrom grid grobName\nsetup_patch_titles <- function(table, patch_titles, theme) {\n # complete_theme() will ensure `plot_title` exists\n old_text <- calc_element(\"plot.title\", theme)\n # always justification by center for patch title\n old_text$hjust <- 0.5\n if (is.null(text <- .subset2(theme, \"plot.patch_title\"))) {\n text <- old_text\n } else if (inherits(text, \"element_text\")) {\n text <- merge_element(text, old_text)\n } else {\n cli_abort(paste(\n \"Theme element {.var plot.patch_title} must be a\",\n \"{.cls element_text}.\"\n ), call = quote(theme()))\n }\n # inherit from plot.title.position, default use \"panel\"\n position <- .subset2(theme, \"plot.patch_title.position\") %||%\n .subset2(theme, \"plot.title.position\") %||% \"panel\"\n for (border in .TLBR) {\n panel_pos <- find_panel(table)\n patch_title <- .subset2(patch_titles, border)\n name <- paste(\"plot.patch_title\", border, sep = \".\")\n if (is.null(patch_title)) {\n title <- zeroGrob()\n } else {\n # set the default angle\n text$angle <- switch(border,\n top = 0L,\n left = 90L,\n bottom = 0L,\n right = -90L\n )\n # we merge the element with `plot.patch_title`\n if (is.null(el <- .subset2(theme, name))) {\n el <- text\n } else if (inherits(el, \"element_text\")) {\n el <- merge_element(el, text)\n } else {\n cli_abort(paste(\n \"Theme element {.var {name}} must have\",\n \"class {.cls element_text}.\"\n ), call = quote(theme()))\n }\n # render the patch title grob\n title <- element_grob(el, patch_title,\n margin_y = TRUE, margin_x = TRUE\n )\n title$name <- grobName(title, name)\n }\n\n name <- paste(\"plot.patch_title.position\", border, sep = \".\")\n pos <- arg_match0(\n .subset2(theme, name) %||% position,\n c(\"panel\", \"plot\"),\n arg_nm = name,\n error_call = quote(theme())\n )\n if (border == \"top\") {\n height <- grobHeight(title)\n if (pos == \"panel\") {\n l <- panel_pos$l\n r <- panel_pos$r\n } else {\n l <- 1L\n r <- ncol(table)\n }\n h <- .subset2(panel_pos, \"t\") - 4L # above original xlab\n table <- gtable_add_rows(table, height, pos = h)\n table <- gtable_add_grob(table, title,\n name = \"patch-title-top\",\n t = h + 1L, b = h + 1L, l = l, r = r,\n clip = \"off\"\n )\n } else if (border == \"left\") {\n width <- grobWidth(title)\n if (pos == \"panel\") {\n t <- panel_pos$t\n b <- panel_pos$b\n } else {\n t <- 1L\n b <- nrow(table)\n }\n v <- .subset2(panel_pos, \"l\") - 4L # left of the ylab\n table <- gtable_add_cols(table, width, pos = v)\n table <- gtable_add_grob(table, title,\n name = \"patch-title-left\",\n t = t, b = b, l = v + 1L, r = v + 1L,\n clip = \"off\"\n )\n } else if (border == \"bottom\") {\n height <- grobHeight(title)\n if (pos == \"panel\") {\n l <- panel_pos$l\n r <- panel_pos$r\n } else {\n l <- 1L\n r <- ncol(table)\n }\n h <- .subset2(panel_pos, \"b\") + 3L # below original xlab\n table <- gtable_add_rows(table, height, pos = h)\n table <- gtable_add_grob(table, title,\n name = \"patch-title-bottom\",\n t = h + 1L, b = h + 1L, l = l, r = r,\n clip = \"off\"\n )\n } else if (border == \"right\") {\n width <- grobWidth(title)\n if (pos == \"panel\") {\n t <- panel_pos$t\n b <- panel_pos$b\n } else {\n t <- 1L\n b <- nrow(table)\n }\n v <- .subset2(panel_pos, \"r\") + 3L # right of the ylab\n table <- gtable_add_cols(table, width, pos = v)\n table <- gtable_add_grob(table, title,\n name = \"patch-title-right\",\n t = t, b = b, l = v + 1L, r = v + 1L,\n clip = \"off\"\n )\n }\n }\n table\n}\n\n#' @importFrom ggplot2 ggplot_add\n#' @export\nggplot_add.ggalign_patch_labels <- function(object, plot, object_name, ...) {\n plot$ggalign_patch_labels <- update_non_waive(\n plot$ggalign_patch_labels %||% list(), object\n )\n if (!inherits(plot, \"patch_ggplot\")) {\n plot <- add_class(plot, \"patch_ggplot\")\n }\n plot\n}\n"], ["/ggalign/R/ggplot-helper.R", "# Exported function for ggplot2\n# Usually a quick shortcuts to define something\n#\n#' Remove axis elements\n#'\n#' @param axes Which axes elements should be removed? A string containing\n#' one or more of `r oxford_and(c(.tlbr, \"x\", \"y\"))`.\n#' @param text If `TRUE`, will remove the axis labels.\n#' @param ticks If `TRUE`, will remove the axis ticks.\n#' @param title If `TRUE`, will remove the axis title.\n#' @param line If `TRUE`, will remove the axis line.\n#' @return A [`theme()`][ggplot2::theme] object.\n#' @examples\n#' p <- ggplot() +\n#' geom_point(aes(x = wt, y = qsec), data = mtcars)\n#' p + theme_no_axes()\n#' p + theme_no_axes(\"b\")\n#' p + theme_no_axes(\"l\")\n#' @importFrom rlang inject\n#' @importFrom ggplot2 theme element_blank\n#' @export\ntheme_no_axes <- function(axes = \"xy\", text = TRUE, ticks = TRUE,\n title = TRUE, line = FALSE) {\n assert_string(axes, empty_ok = FALSE)\n if (grepl(\"[^tlbrxy]\", axes)) {\n cli_abort(sprintf(\n \"{.arg axes} can only contain the %s characters\",\n oxford_and(c(.tlbr, \"x\", \"y\"))\n ))\n }\n axes <- split_position(axes)\n el <- list(text = text, ticks = ticks, title = title, line = line)\n el <- names(el)[vapply(el, isTRUE, logical(1L), USE.NAMES = FALSE)]\n el_axis <- el_pos <- NULL\n if (length(positions <- vec_set_intersect(axes, .tlbr))) {\n positions <- .subset(\n c(t = \"top\", l = \"left\", b = \"bottom\", r = \"right\"),\n positions\n )\n el_pos <- vec_expand_grid(pos = positions, el = el)\n el_pos <- paste(\"axis\",\n .subset2(el_pos, \"el\"),\n if_else(.subset2(el_pos, \"pos\") %in% c(\"top\", \"bottom\"), \"x\", \"y\"),\n .subset2(el_pos, \"pos\"),\n sep = \".\"\n )\n }\n if (length(axes <- vec_set_intersect(axes, c(\"x\", \"y\")))) {\n el_axis <- vec_expand_grid(axes = axes, el = el)\n el_axis <- paste(\"axis\",\n .subset2(el_axis, \"el\"), .subset2(el_axis, \"axes\"),\n sep = \".\"\n )\n }\n el <- c(el_axis, el_pos)\n el <- vec_set_names(vec_rep(list(element_blank()), length(el)), el)\n inject(theme(!!!el, validate = FALSE))\n}\n\n##########################################################################\n#' Theme Polygon elements\n#'\n#' Draw polygon.\n#'\n#' @inheritParams ggplot2::element_rect\n#' @inheritParams geom_rect3d\n#' @inheritParams ggplot2::fill_alpha\n#' @param linewidth Line size in `mm`.\n#' @param linetype Line type for lines. An integer (0:8), a name (blank, solid,\n#' dashed, dotted, dotdash, longdash, twodash), or a string with an even number\n#' (up to eight) of hexadecimal digits which give the lengths in consecutive\n#' positions in the string.\n#' @seealso [`element_rect`][ggplot2::element_rect]\n#' @return A `element_polygon` object\n#' @export\nelement_polygon <- function(fill = NULL, colour = NULL, linewidth = NULL,\n linetype = NULL, alpha = NULL, lineend = NULL,\n linejoin = NULL, linemitre = NULL, color = NULL,\n inherit.blank = FALSE) {\n if (!is.null(color)) colour <- color\n structure(\n list(\n fill = fill, colour = colour, alpha = alpha,\n linewidth = linewidth, linetype = linetype,\n lineend = lineend, linejoin = linejoin, linemitre = linemitre,\n inherit.blank = inherit.blank\n ),\n class = c(\"ggalign_element_polygon\", \"element_polygon\", \"element\")\n )\n}\n\n#' @importFrom utils packageVersion\n#' @importFrom grid gpar\n#' @importFrom ggplot2 element_grob fill_alpha\n#' @export\nelement_grob.ggalign_element_polygon <- function(element,\n x = c(0, 0.5, 1, 0.5),\n y = c(0.5, 1, 0.5, 0),\n fill = NULL,\n colour = NULL,\n linewidth = NULL,\n linetype = NULL, ...) {\n if (packageVersion(\"ggplot2\") > \"3.5.2\") {\n gp <- ggfun(\"gg_par\")(\n lwd = linewidth, col = colour, fill = fill, lty = linetype\n )\n element_gp <- ggfun(\"gg_par\")(\n lwd = element$linewidth,\n col = element$colour,\n fill = fill_alpha(element$fill, element$alpha %||% NA),\n lty = element$linetype,\n lineend = element$lineend,\n linejoin = element$linejoin,\n linemitre = element$linemitre\n )\n } else {\n gp <- gpar(\n lwd = ggfun(\"len0_null\")(linewidth * .pt),\n col = colour,\n fill = fill,\n lty = linetype\n )\n element_gp <- gpar(\n lwd = ggfun(\"len0_null\")(element$linewidth * .pt),\n col = element$colour,\n fill = fill_alpha(element$fill, element$alpha %||% NA),\n lty = element$linetype,\n lineend = element$lineend,\n linejoin = element$linejoin,\n linemitre = element$linemitre\n )\n }\n grid::polygonGrob(\n x = x, y = y,\n gp = ggfun(\"modify_list\")(element_gp, gp), ...\n )\n}\n\n#' Theme curve elements\n#'\n#' Draw curve.\n#'\n#' @inheritParams element_polygon\n#' @inheritParams grid::curveGrob\n#' @param arrow.fill Fill colour for arrows.\n#' @return A `element_curve` object\n#' @export\nelement_curve <- function(colour = NULL, linewidth = NULL, linetype = NULL,\n lineend = NULL, color = NULL, curvature = NULL,\n angle = NULL, ncp = NULL, shape = NULL,\n arrow = NULL, arrow.fill = NULL,\n inherit.blank = FALSE) {\n colour <- color %||% colour\n arrow.fill <- arrow.fill %||% colour\n arrow <- arrow %||% FALSE\n structure(\n list(\n colour = colour, linewidth = linewidth, linetype = linetype,\n lineend = lineend, curvature = curvature, angle = angle,\n ncp = ncp, shape = shape, arrow = arrow, arrow.fill = arrow.fill,\n inherit.blank = inherit.blank\n ),\n class = c(\"ggalign_element_curve\", \"element_curve\", \"element\")\n )\n}\n\n#' @importFrom grid gpar gTree gList\n#' @importFrom ggplot2 element_grob\n#' @export\nelement_grob.ggalign_element_curve <- function(element, x = 0:1, y = 0:1,\n colour = NULL, linewidth = NULL, linetype = NULL, lineend = NULL,\n arrow.fill = NULL,\n default.units = \"npc\",\n id = NULL,\n id.lengths = NULL, ...) {\n arrow <- if (is.logical(element$arrow) && !element$arrow) {\n NULL\n } else {\n element$arrow\n }\n if (is.null(arrow)) {\n arrow.fill <- colour\n element$arrow.fill <- element$colour\n }\n # The gp settings can override element_gp\n gp <- gpar(\n col = colour,\n fill = arrow.fill %||% colour,\n lwd = ggfun(\"len0_null\")(linewidth * .pt),\n lty = linetype,\n lineend = lineend\n )\n element_gp <- gpar(\n col = element$colour,\n fill = element$arrow.fill %||% element$colour,\n lwd = ggfun(\"len0_null\")(element$linewidth * .pt),\n lty = element$linetype,\n lineend = element$lineend\n )\n gp <- ggfun(\"modify_list\")(element_gp, gp)\n if (is.null(id)) {\n if (is.null(id.lengths)) {\n id <- vec_rep(1L, length(x))\n } else {\n id <- vec_rep_each(seq_along(id.lengths), id.lengths)\n }\n }\n index_list <- .subset2(vec_split(seq_along(x), id), \"val\")\n ans <- lapply(index_list, function(index) {\n grid::curveGrob(\n vec_slice(x, index),\n vec_slice(y, index),\n default.units = default.units,\n gp = gp[index],\n curvature = element$curvature,\n angle = element$angle,\n ncp = element$ncp,\n shape = element$shape,\n arrow = arrow,\n square = FALSE, squareShape = 1,\n inflect = FALSE, open = TRUE,\n ...\n )\n })\n gTree(children = inject(gList(!!!ans)))\n}\n\n##########################################################################\nelement_lengths <- function(.el, .fn, ...) {\n fields <- element_vec_fields(.el)\n if (is.null(fields)) 0L\n lengths(.el[fields])\n}\n\n#' Apply a function to the fields of an element object\n#'\n#' @description\n#' For an [`element`][ggplot2::element_blank] object, some fields are\n#' vectorized, while others are not. This function allows you to apply a\n#' function to the vectorized fields.\n#'\n#' The following helper functions are available:\n#'\n#' - `element_rep`: Applies [`rep()`].\n#' - `element_rep_len`: Applies [`rep_len()`].\n#' - `element_vec_recycle`: Applies [`vec_recycle()`][vctrs::vec_recycle].\n#' - `element_vec_rep`: Applies [`vec_rep()`][vctrs::vec_rep].\n#' - `element_vec_rep_each`: Applies [`vec_rep_each()`][vctrs::vec_rep_each].\n#' - `element_vec_slice`: Applies [`vec_slice()`][vctrs::vec_slice].\n#'\n#' @param .el An [`element`][ggplot2::element_blank] object.\n#' @param .fn The function to be applied to the vectorized fields of the element\n#' object.\n#' @param ... Additional arguments passed on to `fn`.\n#' @export\nelement_vec <- function(.el, .fn, ...) {\n fields <- element_vec_fields(.el)\n if (is.null(fields)) {\n return(.el)\n }\n .el[fields] <- lapply(.el[fields], function(value) {\n if (!is.null(value)) value <- .fn(value, ...)\n value\n })\n .el\n}\n\n#' @export\n#' @rdname element_vec\nelement_rep <- function(.el, ...) element_vec(.el, rep, ...)\n\n#' @param length.out Non-negative integer. The desired length of the output\n#' vector. Other inputs will be coerced to a double vector and the first element\n#' taken. Ignored if `NA` or invalid.\n#' @export\n#' @rdname element_vec\nelement_rep_len <- function(.el, length.out, ...) {\n element_vec(.el, rep_len, ..., length.out = length.out)\n}\n\n#' @inheritParams vctrs::vec_recycle\n#' @export\n#' @rdname element_vec\nelement_vec_recycle <- function(.el, size, ...) {\n element_vec(.el, vec_recycle, size = size, ...)\n}\n\n#' @inheritParams vctrs::vec_rep\n#' @export\n#' @rdname element_vec\nelement_vec_rep <- function(.el, times, ...) {\n element_vec(.el, vec_rep, times = times, ...)\n}\n\n#' @export\n#' @rdname element_vec\nelement_vec_rep_each <- function(.el, times, ...) {\n element_vec(.el, vec_rep_each, times = times, ...)\n}\n\n#' @inheritParams vctrs::vec_slice\n#' @importFrom grid is.unit\n#' @export\n#' @rdname element_vec\nelement_vec_slice <- function(.el, i, ...) {\n element_vec(.el, function(x) {\n if (is.unit(x)) x[i, ...] else vec_slice(x, i, ...)\n })\n}\n\nelement_vec_fields <- function(el) UseMethod(\"element_vec_fields\")\n\n#' @export\nelement_vec_fields.ggalign_element_polygon <- function(el) {\n c(\n \"fill\", \"colour\", \"linewidth\", \"linetype\",\n \"lineend\", \"linejoin\", \"linemitre\", \"alpha\"\n )\n}\n\n#' @export\nelement_vec_fields.element_blank <- function(el) NULL\n\n#' @export\nelement_vec_fields.element_polygon <- function(el) {\n c(\"fill\", \"colour\", \"linewidth\", \"linetype\")\n}\n\n#' @export\nelement_vec_fields.element_point <- function(el) {\n c(\"colour\", \"shape\", \"size\", \"fill\", \"stroke\")\n}\n\n#' @export\nelement_vec_fields.element_rect <- function(el) {\n c(\"fill\", \"colour\", \"linewidth\", \"linetype\")\n}\n\n#' @export\nelement_vec_fields.element_line <- function(el) {\n c(\"colour\", \"linewidth\", \"linetype\", \"lineend\")\n}\n\n#' @export\nelement_vec_fields.element_text <- function(el) {\n c(\n \"family\", \"face\", \"colour\", \"size\", \"hjust\", \"vjust\",\n \"angle\", \"lineheight\"\n )\n}\n\n#' @export\nelement_vec_fields.default <- function(el) stop_input_type(el, \"an element\")\n\n######################################################\n#' Remove scale expansion\n#'\n#' @param borders Which border should be removed? A string containing\n#' one or more of `r oxford_and(c(.tlbr, \"x\", \"y\"))`.\n#' @return An object which can be added to ggplot.\n#' @export\nno_expansion <- function(borders = \"tlbr\") {\n assert_string(borders, empty_ok = FALSE)\n if (grepl(\"[^tlbrxy]\", borders)) {\n cli_abort(sprintf(\n \"{.arg borders} can only contain the %s characters\",\n oxford_and(c(.tlbr, \"x\", \"y\"))\n ))\n }\n borders <- .subset(list(\n t = \"top\", l = \"left\", b = \"bottom\", r = \"right\",\n x = c(\"left\", \"right\"), y = c(\"bottom\", \"top\")\n ), split_position(borders))\n borders <- vec_unique(unlist(borders, recursive = FALSE, use.names = FALSE))\n # expansion in x-axis\n structure(list(borders = borders), class = c(\"ggalign_no_expansion\"))\n}\n\n#' @importFrom ggplot2 ggplot_add ggproto ggproto_parent\n#' @export\nggplot_add.ggalign_no_expansion <- function(object, plot, object_name, ...) {\n borders <- .subset2(object, \"borders\")\n ParentLayout <- plot$layout\n\n # tricks to ensure remove `coord` won't remove `no_expansion()`\n plot$layout <- ggproto(NULL, ParentLayout,\n setup_panel_params = function(self) {\n ParentCoord <- self$coord\n self$coord <- ggproto(NULL, ParentCoord,\n setup_panel_params = function(self, scale_x, scale_y,\n params = list()) {\n if (!is.null(scale_x)) {\n expansion <- scale_x$expand %|w|%\n if (packageVersion(\"ggplot2\") > \"3.5.2\") {\n ggfun(\"default_expansion\")(\n scale_y,\n # for ggplot2 > 3.5.2, expand was passed by\n # params\n expand = params$expand[c(4, 2)]\n )\n } else {\n ggfun(\"default_expansion\")(\n scale_y,\n # for ggplot2 > 3.5.2, expand was passed by\n # params\n expand = self$expand\n )\n }\n if (any(borders == \"left\")) {\n expansion[1:2] <- 0\n }\n if (any(borders == \"right\")) {\n expansion[3:4] <- 0\n }\n scale_x$expand <- expansion\n }\n if (!is.null(scale_y)) {\n expansion <- scale_y$expand %|w|%\n if (packageVersion(\"ggplot2\") > \"3.5.2\") {\n ggfun(\"default_expansion\")(\n scale_y,\n # for ggplot2 > 3.5.2, expand was passed by\n # params\n expand = params$expand[c(3, 1)]\n )\n } else {\n ggfun(\"default_expansion\")(\n scale_y,\n # for ggplot2 > 3.5.2, expand was passed by\n # params\n expand = self$expand\n )\n }\n if (any(borders == \"bottom\")) {\n expansion[1:2] <- 0\n }\n if (any(borders == \"top\")) {\n expansion[3:4] <- 0\n }\n scale_y$expand <- expansion\n }\n ggproto_parent(ParentCoord, self)$setup_panel_params(\n scale_x = scale_x, scale_y = scale_y, params = params\n )\n }\n )\n ggproto_parent(ParentLayout, self)$setup_panel_params()\n }\n )\n plot\n}\n"], ["/ggalign/R/layout-heatmap-oncoplot.R", "#' Create an OncoPrint\n#'\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' The `ggoncoplot()` function generates `oncoPrint` visualizations that display\n#' genetic alterations in a matrix format. This function is especially useful\n#' for visualizing complex genomic data, such as mutations, copy number\n#' variations, and other genomic alterations in cancer research.\n#'\n#' @details\n#' `ggoncoplot()` is a wrapper around the [`ggheatmap()`] function, designed to\n#' simplify the creation of `OncoPrint`-style visualizations. The function\n#' automatically processes the input character matrix by splitting the encoded\n#' alterations (delimited by `r oxford_or(c(\";\", \":\", \",\", \"|\"))`) into\n#' individual genomic events and unnesting the columns for visualization.\n#'\n#' @param data A character matrix which encodes the alterations, you can use\n#' `r oxford_or(c(\";\", \":\", \",\", \"|\"))` to separate multiple alterations.\n#' @inheritParams heatmap_layout\n#' @param map_width,map_height A named numeric value defines the width/height of\n#' each alterations.\n#'\n#' @param reorder_row A boolean value indicating whether to reorder the rows\n#' based on the frequency of alterations. You can set this to `FALSE`, then add\n#' `align_order(~rowSums(!is.na(.x)), reverse = TRUE)` to achieve the same\n#' result. You may also need to set `strit = FALSE` in [`align_order()`] if\n#' there are already groups.\n#'\n#' @param reorder_column A boolean value indicating whether to reorder the\n#' columns based on the characteristics of the alterations. You can set this to\n#' `FALSE`, then add `align_order2(memo_order)` to achieve the same result. You\n#' may also need to set `strit = FALSE` in [`align_order2()`] if there are\n#' already groups.\n#'\n#' @param remove_duplicates A logical value indicating whether to remove\n#' duplicated variants within the same cell.\n#'\n#' @param filling Same as [`ggheatmap()`], but only `\"tile\"` can be used.\n#' @examples\n#' # A simple example from `ComplexHeatmap`\n#' mat <- read.table(textConnection(\n#' \"s1,s2,s3\n#' g1,snv;indel,snv,indel\n#' g2,,snv;indel,snv\n#' g3,snv,,indel;snv\"\n#' ), row.names = 1, header = TRUE, sep = \",\", stringsAsFactors = FALSE)\n#'\n#' ggoncoplot(mat, map_width = c(snv = 0.5), map_height = c(indel = 0.9)) +\n#' guides(fill = \"none\") +\n#' anno_top(size = 0.5) +\n#' ggalign() +\n#' geom_bar(aes(fill = value), data = function(x) {\n#' subset(x, !is.na(value))\n#' }) +\n#' anno_right(size = 0.5) +\n#' ggalign() +\n#' geom_bar(aes(fill = value), orientation = \"y\", data = function(x) {\n#' subset(x, !is.na(value))\n#' }) &\n#' scale_fill_brewer(palette = \"Dark2\", na.translate = FALSE)\n#' @inherit heatmap_layout return\n#' @importFrom ggplot2 aes\n#' @export\nggoncoplot <- function(data = NULL, mapping = aes(), ...,\n map_width = NULL, map_height = NULL,\n reorder_row = reorder_column,\n reorder_column = TRUE,\n remove_duplicates = FALSE,\n width = NA, height = NA, filling = waiver(),\n theme = NULL, active = NULL) {\n UseMethod(\"ggoncoplot\")\n}\n\n#' @export\nggoncoplot.NULL <- function(data = NULL, mapping = aes(), ...) {\n cli_abort(\"{.fn ggoncoplot} only accept a valid character matrix\")\n}\n\n#' @export\nggoncoplot.functon <- ggoncoplot.NULL\n\n#' @export\nggoncoplot.formula <- ggoncoplot.functon\n\n#' @importFrom ggplot2 aes\n#' @importFrom rlang arg_match0\n#' @export\n#' @rdname ggoncoplot\nggoncoplot.default <- function(data = NULL, mapping = aes(), ...,\n map_width = NULL, map_height = NULL,\n reorder_row = reorder_column,\n reorder_column = TRUE,\n remove_duplicates = FALSE,\n width = NA, height = NA, filling = waiver(),\n theme = NULL, active = NULL) {\n # prepare the matrix\n data <- fortify_matrix(data = data, ...)\n if (!is.character(data)) {\n cli_abort(\"{.arg data} must be a character matrix\")\n }\n\n assert_bool(reorder_column)\n assert_bool(reorder_row)\n assert_bool(remove_duplicates)\n\n # convert empty string into NA\n data <- trimws(data, whitespace = \"[\\\\h\\\\v]\")\n data[data == \"\"] <- NA_character_\n\n # check filling\n if (isTRUE(filling) || is.waive(filling)) {\n filling <- \"tile\"\n } else if (isFALSE(filling)) {\n filling <- NULL\n } else if (!is.null(filling)) {\n filling <- arg_match0(filling, c(\"tile\", \"raster\"))\n if (filling == \"raster\") {\n cli_warn(\"Cannot use {.fn geom_raster} in oncoplot\")\n filling <- \"tile\"\n }\n }\n\n # prepare the plot data action\n pdata <- function(data) {\n vars <- strsplit(data$value, split = \"\\\\s*[;:,|]\\\\s*\", perl = TRUE)\n if (remove_duplicates) vars <- lapply(vars, vec_unique)\n lvls <- ggalign_lvls_get(data)\n data <- vec_rep_each(data, list_sizes(vars))\n value <- unlist(vars, recursive = FALSE, use.names = FALSE)\n if (!is.null(lvls)) value <- factor(value, levels = lvls)\n data$value <- value\n data\n }\n\n # draw the oncoplot\n ans <- heatmap_layout(\n data = data, mapping = mapping,\n width = width, height = height,\n theme = theme, active = active, filling = NULL\n ) -\n # set the default `scheme_data()`\n scheme_data(data = pdata)\n\n # prepare counts matrix to reorder the column or rows\n if (reorder_column || reorder_row) {\n counts <- !is.na(data)\n storage.mode(counts) <- \"integer\"\n weights <- rowSums(counts)\n row_index <- order(weights, decreasing = TRUE)\n }\n\n if (reorder_row) {\n ans <- ans + anno_left() + align_order(row_index, reverse = TRUE)\n }\n if (reorder_column) {\n column_scores <- .memo_order(vec_slice(counts, row_index))\n ans <- ans +\n anno_top() +\n align_order(order(column_scores, decreasing = TRUE))\n }\n\n # reset the active context\n ans <- ans + quad_active()\n if (!is.null(filling)) {\n # we always make sure heatmap body has such action data\n ans <- ans + scheme_data(data = pdata)\n\n # set mapping for width and height\n tile_mapping <- aes(\n .data$.x, .data$.y,\n fill = .data$value,\n width = replace_na(map_width[.data$value], 1),\n height = replace_na(map_height[.data$value], 1)\n )\n if (!is.null(map_width)) {\n if (!rlang::is_named(map_width) || !is.numeric(map_width)) {\n cli_abort(\"{.arg map_width} must be a named numeric\")\n }\n } else {\n tile_mapping$width <- NULL\n }\n if (!is.null(map_height)) {\n if (!rlang::is_named(map_height) || !is.numeric(map_height)) {\n cli_abort(\"{.arg map_height} must be a named numeric\")\n }\n } else {\n tile_mapping$height <- NULL\n }\n # check if user has provided and manual fill mapping\n if (!is.null(.subset2(ans@plot$mapping, \"fill\"))) {\n tile_mapping$fill <- NULL\n }\n ans <- ans + ggplot2::geom_tile(tile_mapping)\n }\n ans\n}\n\n#' Sort matrix for better visualization\n#'\n#' Helper function used to order the Oncoplot samples. Typically, you would use\n#' this in combination with [`align_order2()`], e.g.,\n#' `align_order2(memo_order)`.\n#'\n#' @param x A matrix, where `NA` values will be treated as empty.\n#' @return A vector of ordering weights.\n#' @export\nmemo_order <- function(x) {\n # For `align_order2()`, rows are considered as the observations\n # `.memo_order` will regard the columns as the observations\n .memo_order(t(x), counts = FALSE, reorder_rows = TRUE)\n}\n\n# Following code is modified from\n# \n.memo_order <- function(x, counts = TRUE, reorder_rows = FALSE) {\n if (!isTRUE(counts)) {\n x <- !is.na(x)\n storage.mode(x) <- \"integer\"\n }\n if (isTRUE(reorder_rows)) {\n row_index <- order(rowSums(x), decreasing = TRUE)\n x <- vec_slice(x, row_index)\n }\n structure(\n apply(x, 2L, function(x) {\n score <- 2^(length(x) - seq_along(x))\n score[x == 0L] <- 0\n sum(score)\n }),\n class = \"memo_weights\"\n )\n}\n\n#' @export\n#' @rdname order2\norder2.memo_weights <- function(x) order(x, decreasing = TRUE)\n"], ["/ggalign/R/alignpatch-area.R", "# We are removing the patchwork dependency by defining our own version of\n# patchwork::area, as some desired features won't be merged (see this\n# https://github.com/thomasp85/patchwork/issues/379). Therefore, ggalign will\n# retain `alignpatch-*` scripts.\n\n#' Define the plotting areas in `align_plots`\n#'\n#' @inherit patchwork::area\n#' @details\n#' The grid that the areas are specified in reference to enumerate rows from top\n#' to bottom, and coloumns from left to right. This means that `t` and `l`\n#' should always be less or equal to `b` and `r` respectively. Instead of\n#' specifying area placement with a combination of `area()` calls, it is\n#' possible to instead pass in a single string\n#'\n#' ```\n#' areas <- c(area(1, 1, 2, 1),\n#' area(2, 3, 3, 3))\n#' ```\n#'\n#' is equivalent to\n#'\n#' ```\n#' areas < -\"A##\n#' A#B\n#' ##B\"\n#' ```\n#' @return A `ggalign_area` object.\n#' @examples\n#' p1 <- ggplot(mtcars) +\n#' geom_point(aes(mpg, disp))\n#' p2 <- ggplot(mtcars) +\n#' geom_boxplot(aes(gear, disp, group = gear))\n#' p3 <- ggplot(mtcars) +\n#' geom_bar(aes(gear)) +\n#' facet_wrap(~cyl)\n#'\n#' layout <- c(\n#' area(1, 1),\n#' area(1, 3, 3),\n#' area(3, 1, 3, 2)\n#' )\n#'\n#' # Show the layout to make sure it looks as it should\n#' plot(layout)\n#'\n#' # Apply it to a alignpatches\n#' align_plots(p1, p2, p3, design = layout)\n#' @export\narea <- function(t, l, b = t, r = l) {\n if (missing(t) || missing(l)) {\n one_area <- list(\n t = integer(0L),\n l = integer(0L),\n b = integer(0L),\n r = integer(0L)\n )\n } else {\n one_area <- df_list(\n t = vec_cast(t, integer()),\n l = vec_cast(l, integer()),\n b = vec_cast(b, integer()),\n r = vec_cast(r, integer())\n )\n if (any(.subset2(one_area, \"t\") > .subset2(one_area, \"b\"))) {\n cli_abort(\"{.arg t} must be less than {.arg b}\")\n }\n if (any(.subset2(one_area, \"l\") > .subset2(one_area, \"r\"))) {\n cli_abort(\"{.arg l} must be less than {.arg r}\")\n }\n }\n new_areas(one_area)\n}\n\n# Define a custom S3 class `ggalign_area`, without using S7 directly\n# Patchwork expects traditional S3 classes, and S7 classes are not fully\n# interoperable with patchwork layouts.\nS3_area <- S7::new_S3_class(\"ggalign_area\")\n\nnew_areas <- function(x) new_rcrd(x, class = c(\"ggalign_area\", \"patch_area\"))\n\ncreate_area <- function(ncol, nrow, byrow) {\n mat <- matrix(seq_len(ncol * nrow),\n nrow = nrow, ncol = ncol, byrow = byrow\n )\n ind <- as.vector(mat)\n ind <- match(seq_along(ind), ind)\n area(t = row(mat)[ind], l = col(mat)[ind])\n}\n\n#' @export\nobj_print_data.ggalign_area <- function(x, ...) {\n x <- vec_data(x)\n if (vec_size(x) > 0) {\n x <- vec_set_names(x, paste0(vec_seq_along(x), \": \"))\n print(x = x, ..., quote = FALSE)\n } else {\n cat(\" \", names(x), \"\\n\", sep = \" \")\n }\n}\n\n#' @export\nobj_print_footer.ggalign_area <- function(x, ...) {\n if (vec_size(x) == 0) {\n ncols <- 0\n nrows <- 0\n } else {\n ncols <- max(field(x, \"r\"))\n nrows <- max(field(x, \"b\"))\n }\n cat(\"\\n\\n\")\n}\n\n#' @export\nvec_ptype_abbr.ggalign_area <- function(x, ...) \"areas\"\n\ntrim_area <- function(area) {\n area <- vec_data(area)\n w <- min(.subset2(area, \"l\"), .subset2(area, \"r\"))\n h <- min(.subset2(area, \"t\"), .subset2(area, \"b\"))\n area$l <- .subset2(area, \"l\") - w + 1L\n area$r <- .subset2(area, \"r\") - w + 1L\n area$t <- .subset2(area, \"t\") - h + 1L\n area$b <- .subset2(area, \"b\") - h + 1L\n new_areas(area)\n}\n\nas_areas <- function(x) UseMethod(\"as_areas\")\n\n#' @export\nas_areas.default <- function(x) {\n cli_abort(\"Cannot convert {.obj_type_friendly {x}} into a design area\")\n}\n\n#' @export\nas_areas.NULL <- function(x) NULL\n\n#' @export\nas_areas.ggalign_area <- function(x) x\n\n#' @export\nas_areas.character <- function(x) {\n call <- current_call() # used for message only\n # split into rows\n x <- .subset2(strsplit(x, split = \"\\n\"), 1L)\n x <- lapply(x, trimws)\n if (identical(x[[1L]], \"\")) x[[1L]] <- NULL\n if (identical(x[[length(x)]], \"\")) x[[length(x)]] <- NULL\n x <- lapply(x, function(x) .subset2(strsplit(x, split = \"\"), 1L))\n ncols <- list_sizes(x)\n ncol <- .subset(ncols, 1L)\n if (any(ncols != ncol)) {\n cli_abort(\"character layout must be rectangular\", call = call)\n }\n row <- rep(seq_along(x), each = ncol)\n col <- rep(seq_len(ncol), length(x))\n x <- unlist(x, use.names = FALSE)\n # here, area will be reordered by the levels of `x`\n area_list <- imap(split(seq_along(x), x), function(i, name) {\n if (identical(name, \"#\")) {\n return(area())\n }\n area_rows <- range(row[i])\n area_cols <- range(col[i])\n t <- .subset(area_rows, 1L)\n l <- .subset(area_cols, 1L)\n b <- .subset(area_rows, 2L)\n r <- .subset(area_cols, 2L)\n if (!all(x[row >= t & row <= b & col >= l & col <= r] ==\n x[.subset(i, 1L)])) {\n cli_abort(\"Patch areas must be rectangular\", call = call)\n }\n new_areas(list(t = t, l = l, b = b, r = r))\n })\n vec_c(!!!vec_set_names(area_list, NULL))\n}\n\n# For area from patchwork\n#' @export\nas_areas.patch_area <- function(x) add_class(x, \"ggalign_area\")\n\n#' @importFrom grid unit\n#' @importFrom ggplot2 aes margin theme ggplot\n#' @importFrom utils packageVersion\n#' @export\nplot.ggalign_area <- function(x, ...) {\n data <- vec_data(x)\n data$l <- data$l - 0.45\n data$r <- data$r + 0.45\n data$t <- data$t - 0.45\n data$b <- data$b + 0.45\n data$name <- as.factor(vec_seq_along(x))\n b_fun <- function(lim) {\n if (lim[1] < lim[2]) {\n lim <- seq(floor(lim[1]), ceiling(lim[2]), by = 1)\n } else {\n lim <- seq(ceiling(lim[1]), floor(lim[2]), by = -1)\n }\n lim[-c(1, length(lim))]\n }\n ggplot(data) +\n ggplot2::geom_rect(aes(\n xmin = .data$l, xmax = .data$r,\n ymin = .data$t, ymax = .data$b, fill = .data$name\n ), alpha = 0.3) +\n ggplot2::scale_y_reverse(breaks = b_fun, expand = c(0, 0.04)) +\n ggplot2::scale_x_continuous(\n breaks = b_fun, expand = c(0, 0.04), position = \"top\"\n ) +\n ggplot2::labs(fill = \"Patch\") +\n ggplot2::theme_void() +\n theme(\n panel.grid.minor = if (packageVersion(\"ggplot2\") >= \"3.4.0\") {\n ggplot2::element_line(linewidth = 0.5, colour = \"grey\")\n } else {\n ggplot2::element_line(size = 0.5, colour = \"grey\")\n },\n axis.text = ggplot2::element_text(),\n axis.ticks.length = unit(3, \"mm\"),\n plot.margin = margin(10, 10, 10, 10)\n )\n}\n"], ["/ggalign/R/fortify-matrix-.R", "#' Build a Matrix\n#'\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' This function converts various objects into a matrix format. By default, it\n#' calls [`as.matrix()`] to build a matrix.\n#'\n#' @param data An object to be converted into a matrix.\n#' @param ... Additional arguments passed to methods.\n#' @param data_arg The argument name for `data`. Developers can use it to\n#' improve messages. Not used by the user.\n#' @param call The execution environment where `data` and other arguments for\n#' the method are collected. Developers can use it to improve messages. Not\n#' used by the user.\n#' @return A matrix.\n#' @eval\n#' rd_collect_family(\"fortify_matrix\", \"`fortify_matrix` method collections\")\n#' @export\nfortify_matrix <- function(data, ..., data_arg = NULL,\n call = NULL) {\n UseMethod(\"fortify_matrix\")\n}\n\n#' @inheritParams rlang::args_dots_empty\n#' @inherit fortify_matrix title return\n#' @description\n#' By default, it calls [`as.matrix()`] to build a matrix.\n#' @inheritParams fortify_matrix\n#' @family fortify_matrix\n#' @importFrom rlang try_fetch\n#' @export\nfortify_matrix.default <- function(data, ..., data_arg = NULL,\n call = NULL) {\n call <- call %||% current_call()\n data_arg <- data_arg %||% \"data\"\n rlang::check_dots_empty(call = call)\n try_fetch(\n as.matrix(data),\n error = function(cnd) {\n cli_abort(\n paste0(\n \"{.arg {data_arg}} must be a {.cls matrix}, \",\n \"or an object coercible by {.fn fortify_matrix}, or a valid \",\n \"{.cls matrix}-like object coercible by {.fn as.matrix}\"\n ),\n call = call\n )\n }\n )\n}\n\n#' @export\nfortify_matrix.waiver <- function(data, ..., data_arg = NULL,\n call = NULL) {\n call <- call %||% current_call()\n rlang::check_dots_empty(call = call)\n data\n}\n\n#' @export\nfortify_matrix.NULL <- fortify_matrix.waiver\n\n#' @export\nfortify_matrix.function <- fortify_matrix.waiver\n\n#' @export\nfortify_matrix.formula <- function(data, ..., data_arg = NULL,\n call = NULL) {\n call <- call %||% current_call()\n rlang::check_dots_empty(call = call)\n rlang::as_function(data)\n}\n"], ["/ggalign/R/genomic-helper.R", "#' Calculate inter-region distances for genomic rainfall plots\n#'\n#' This function computes distances between adjacent genomic regions, grouped by\n#' chromosome. Useful for visualizing clustering or dispersion of genomic\n#' features.\n#'\n#' @param region A data frame with at least 3 columns: chromosome, start, and\n#' end.\n#' @param mode How to assign distance for intermediate regions: one of `\"min\"`,\n#' `\"max\"`, `\"mean\"`, `\"left\"`, or `\"right\"`.\n#' @details\n#' The distance between two adjacent regions is calculated as the number of\n#' bases between the **end position of the upstream region** and the\n#' **start position of the downstream region**. If two regions overlap or are\n#' adjacent (≤1 bp apart), the distance is set to `0`. The resulting distance is\n#' assigned to each region according to the selected `mode`:\n#'\n#' - `\"left\"`: assign the distance to the upstream region\n#' - `\"right\"`: assign to the downstream region\n#' - `\"min\"` / `\"max\"` / `\"mean\"`: for intermediate regions, calculate the\n#' minimum, maximum, or average of the distances to neighboring regions\n#'\n#' @return A data frame with an additional `dist` column.\n#' @export\ngenomic_dist <- function(region, mode = NULL) {\n # Check input validity\n if (is.null(mode)) {\n mode <- \"min\"\n } else {\n mode <- arg_match0(mode, c(\"min\", \"max\", \"mean\", \"left\", \"right\"))\n }\n if (!is.data.frame(region) || ncol(region) < 3L) {\n cli_abort(\"{.arg region} must have at least 3 columns: chromosome, start, and end\")\n }\n if (anyNA(region[[1L]]) || anyNA(region[[2L]]) || anyNA(region[[3L]])) {\n cli_abort(\"Columns 1, 2, and 3 of {.arg region} must not contain missing values\")\n }\n if (!is.numeric(region[[2L]]) || !is.numeric(region[[3L]])) {\n cli_abort(\"Columns 2 and 3 of {.arg region} must be numeric (start and end positions)\")\n }\n if (any(region[[2L]] > region[[3L]])) {\n cli_abort(\"Column 2 (start) must not be greater than column 3 (end) in any row of {.arg region}\")\n }\n\n # Split the region data frame by chromosome (first column)\n groups <- vec_split(region, .subset2(region, 1L))\n dist_list <- lapply(.subset2(groups, \"val\"), function(d) {\n n <- nrow(d)\n if (n < 2L) {\n d$dist <- NA_real_\n return(d)\n }\n\n # Sort regions by start, then end positions\n ordering <- order(.subset2(d, 2L), .subset2(d, 3L))\n\n # Compute distances between adjacent regions\n dists <- vapply(seq_len(n - 1L), function(i) {\n first <- vec_slice(d, ordering[i])\n second <- vec_slice(d, ordering[i + 1])\n out <- .subset2(second, 2L) - .subset2(first, 3L)\n # If overlapping or adjacent (≤1 bp), treat distance as 0\n if (out <= 1L) out <- 0L else out <- as.integer(out)\n out\n }, integer(1L), USE.NAMES = FALSE)\n\n # If only two regions, just repeat the distance\n if (n == 2L) {\n d$dist <- rep_len(dists, n)\n return(d)\n }\n\n # For intermediate regions (not first or last), choose how to assign\n # distance\n d1 <- dists[seq_len(n - 2L)]\n d2 <- dists[2:(n - 1L)]\n if (mode == \"min\") {\n body_dists <- pmin(d1, d2)\n } else if (mode == \"max\") {\n body_dists <- pmax(d1, d2)\n } else if (mode == \"mean\") {\n body_dists <- (d1 + d2) / 2L\n } else if (mode == \"left\") {\n body_dists <- d1\n } else if (mode == \"right\") {\n body_dists <- d2\n }\n\n # Combine distances: head, body, and tail\n d$dist <- c(dists[1L], body_dists, dists[n - 1L])[order(ordering)]\n d\n })\n vec_rbind(!!!dist_list)\n}\n\n#' Calculate Genomic Region Density\n#'\n#' Computes the density or count of genomic regions in sliding or fixed windows\n#' across the genome. The density can be reported as the percentage of uncovered\n#' bases or the number of overlapping regions within each window.\n#'\n#' This function splits the input by chromosome and tiles the genomic space\n#' into windows, optionally overlapping. For each window, it calculates:\n#'\n#' - the number of regions that overlap it (if `mode = \"count\"`), or\n#' - the fraction of bases covered by any region (if `mode = \"percent\"`).\n#'\n#' @param region A data frame with at least 3 columns: chromosome, start, and\n#' end.\n#' - Column 1: character or factor, chromosome name.\n#' - Column 2: numeric, start position (must be ≤ end).\n#' - Column 3: numeric, end position.\n#' @param window_size Numeric, the width of each window (default is `1e+07`).\n#' Ignored if `n_window` is specified.\n#' @param n_window Integer, the number of windows per chromosome. If provided,\n#' overrides `window_size` and evenly splits the chromosome into `n_window`\n#' (non-overlapping) or `2*n_window - 1` (overlapping) windows.\n#' @param overlap Logical, whether to use overlapping windows (default `TRUE`).\n#' Overlapping windows are spaced by half the window size.\n#' @param mode Character, either `\"coverage\"` or `\"count\"`:\n#' - `\"count\"`: reports the number of regions overlapping each window.\n#' - `\"coverage\"`: reports the fraction of each window covered by regions.\n#' @param seqlengths Optional named vector of chromosome lengths. If missing,\n#' the maximum `end` value in the input is used as the chromosome length.\n#'\n#' @return A data frame with columns:\n#' - `seqnames`: The sequence (e.g., chromosome) names.\n#' - `start`: start of each window\n#' - `end`: end of each window\n#' - `density`: the region count or covered percent, depending on `mode`\n#'\n#' @examples\n#' region <- data.frame(\n#' chr = rep(\"chr1\", 3),\n#' start = c(100, 5000000, 15000000),\n#' end = c(2000000, 7000000, 17000000)\n#' )\n#' genomic_density(region, window_size = 1e7, mode = \"count\")\n#' genomic_density(region, n_window = 3, overlap = FALSE, mode = \"coverage\")\n#'\n#' @export\ngenomic_density <- function(region, window_size = 1e+07, n_window = NULL,\n overlap = TRUE, mode = c(\"coverage\", \"count\"),\n seqlengths = NULL) {\n # Check input validity\n assert_number_whole(window_size, allow_null = TRUE, min = 1)\n assert_number_whole(n_window, allow_null = TRUE, min = 1)\n if (is.null(window_size) && is.null(n_window)) {\n cli_abort(c(\n \"Both {.arg window_size} and {.arg n_window} are {.val NULL}.\",\n \"i\" = \"You must supply at least one of these arguments to define the binning strategy.\"\n ))\n }\n assert_bool(overlap)\n if (is.null(mode)) {\n mode <- \"coverage\"\n } else {\n mode <- arg_match0(mode, c(\"coverage\", \"count\"))\n }\n if (!is.data.frame(region) || ncol(region) < 3L) {\n cli_abort(\"{.arg region} must have at least 3 columns: chromosome, start, and end\")\n }\n if (anyNA(region[[1L]]) || anyNA(region[[2L]]) || anyNA(region[[3L]])) {\n cli_abort(\"Columns 1, 2, and 3 of {.arg region} must not contain missing values\")\n }\n if (!is.numeric(region[[2L]]) || !is.numeric(region[[3L]])) {\n cli_abort(\"Columns 2 and 3 of {.arg region} must be numeric (start and end positions)\")\n }\n if (any(region[[2L]] > region[[3L]])) {\n cli_abort(\"Column 2 (start) must not be greater than column 3 (end) in any row of {.arg region}\")\n }\n\n # Split the region data frame by chromosome (first column)\n groups <- vec_split(region, .subset2(region, 1L))\n density_list <- lapply(.subset2(groups, \"val\"), function(d) {\n chr <- .subset2(d, 1L)[1L]\n if (is.null(seqlengths)) {\n max_pos <- max(.subset2(region, 3L))\n } else {\n max_pos <- seqlengths[chr]\n if (is.na(max_pos)) {\n cli_abort(\"Chromosome {.val {chr}} is not found in {.arg seqlengths}. Please check that all chromosomes in {.arg region} have corresponding sequence lengths.\")\n }\n }\n if (overlap) {\n if (is.null(n_window)) {\n # Half-step sliding windows: start at 1, step = half window size\n b <- seq(0L, max_pos, by = window_size %/% 2L)\n s <- b[-length(b)]\n s <- s[-length(s)] + 1L\n e <- s + window_size - 1L\n } else {\n b <- seq(0L, max_pos, length.out = 2L * n_window + 1L)\n s <- b[-length(b)]\n s <- s[-length(s)] + 1L\n e <- s + b[3L] - b[1L] - 1L\n }\n } else {\n if (is.null(n_window)) {\n b <- seq(0L, max_pos, by = window_size)\n s <- b[-length(b)] + 1L\n e <- s + window_size - 1L\n } else {\n b <- seq(0, max_pos, length.out = n_window + 1L)\n s <- b[-length(b)] + 1L\n e <- s + b[2L] - b[1L]\n }\n }\n s <- as.integer(s)\n e <- as.integer(e)\n region_s <- .subset2(d, 2L)\n region_e <- .subset2(d, 3L)\n if (mode == \"count\") {\n # For each window, count how many regions overlap with it\n density <- vapply(seq_along(s), function(i) {\n si <- s[i]\n ei <- e[i]\n sum(!(region_s > ei | region_e < si))\n }, integer(1L), USE.NAMES = FALSE)\n } else {\n region_s <- as.integer(ceiling(region_s))\n region_e <- as.integer(floor(region_e))\n # For each window, calculate the proportion of bases covered by\n # regions\n density <- vapply(seq_along(s), function(i) {\n si <- s[i]\n ei <- e[i]\n # Keep regions that overlap with current window\n keep <- !(region_s > ei | region_e < si)\n\n # Clip regions to fit within the current window\n region_s_used <- pmax(region_s[keep], si)\n region_e_used <- pmin(region_e[keep], ei)\n\n # If no overlapping region, coverage is zero\n if (length(region_s_used) == 0L) {\n return(0)\n }\n\n # Sort intervals by start, then end\n ordering <- order(region_s_used, region_e_used)\n region_s_used <- region_s_used[ordering]\n region_e_used <- region_e_used[ordering]\n\n # Initialize with the first interval\n start <- region_s_used[1L]\n end <- region_e_used[1L]\n\n # If there's only one interval, just compute its coverage\n if (length(region_s_used) == 1L) {\n cov <- end - start + 1L\n return(cov / (ei - si + 1L))\n }\n # Merge overlapping/adjacent intervals and compute total\n # coverage\n cov <- 0L\n for (j in 2:length(region_s_used)) {\n if (region_s_used[j] - end <= 1L) {\n end <- max(end, region_e_used[j])\n } else {\n cov <- cov + (end - start + 1L)\n start <- region_s_used[j]\n end <- region_e_used[j]\n }\n }\n cov <- cov + (end - start + 1L)\n cov / (ei - si + 1L)\n }, numeric(1L), USE.NAMES = FALSE)\n }\n data_frame0(seqnames = chr, start = s, end = e, density = density)\n })\n vec_rbind(!!!density_list)\n}\n"], ["/ggalign/R/ggplot-coord-circle.R", "#' Polar Coordinates with Enhanced Controls\n#'\n#' An extended version of [`coord_radial()`][ggplot2::coord_radial], providing\n#' additional customization options.\n#'\n#' @inheritParams ggplot2::coord_radial\n#' @param thetalim,rlim Limits for the `theta` and `r` axes.\n#' @param inner.radius A numeric in `[0, 1)` indicates the inner radius.\n#' @param outer.radius A numeric in `(0, 1]` indicates the outer radius.\n#' [`coord_radial()`][ggplot2::coord_radial] by default uses `0.8`.\n#' @examples\n#' ggplot(mtcars, aes(disp, mpg)) +\n#' geom_point() +\n#' coord_circle(\n#' start = -0.4 * pi, end = 0.4 * pi,\n#' inner.radius = 0.3, outer.radius = 1\n#' )\n#' ggplot(mtcars, aes(disp, mpg)) +\n#' geom_point() +\n#' coord_circle(\n#' start = -0.4 * pi, end = 0.4 * pi,\n#' inner.radius = 0.3, outer.radius = 0.5\n#' )\n#' @importFrom ggplot2 ggproto\n#' @importFrom rlang arg_match0\n#' @export\ncoord_circle <- function(theta = \"x\", start = 0, end = NULL,\n thetalim = NULL, rlim = NULL, expand = FALSE,\n direction = 1, clip = \"off\",\n r.axis.inside = NULL, rotate.angle = FALSE,\n inner.radius = 0, outer.radius = 0.95) {\n theta <- arg_match0(theta, c(\"x\", \"y\"))\n assert_number_decimal(start, allow_infinite = FALSE)\n assert_number_decimal(end, allow_infinite = FALSE, allow_null = TRUE)\n if (packageVersion(\"ggplot2\") <= \"3.5.2\") {\n assert_bool(expand)\n }\n clip <- arg_match0(clip, c(\"off\", \"on\"))\n\n valid_inside_axis <- .rlang_check_bool(r.axis.inside,\n allow_null = TRUE\n ) ||\n .rlang_check_number(r.axis.inside,\n allow_decimal = TRUE, allow_infinite = FALSE\n ) == 0L\n if (!valid_inside_axis) {\n cli_abort(\n \"{.arg r.axis.inside} must be a single boolean value or a number\"\n )\n }\n\n assert_bool(rotate.angle)\n assert_number_decimal(inner.radius,\n min = 0, max = 1,\n allow_infinite = FALSE\n )\n assert_number_decimal(outer.radius,\n min = 0, max = 1,\n allow_infinite = FALSE\n )\n if (inner.radius >= outer.radius) {\n cli_abort(\n \"{.arg outer.radius} must be larger than {.arg inner.radius}\"\n )\n }\n r <- if (theta == \"x\") \"y\" else \"x\"\n\n arc <- c(start, end %||% (start + 2 * pi))\n if (arc[1] > arc[2]) {\n n_rotate <- ((arc[1] - arc[2]) %/% (2 * pi)) + 1\n arc[1] <- arc[1] - n_rotate * 2 * pi\n }\n r.axis.inside <- r.axis.inside %||% !(abs(arc[2] - arc[1]) >= 1.999 * pi)\n inner_radius <- c(inner.radius, outer.radius) / 2\n\n ggproto(NULL, CoordCircle,\n limits = list(theta = thetalim, r = rlim),\n theta = theta,\n r = r,\n arc = arc,\n expand = expand,\n direction = sign(direction),\n r_axis_inside = r.axis.inside,\n rotate_angle = rotate.angle,\n inner_radius = inner_radius,\n clip = clip\n )\n}\n\n#' @importFrom ggplot2 ggproto_parent\ncircle_panel_params <- function(self, scale_x, scale_y, params = list()) {\n out <- ggproto_parent(ggplot2::CoordRadial, self)$setup_panel_params(\n scale_x, scale_y, params\n )\n if (packageVersion(\"ggplot2\") <= \"3.5.2\") {\n if (self$theta == \"x\") {\n xlimits <- self$limits$theta\n ylimits <- self$limits$r\n } else {\n xlimits <- self$limits$r\n ylimits <- self$limits$theta\n }\n new <- c(\n view_scales_polar(\n scale_x, self$theta, xlimits,\n expand = params$expand[c(4, 2)] %||% self$expand\n ),\n view_scales_polar(\n scale_y, self$theta, ylimits,\n expand = params$expand[c(3, 1)] %||% self$expand\n )\n )\n out[names(new)] <- new\n }\n out$bbox <- ggfun(\"polar_bbox\")(\n self$arc, margin = c(0, 0, 0, 0),\n inner_radius = self$inner_radius\n )\n out\n}\n\nview_scales_polar <- function(scale, theta, coord_limits, expand = TRUE) {\n aesthetic <- scale$aesthetics[1]\n is_theta <- theta == aesthetic\n name <- if (is_theta) \"theta\" else \"r\"\n expansion <- ggfun(\"default_expansion\")(scale, expand = expand)\n limits <- scale$get_limits()\n continuous_range <- ggfun(\"expand_limits_scale\")(\n scale, expansion, limits, coord_limits = coord_limits\n )\n primary <- ggfun(\"view_scale_primary\")(scale, limits, continuous_range)\n view_scales <- list(\n primary,\n sec = ggfun(\"view_scale_secondary\")(scale, limits, continuous_range),\n major = primary$map(primary$get_breaks()),\n minor = primary$map(primary$get_breaks_minor()),\n range = continuous_range\n )\n names(view_scales) <- c(name, paste0(name, \".\", names(view_scales)[-1]))\n view_scales\n}\n\n#' @importFrom ggplot2 ggproto\nCoordCircle <- ggproto(\n \"CoordCircle\", ggplot2::CoordRadial,\n setup_panel_params = circle_panel_params\n)\n"], ["/ggalign/R/alignpatch-.R", "# here is copied from patchwork\n# we modified the `patchwork` package for following reasons:\n# 1. collect guides for each side (should be merged into patchwork, not allowed\n# to be merged: https://github.com/thomasp85/patchwork/issues/379).\n# 2. `free_*()` functions: see https://github.com/thomasp85/patchwork/issues/379\n# - `free_align()`: added\n# - `free_border()`: not added\n# - `free_lab()`: added\n# - `free_space()`: added\n# - `free_vp()`: not added\n# 3. Added titles around the plot top, left, bottom, and right\n# (`patch_titles()`)\nTABLE_ROWS <- 18L + 2L\nTABLE_COLS <- 15L + 2L\n\nTOP_BORDER <- 9L + 1L\nLEFT_BORDER <- 7L + 1L\nBOTTOM_BORDER <- 8L + 1L\nRIGHT_BORDER <- 7L + 1L\n\n# top-bottom\n# 1: margin\n# 2: tag\n# 3: title\n# 4: subtitle\n# 5: guide-box-top\n# 6: legend.box.spacing\n# feature: insert patch title\n# 7: xlab-t\n# strip.placement = \"inside\"/\"outside\"\n# 8: axis-t/strip-t\n# 9: strip-t/axis-t\n# 10: panel\n# 11: strip-b\n# 12: axis-b\n# 13: xlab-b\n# feature: insert patch title\n# 14: legend.box.spacing\n# 15: guide-box-bottom\n# 16: caption\n# 17: tag\n# 18: margin\n\n# left-right\n#\n# 1: margin\n# 2: tag\n# 3: guide-box-left\n# 4: legend.box.spacing\n# feature: insert patch title\n# 5: ylab-l\n# 6: axis-l\n# 8: panel\n# 10: axis-r\n# 11: ylab-r\n# feature: insert patch title\n# 12: legend.box.spacing\n# 13: guide-box-right\n# 14: tag\n# 15: margin\n\n.TLBR <- c(\"top\", \"left\", \"bottom\", \"right\")\n.tlbr <- c(\"t\", \"l\", \"b\", \"r\")\n\n# position is a single string contains `.tlbr`\nsetdiff_position <- function(x, y) gsub(sprintf(\"[%s]\", y), \"\", x)\nunion_position <- function(x, y) paste0(x, gsub(sprintf(\"[%s]\", x), \"\", y))\nsplit_position <- function(x) {\n vec_unique(.subset2(strsplit(x, \"\", fixed = TRUE), 1L))\n}\n\n# pos is an atomic character\nsetup_pos <- function(x) unname(complete_pos(split_position(x)))\n\nsetup_guides <- function(x) {\n .subset(\n c(t = \"top\", l = \"left\", b = \"bottom\", r = \"right\", i = \"inside\"),\n split_position(x)\n )\n}\n\ncomplete_pos <- function(x) {\n .subset(c(t = \"top\", l = \"left\", b = \"bottom\", r = \"right\"), x)\n}\n\nopposite_pos <- function(pos) {\n switch(pos,\n top = \"bottom\",\n bottom = \"top\",\n left = \"right\",\n right = \"left\"\n )\n}\n\n#' @importFrom ggplot2 zeroGrob\n#' @importFrom gtable gtable gtable_add_grob\n#' @importFrom grid unit\nmake_patch_table <- function() {\n widths <- unit(rep(0L, TABLE_COLS), \"mm\")\n widths[LEFT_BORDER + 1L] <- unit(1L, \"null\")\n heights <- unit(rep(0L, TABLE_ROWS), \"mm\")\n heights[TOP_BORDER + 1L] <- unit(1L, \"null\")\n ans <- gtable(widths, heights)\n gtable_add_grob(ans,\n list(zeroGrob()), TOP_BORDER + 1L, LEFT_BORDER + 1L,\n z = -Inf, name = \"panel-area\"\n )\n}\n\n#' Generate a plot grob.\n#'\n#' @param x An object to be converted into a [grob][grid::grob].\n#' @return A [`grob()`][grid::grob] object.\n#' @examples\n#' ggalignGrob(ggplot())\n#' @export\nggalignGrob <- function(x) {\n ggalign_gtable(ggalign_build(x))\n}\n\n# Now, we only define `ggalign_gtable` method for `alignpatches` and `ggplot`\n# `ggalign_build` must return these objects\nggalign_build <- function(x) UseMethod(\"ggalign_build\")\n\nggalign_gtable <- function(x) UseMethod(\"ggalign_gtable\")\n\n#' @export\nggalign_gtable.gtable <- function(x) x\n\n#' Prepare plots to be aligned with `align_plots`\n#'\n#' @param x A plot object to be prepared for alignment.\n#' @details\n#' `ggalign` has implement `alignpatch` method for following objects:\n#' - [`ggplot`][ggplot2::ggplot]\n#' - [`alignpatches`][align_plots]\n#' - [`wrapped_plot`][ggwrap]\n#' - [`patch`][patchwork::patchGrob]\n#' - [`wrapped_patch`][patchwork::wrap_elements]\n#' - [`spacer`][patchwork::plot_spacer]\n#'\n#' @return A `Patch` object.\n#' @examples\n#' alignpatch(ggplot())\n#' @seealso [`align_plots()`]\n#' @export\n#' @keywords internal\nalignpatch <- function(x) UseMethod(\"alignpatch\")\n\n#' @export\nalignpatch.default <- function(x) {\n cli_abort(\"Cannot align {.obj_type_friendly {x}}\")\n}\n\n#' @export\nalignpatch.NULL <- function(x) NULL\n\npatch_no_method <- function(plot, method) {\n cli_abort(\"no {.fn {method}} method for {.obj_type_friendly {plot}}\")\n}\n\n#' @importFrom ggplot2 ggproto\n#' @importFrom grid unit.c\nPatch <- ggproto(\n \"Patch\", NULL,\n # following fields will be added by `alignpatch()`\n plot = NULL,\n # following fields will be added in `alignpatches$patch_gtable()`\n # borders = NULL, gt = NULL,\n\n #' @param guides `guides` argument from the parent alignpatches\n #' @return Which side of guide legends should be collected by the parent\n #' `alignpatches` object?\n #' @noRd\n set_guides = function(self, guides) {\n patch_no_method(self$plot, \"set_guides\")\n },\n patch_gtable = function(self, theme, guides, plot = self$plot) {\n patch_no_method(self$plot, \"patch_gtable\")\n },\n collect_guides = function(self, guides, gt = self$gt) {\n if (is.null(guides)) return(list()) # styler: off\n layout <- .subset2(gt, \"layout\")\n grobs <- .subset2(gt, \"grobs\")\n guides_ind <- grep(\"guide-box\", .subset2(layout, \"name\"))\n guides_loc <- vec_slice(layout, guides_ind)\n collected_guides <- vector(\"list\", length(guides))\n names(collected_guides) <- guides\n panel_loc <- find_panel(gt)\n remove_grobs <- NULL\n for (guide_pos in guides) {\n guide_ind <- switch(guide_pos,\n top = .subset2(guides_loc, \"b\") < .subset2(panel_loc, \"t\"),\n left = .subset2(guides_loc, \"r\") < .subset2(panel_loc, \"l\"),\n bottom = .subset2(guides_loc, \"t\") > .subset2(panel_loc, \"b\"),\n right = .subset2(guides_loc, \"l\") > .subset2(panel_loc, \"r\"),\n inside = .subset2(guides_loc, \"t\") >= .subset2(panel_loc, \"t\") &\n .subset2(guides_loc, \"b\") <= .subset2(panel_loc, \"b\") &\n .subset2(guides_loc, \"l\") >= .subset2(panel_loc, \"l\") &\n .subset2(guides_loc, \"r\") <= .subset2(panel_loc, \"r\")\n )\n if (!any(guide_ind)) next\n guide_loc <- vec_slice(guides_loc, guide_ind)\n guide_ind <- .subset(guides_ind, guide_ind)\n remove_grobs <- c(guide_ind, remove_grobs)\n collected_guides[[guide_pos]] <- .subset2(grobs, guide_ind)\n\n # remove the guide spaces from the original gtable\n # for inside guide, no need to remove the spaces\n if (guide_pos == \"inside\") next\n\n space_pos <- switch(guide_pos,\n top = ,\n left = 1L,\n bottom = ,\n right = -1L\n )\n if (guide_pos %in% c(\"right\", \"left\")) {\n gt$widths[c(guide_loc$l, guide_loc$l + space_pos)] <- unit(\n c(0L, 0L), \"mm\"\n )\n } else if (guide_pos %in% c(\"bottom\", \"top\")) {\n gt$heights[c(guide_loc$t, guide_loc$t + space_pos)] <- unit(\n c(0L, 0L), \"mm\"\n )\n }\n }\n if (length(remove_grobs)) {\n gt <- subset_gt(gt, -remove_grobs, trim = FALSE)\n }\n self$gt <- gt\n collected_guides\n },\n respect = function(self, gt = self$gt) isTRUE(.subset2(gt, \"respect\")),\n align_panel_sizes = function(self, panel_width, panel_height,\n gt = self$gt) {\n list(width = panel_width, height = panel_height, respect = FALSE)\n },\n get_sizes = function(self, free = NULL, gt = self$gt) {\n ans <- .subset2(gt, \"heights\")\n if (any(free == \"t\")) {\n top <- unit(rep_len(0, TOP_BORDER), \"mm\")\n } else {\n top <- ans[seq_len(TOP_BORDER)]\n }\n if (any(free == \"b\")) {\n bottom <- unit(rep_len(0, BOTTOM_BORDER), \"mm\")\n } else {\n bottom <- ans[seq(length(ans) - BOTTOM_BORDER + 1L, length(ans))]\n }\n ans <- .subset2(gt, \"widths\")\n if (any(free == \"l\")) {\n left <- unit(rep_len(0, LEFT_BORDER), \"mm\")\n } else {\n left <- ans[seq_len(LEFT_BORDER)]\n }\n if (any(free == \"r\")) {\n right <- unit(rep_len(0, RIGHT_BORDER), \"mm\")\n } else {\n right <- ans[seq(length(ans) - RIGHT_BORDER + 1L, length(ans))]\n }\n list(\n widths = unit.c(left, unit(0, \"mm\"), right),\n heights = unit.c(top, unit(0, \"mm\"), bottom)\n )\n },\n align_border = function(self, t = NULL, l = NULL, b = NULL, r = NULL,\n gt = self$gt) {\n if (!is.null(t)) gt$heights[seq_along(t)] <- t\n if (!is.null(l)) gt$widths[seq_along(l)] <- l\n if (!is.null(b)) {\n n_row <- nrow(gt)\n gt$heights[seq(n_row - length(b) + 1L, n_row)] <- b\n }\n if (!is.null(r)) {\n n_col <- ncol(gt)\n gt$widths[seq(n_col - length(r) + 1L, n_col)] <- r\n }\n gt\n },\n split_gt = function(self, gt = self$gt) {\n isbg <- .subset2(.subset2(gt, \"layout\"), \"name\") == \"background\"\n if (any(isbg)) {\n bg <- .subset(.subset2(gt, \"grobs\"), isbg) # a list of background\n plot <- subset_gt(gt, !isbg, trim = FALSE)\n } else {\n bg <- NULL\n plot <- gt\n }\n list(bg = bg, plot = plot)\n },\n add_plot = function(self, gt, plot, t, l, b, r, name, z = 2L) {\n gtable_add_grob(\n gt,\n grobs = plot,\n t = t, l = l, b = b, r = r,\n name = name, z = z\n )\n },\n add_background = function(self, gt, bg, t, l, b, r, name, z = 1L) {\n gtable_add_grob(\n gt,\n grobs = bg,\n t = t, l = l, b = b, r = r,\n name = name, z = z\n )\n },\n free_border = function(self, borders, gt = self$gt) {\n patch_no_method(self$plot, \"free_border\")\n },\n align_free_border = function(self, borders,\n t = NULL, l = NULL, b = NULL, r = NULL,\n gt = self$gt) {\n patch_no_method(self$plot, \"align_free_border\")\n },\n free_lab = function(self, labs, gt = self$gt) {\n patch_no_method(self$plot, \"free_lab\")\n }\n)\n"], ["/ggalign/R/fortify-data-frame-.R", "#' Build a data frame\n#'\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' This function converts various objects to a data frame.\n#'\n#' @param data An object to be converted to a data frame.\n#' @param ... Arguments passed to methods.\n#' @inheritParams fortify_matrix\n#' @return A data frame.\n#' @eval\n#' rd_collect_family(\"fortify_data_frame\",\n#' \"`fortify_data_frame` method collections\"\n#' )\n#' @export\nfortify_data_frame <- function(data, ..., data_arg = NULL, call = NULL) {\n UseMethod(\"fortify_data_frame\")\n}\n\n#' @inherit fortify_data_frame title description\n#' @param ... Additional arguments passed to [`fortify()`][ggplot2::fortify].\n#' @inheritParams fortify_data_frame\n#' @details\n#' By default, it calls [`fortify()`][ggplot2::fortify] to build the\n#' data frame.\n#' @family fortify_data_frame\n#' @export\nfortify_data_frame.default <- function(data, ..., data_arg = NULL,\n call = NULL) {\n ggplot2::fortify(model = data, ...)\n}\n\n#' @inherit fortify_data_frame.default title description\n#' @param data An object to be converted to a data frame.\n#' @inheritParams rlang::args_dots_empty\n#' @inheritParams fortify_data_frame\n#' @return A data frame with following columns:\n#'\n#' - `.names`: the names for the vector (only applicable if names exist).\n#' - `value`: the actual value of the vector.\n#'\n#' @family fortify_data_frame\n#' @export\nfortify_data_frame.character <- function(data, ..., data_arg = NULL,\n call = NULL) {\n call <- call %||% current_call()\n rlang::check_dots_empty(call = call)\n ans <- list(.names = vec_names(data), value = data)\n if (is.null(.subset2(ans, \".names\"))) ans$.names <- NULL\n new_data_frame(ans)\n}\n\n#' @rdname fortify_data_frame.character\n#' @export\nfortify_data_frame.numeric <- fortify_data_frame.character\n\n#' @rdname fortify_data_frame.character\n#' @export\nfortify_data_frame.logical <- fortify_data_frame.character\n\n#' @rdname fortify_data_frame.character\n#' @export\nfortify_data_frame.complex <- fortify_data_frame.character\n\n#' @export\nfortify_data_frame.waiver <- function(data, ..., data_arg = NULL,\n call = NULL) {\n call <- call %||% current_call()\n rlang::check_dots_empty(call = call)\n data\n}\n\n#' @export\nfortify_data_frame.NULL <- fortify_data_frame.waiver\n\n#' @inherit fortify_data_frame.default title description\n#' @param data An object to be converted to a data frame.\n#' @inheritParams fortify_data_frame\n#' @return A data frame with at least following columns:\n#'\n#' - `seqnames`: The sequence (e.g., chromosome) names.\n#' - `start`: The start positions of the ranges.\n#' - `end`: The end positions of the ranges.\n#' - `width`: The width of each range.\n#'\n#' @family fortify_data_frame\n#' @export\nfortify_data_frame.GRanges <- function(data, ..., data_arg = NULL,\n call = NULL) {\n as.data.frame(data, ...)\n}\n\n#' @inherit fortify_data_frame.default title description\n#' @param data A matrix-like object.\n#' @param lvls A logical value indicating whether to restore factor levels using\n#' those stored in [`ggalign_lvls()`], or a character vector specifying custom\n#' levels for the `value` column. If levels are provided or restored, the\n#' `value` column will be returned as a factor.\n#' @inheritParams rlang::args_dots_empty\n#' @inheritParams fortify_data_frame\n#' @return\n#' Matrix will be transformed into a long-form data frame, where each row\n#' represents a unique combination of matrix indices and their corresponding\n#' values. The resulting data frame will contain the following columns:\n#'\n#' - `.row_names` and `.row_index`: the row names (only applicable when names\n#' exist) and an integer representing the row index of the original matrix.\n#'\n#' - `.column_names` and `.column_index`: the column names (only applicable\n#' when names exist) and column index of the original matrix.\n#'\n#' - `value`: the matrix value, returned as a factor if levels are specified or\n#' restored.\n#'\n#' @family fortify_data_frame\n#' @export\nfortify_data_frame.matrix <- function(data, lvls = NULL, ...,\n data_arg = NULL, call = NULL) {\n call <- call %||% current_call()\n rlang::check_dots_empty(call = call)\n row_nms <- vec_names(data)\n col_nms <- colnames(data)\n if (isFALSE(lvls)) {\n lvls <- NULL\n } else if (isTRUE(lvls)) {\n lvls <- ggalign_lvls_get(lvls)\n } else if (!is.null(lvls) && !is.character(lvls)) {\n cli_abort(\n \"{.arg lvls} must be a single boolean value or a character\",\n call = call\n )\n }\n data <- new_data_frame(list(\n .row_index = vec_rep(seq_len(nrow(data)), ncol(data)),\n .column_index = vec_rep_each(seq_len(ncol(data)), nrow(data)),\n value = c(data)\n ))\n if (!is.null(row_nms)) data$.row_names <- row_nms[data$.row_index]\n if (!is.null(col_nms)) data$.column_names <- col_nms[data$.column_index]\n if (!is.null(lvls)) data$value <- factor(data$value, levels = lvls)\n data\n}\n\n#' @export\n#' @rdname fortify_data_frame.matrix\nfortify_data_frame.DelayedMatrix <- function(data, ...) {\n fortify_data_frame(as.matrix(data), ...)\n}\n\n#' @export\n#' @rdname fortify_data_frame.matrix\nfortify_data_frame.Matrix <- function(data, ...) {\n fortify_data_frame(as.matrix(data), ...)\n}\n"], ["/ggalign/R/layout-chain-stack-build.R", "#' @export\nggalign_build.StackLayout <- function(x) {\n x <- default_layout(x)\n (stack_build(x) %||% align_plots(theme = x@theme)) +\n layout_title(\n title = .subset2(x@titles, \"title\"),\n subtitle = .subset2(x@titles, \"subtitle\"),\n caption = .subset2(x@titles, \"caption\")\n )\n}\n\n#' @param schemes,theme Parameters from parent layout\n#' @param extra_design layout parameters of the axis vertically with the stack.\n#' @noRd\nstack_build <- function(stack, schemes = NULL, theme = NULL,\n extra_design = NULL) {\n if (is_empty(stack@plot_list)) {\n return(NULL)\n }\n direction <- stack@direction\n position <- .subset2(stack@heatmap, \"position\")\n schemes <- inherit_parent_layout_schemes(stack, schemes)\n\n if (is_horizontal(direction)) {\n spacing <- \"y\"\n # for horizontal stack, we by default remove top and bottom spaces\n # if (!is.null(position)) {\n # schemes$scheme_align[\"free_spaces\"] <- list(\n # .subset2(schemes$scheme_align, \"free_spaces\") %|w|% \"tb\"\n # )\n # }\n } else {\n spacing <- \"x\"\n # for vertical stack, we by default remove left and right spaces\n # if (!is.null(position)) {\n # schemes$scheme_align[\"free_spaces\"] <- list(\n # .subset2(schemes$scheme_align, \"free_spaces\") %|w|% \"lr\"\n # )\n # }\n }\n theme <- inherit_parent_layout_theme(stack, theme, spacing = spacing)\n composer <- resolve_stack_layout(stack, schemes, theme, extra_design)\n if (is_empty(plots <- .subset2(composer, \"plots\"))) {\n return(NULL)\n }\n\n # arrange plots\n if (is.null(position)) { # for stack layout\n # sizes should be of length 3\n sizes <- stack@sizes\n # recycle the sizes when necessary\n if (length(sizes) == 1L) sizes <- rep(sizes, length.out = 3L)\n sizes <- sizes[\n c(\n .subset2(composer, \"left_or_top\"),\n TRUE,\n .subset2(composer, \"right_or_bottom\")\n )\n ]\n } else { # for the heatmap annotation\n sizes <- NA\n }\n plot <- align_plots(\n !!!plots,\n design = area(\n .subset2(composer, \"t\"),\n .subset2(composer, \"l\"),\n .subset2(composer, \"b\"),\n .subset2(composer, \"r\")\n ),\n widths = switch_direction(\n direction,\n do.call(unit.c, .subset2(composer, \"sizes\")),\n sizes\n ),\n heights = switch_direction(\n direction,\n sizes,\n do.call(unit.c, .subset2(composer, \"sizes\"))\n ),\n guides = .subset2(.subset2(schemes, \"scheme_align\"), \"guides\"),\n theme = stack@theme\n )\n\n # for annotation, we should always make it next to the main body\n if (is.null(position)) {\n return(plot)\n }\n plot <- free_vp(\n plot,\n x = switch(position,\n left = 1L,\n right = 0L,\n 0.5\n ),\n y = switch(position,\n top = 0L,\n bottom = 1L,\n 0.5\n ),\n just = switch(position,\n top = \"bottom\",\n left = \"right\",\n bottom = \"top\",\n right = \"left\"\n )\n )\n\n # whether we should override the `guides` collection for the whole\n # annotation stack\n free_guides <- .subset2(stack@heatmap, \"free_guides\")\n if (!is.waive(free_guides)) plot <- free_guide(plot, free_guides)\n # we also apply the `free_spaces` for the whole annotation stack\n free_spaces <- .subset2(\n .subset2(schemes, \"scheme_align\"), \"free_spaces\"\n ) %|w|% NULL\n if (!is.null(free_spaces)) {\n plot <- free_space(free_border(plot, free_spaces), free_spaces)\n }\n plot\n}\n\n#' @param schemes,theme Parameters for current stack, which have inherited\n#' parameters from the parent.\n#' @noRd\nresolve_stack_layout <- function(stack, schemes, theme, extra_design) {\n UseMethod(\"resolve_stack_layout\")\n}\n\n#' @export\nresolve_stack_layout.StackLayout <- function(stack, schemes, theme,\n extra_design) {\n plot_list <- stack@plot_list\n direction <- stack@direction\n position <- .subset2(stack@heatmap, \"position\")\n\n # we remove the plot without actual plot area\n keep <- vapply(plot_list, function(plot) {\n # we remove objects without plot area\n # Now, only `CraftBox` will contain `NULL`\n !is_craftbox(plot) || !is.null(plot@plot)\n }, logical(1L), USE.NAMES = FALSE)\n plot_list <- .subset(plot_list, keep)\n if (is_empty(plot_list)) return(NULL) # styler: off\n\n # we reorder the plots based on the `order` slot\n plot_order <- vapply(plot_list, function(plot) {\n if (is_layout(plot)) {\n .subset2(plot@plot_active, \"order\")\n } else {\n .subset2(plot@active, \"order\")\n }\n }, integer(1L), USE.NAMES = FALSE)\n plot_list <- .subset(plot_list, make_order(plot_order))\n\n # build the stack\n composer <- stack_composer(direction)\n\n # for `free_spaces`, if we have applied it in the whole stack layout\n # we shouln't use it for a single plot. Otherwise, the guide legends\n # collected by the layout will overlap with the axis of the plot in the\n # layout.\n #\n # this occurs in the annotation stack (`position` is not `NULL`).\n #\n # here is the example:\n # p1 <- ggplot(mtcars) +\n # geom_point(aes(mpg, disp))\n # p2 <- ggplot(mtcars) +\n # geom_boxplot(aes(gear, disp, group = gear, fill = gear))\n # p3 <- ggplot(mtcars) +\n # geom_bar(aes(gear)) +\n # facet_wrap(~cyl)\n # align_plots(\n # free_space(free_border(\n # align_plots(\n # # we shouldn't add free_space for the internal plot\n # free_space(\n # free_border(\n # p1 + scale_y_continuous(\n # expand = expansion(),\n # labels = ~ paste(\"very very long labels\", .x)\n # ),\n # \"l\"\n # ),\n # \"l\"\n # ),\n # p2 + theme(legend.position = \"left\"),\n # guides = \"l\"\n # ),\n # \"l\"\n # ), \"l\"),\n # p3 + theme(plot.margin = margin(l = 5, unit = \"cm\")),\n # ncol = 1\n # )\n stack_spaces <- .subset2(.subset2(schemes, \"scheme_align\"), \"free_spaces\")\n if (is_string(stack_spaces) && !is.null(position)) {\n released_spaces <- stack_spaces\n } else {\n released_spaces <- NULL\n }\n\n design <- setup_design(stack@design)\n stack_composer_add(\n plot_list,\n stack = stack,\n composer,\n schemes = schemes,\n theme = theme,\n design = design,\n extra_design = extra_design,\n direction = direction,\n position = position,\n released_spaces = released_spaces,\n previous_design = NULL\n )\n}\n\nmake_order <- function(order) {\n l <- length(order)\n index <- seq_len(l)\n\n # for order not set by user, we use heuristic algorithm to define the order\n need_action <- is.na(order)\n if (all(need_action)) { # shorthand for the usual way, we don't set any\n return(index)\n } else if (all(!need_action)) { # we won't need do something special\n return(order(order))\n }\n\n # 1. for outliers, we always put them in the two tail\n # 2. for order has been set and is not the outliers,\n # we always follow the order\n # 3. non-outliers were always regarded as the integer index\n used <- as.integer(order[!need_action & order >= 1L & order <= l])\n\n # we flatten user index to continuous integer sequence\n sequence <- vec_unrep(used) # key is the sequence start\n start <- .subset2(sequence, \"key\")\n end <- pmin(\n start + .subset2(sequence, \"times\") - 1L,\n vec_c(start[-1L] - 1L, l) # the next start - 1L\n )\n used <- .mapply(function(s, e) s:e, list(s = start, e = end), NULL)\n\n # following index can be used\n unused <- vec_set_difference(index, unlist(used, FALSE, FALSE))\n\n # we assign the candidate index to the order user not set.\n order[need_action] <- unused[seq_len(sum(need_action))]\n\n # make_order(c(NA, 1, NA)): c(2, 1, 3)\n # make_order(c(NA, 1, 3)): c(2, 1, 3)\n # make_order(c(NA, 1, 3, 1)): c(2, 4, 3, 1)\n order(order)\n}\n"], ["/ggalign/R/alignpatch-build.R", "#' @importFrom grid grid.draw\n#' @importFrom rlang try_fetch cnd_signal\n#' @export\nprint.alignpatches <- function(x, newpage = is.null(vp), vp = NULL, ...) {\n ggplot2::set_last_plot(x)\n if (newpage) {\n grid::grid.newpage()\n if (is.character(vp)) {\n cli_abort(c(\n \"{.arg vp} cannot be a character string when {.arg newpage} is TRUE.\",\n i = \"Please provide a viewport object or set {.arg newpage} to FALSE.\"\n ))\n }\n }\n if (!is.null(vp)) {\n if (is.character(vp)) {\n cur <- grid::current.viewport()$name\n grid::seekViewport(vp)\n if (!identical(cur, \"ROOT\")) on.exit(grid::seekViewport(cur))\n } else {\n grid::pushViewport(vp)\n on.exit(grid::upViewport())\n }\n }\n\n # render the plot\n try_fetch(\n grid.draw(x, ...),\n error = function(e) {\n if (inherits(e, \"simpleError\") &&\n deparse(conditionCall(e)[[1L]]) == \"grid.Call\") {\n error_name <- obj_type_friendly(x)\n if (Sys.getenv(\"RSTUDIO\") == \"1\") {\n cli_abort(c(paste(\n \"The RStudio {.field Plots} window may be\",\n \"too small to show\", error_name\n ), i = \"Please make the window larger.\"), parent = e)\n } else {\n cli_abort(c(\n \"The viewport may be too small to show {error_name}.\",\n i = \"Please make the window larger.\"\n ), parent = e)\n }\n }\n cnd_signal(e)\n }\n )\n invisible(x)\n}\n\n#' @importFrom grid grid.draw\n#' @exportS3Method\ngrid.draw.alignpatches <- function(x, recording = TRUE) {\n grid.draw(ggalignGrob(x), recording = recording)\n}\n\n#' @export\nggalign_build.alignpatches <- function(x) x\n\n#' @importFrom ggplot2 find_panel element_render theme theme_get\n#' @importFrom gtable gtable_add_grob gtable_add_rows gtable_add_cols\n#' @importFrom rlang arg_match0\n#' @importFrom S7 prop\n#' @export\nggalign_gtable.alignpatches <- function(x) {\n titles <- prop(x, \"titles\")\n\n # ensure theme has no missing value\n theme <- prop(x, \"theme\") %||% theme_get()\n\n # `TO-DO`: use `complete_theme()` from ggplot2 release\n theme <- complete_theme(theme)\n attr(x, \"theme\") <- theme # bypass the setter function\n table <- alignpatch(x)$patch_gtable(top_level = TRUE)\n\n fix_respect <- is.matrix(.subset2(table, \"respect\"))\n\n # Add title, subtitle, and caption -------------------\n # https://github.com/tidyverse/ggplot2/blob/2e08bba0910c11a46b6de9e375fade78b75d10dc/R/plot-build.R#L219C3-L219C9\n title <- element_render(\n theme = theme, \"plot.title\", .subset2(titles, \"title\"),\n margin_y = TRUE, margin_x = TRUE\n )\n title_height <- grobHeight(title)\n\n # Subtitle\n subtitle <- element_render(\n theme, \"plot.subtitle\", .subset2(titles, \"subtitle\"),\n margin_y = TRUE, margin_x = TRUE\n )\n subtitle_height <- grobHeight(subtitle)\n\n # caption\n caption <- element_render(\n theme, \"plot.caption\", .subset2(titles, \"caption\"),\n margin_y = TRUE, margin_x = TRUE\n )\n caption_height <- grobHeight(caption)\n\n # positioning of title and subtitle is governed by plot.title.position\n # positioning of caption is governed by plot.caption.position\n # \"panel\" means align to the panel(s)\n # \"plot\" means align to the entire plot (except margins and tag)\n panel_pos <- find_panel(table)\n title_pos <- arg_match0(\n theme$plot.title.position %||% \"panel\",\n c(\"panel\", \"plot\"),\n arg_nm = \"plot.title.position\",\n error_call = quote(theme())\n )\n\n caption_pos <- arg_match0(\n theme$plot.caption.position %||% \"panel\",\n values = c(\"panel\", \"plot\"),\n arg_nm = \"plot.caption.position\",\n error_call = quote(theme())\n )\n if (title_pos == \"panel\") {\n title_l <- panel_pos$l\n title_r <- panel_pos$r\n } else {\n title_l <- 1L\n title_r <- ncol(table)\n }\n if (caption_pos == \"panel\") {\n caption_l <- panel_pos$l\n caption_r <- panel_pos$r\n } else {\n caption_l <- 1L\n caption_r <- ncol(table)\n }\n\n table <- gtable_add_rows(table, subtitle_height, pos = 0)\n table <- gtable_add_grob(table, subtitle,\n name = \"subtitle\",\n t = 1, b = 1, l = title_l, r = title_r, clip = \"off\"\n )\n\n table <- gtable_add_rows(table, title_height, pos = 0)\n table <- gtable_add_grob(table, title,\n name = \"title\",\n t = 1, b = 1, l = title_l, r = title_r, clip = \"off\"\n )\n\n table <- gtable_add_rows(table, caption_height, pos = -1)\n table <- gtable_add_grob(table, caption,\n name = \"caption\",\n t = -1, b = -1, l = caption_l, r = caption_r, clip = \"off\"\n )\n if (fix_respect) {\n table$respect <- rbind(0L, 0L, table$respect, 0L)\n }\n\n # add margins --------------------------------------\n plot_margin <- calc_element(\"plot.margin\", theme)\n\n table <- gtable_add_rows(table, plot_margin[1L], 0L)\n table <- gtable_add_rows(table, plot_margin[3L])\n if (fix_respect) table$respect <- rbind(0L, table$respect, 0L)\n table <- gtable_add_cols(table, plot_margin[2L], 0L)\n table <- gtable_add_cols(table, plot_margin[4L])\n if (fix_respect) table$respect <- cbind(0L, table$respect, 0L)\n\n # add background -----------------------------------\n if (inherits(theme$plot.background, \"element\")) {\n table <- gtable_add_grob(table,\n element_render(theme, \"plot.background\"),\n t = 1L, l = 1L, b = -1L, r = -1L, name = \"background\", z = -Inf\n )\n table$layout <- table$layout[\n c(nrow(table$layout), 1:(nrow(table$layout) - 1L)),\n ]\n table$grobs <- table$grobs[\n c(nrow(table$layout), 1:(nrow(table$layout) - 1L))\n ]\n }\n table\n}\n"], ["/ggalign/R/grid-grob-channel.R", "#' Create a Grob That Spans Multiple Viewports\n#'\n#' This function initializes a communication channel to share location signals\n#' across different viewports. It returns a `channelSenderGrob` object, which\n#' can transmit multiple signals using its `$signal` method (see the \"Signal\"\n#' section below for details). When drawn, all collected signals are passed to\n#' the `make_content` function to generate the final [`grob`][grid::grob].\n#'\n#' @param make_content A function that accepts the list of signal locations and\n#' returns a [`grob`][grid::grob].\n#' @param ... Additional arguments passed to `make_content`.\n#' @inheritParams grid::grob\n#'\n#' @section Signal:\n#' A `channelSenderGrob` can emit multiple location signals using the `$signal`\n#' method. This method accepts the following arguments:\n#'\n#' - `x`: X-coordinate.\n#' - `y`: Y-coordinate.\n#' - `default.units`: The default units for `x` and `y`.\n#' - `tag`: A character string used to identify the location.\n#' - `name`: A name for the returned grob.\n#' - `vp`: A [`viewport`][grid::viewport] for the returned grob.\n#'\n#' The `$signal` method returns a `channelSignalGrob`.\n#'\n#' @return A `channelSenderGrob` object.\n#' @examples\n#' # we create a new channel, we will emit two singals\n#' # here: we just add a line between the two signals\n#' channel <- channelGrob(function(locations) {\n#' # you can also use `tag` to identify the locations\n#' loc1 <- .subset2(locations, 1L)\n#' loc2 <- .subset2(locations, 2L)\n#' grid::segmentsGrob(loc1$x, loc1$y, loc2$x, loc2$y)\n#' })\n#'\n#' gt <- gtable::gtable(unit(1:2, c(\"cm\")), unit(5, \"cm\"))\n#' gt <- gtable::gtable_add_grob(\n#' gt,\n#' list(\n#' grid::rectGrob(gp = gpar(color = \"black\", fill = NA)),\n#' channel$signal(0.5, 0.5, \"npc\")\n#' ),\n#' t = 1, l = 1, name = c(\"rect1\", \"signal1\")\n#' )\n#' gt <- gtable::gtable_add_grob(\n#' gt,\n#' list(\n#' grid::rectGrob(gp = gpar(color = \"red\", fill = NA)),\n#' channel$signal(0.5, 0.5, \"npc\")\n#' ),\n#' t = 1, l = 2, name = c(\"rect2\", \"signal2\")\n#' )\n#' grid::grid.newpage()\n#' grid::grid.draw(gt)\n#' @importFrom grid unit is.unit grob\n#' @importFrom rlang list2\n#' @export\nchannelGrob <- function(make_content, ..., name = NULL, vp = NULL) {\n make_content <- allow_lambda(make_content)\n if (!is.function(make_content)) {\n cli_abort(\"{.arg make_content} must be a function\")\n }\n # Used to communicate between different signals\n channel <- new.env(parent = emptyenv())\n channel$make_content <- make_content\n channel$dots <- list2(...)\n channel$n <- 0L # total number of signals\n grob(\n channel = channel,\n name = name,\n vp = vp,\n\n # method used to release signal and retutn a new grob\n signal = function(self, x, y, default.units = \"native\",\n tag = NULL, name = NULL, vp = NULL) {\n if (!is.unit(x)) x <- unit(x, default.units)\n if (!is.unit(y)) y <- unit(y, default.units)\n if (length(x) != length(y)) {\n cli_abort(\"{.arg x} and {.arg y} must have the same length\")\n }\n assert_string(tag, allow_empty = FALSE, allow_null = TRUE)\n signal <- list(list(x = x, y = y))\n if (!is.null(tag)) names(signal) <- tag\n channel <- .subset2(self, \"channel\")\n channel$signals <- c(channel$signals, signal)\n i <- channel$n <- channel$n + 1L\n grob(\n channel = channel,\n i = i,\n name = name,\n vp = vp,\n cl = c(\"channelSignalGrob\", \"channelGrob\")\n )\n },\n # Grob used to send signals\n cl = c(\"channelSenderGrob\", \"channelGrob\")\n )\n}\n\n#' @export\n`$.channelGrob` <- function(self, name) {\n field <- .subset2(self, name)\n if (!is.function(field)) {\n return(field)\n }\n args <- formals(field)\n # is.null is a fast path for a common case; the %in% check is slower but\n # also catches the case where there's a `self = NULL` argument.\n has_self <- !is.null(args[[\"self\"]]) || \"self\" %in% names(args)\n\n # We assign the method with its correct name and construct a call to it to\n # make errors reported as coming from the method name rather than `field()`\n assign(name, field, envir = environment())\n args <- list(quote(...))\n if (has_self) {\n args$self <- quote(self)\n }\n rlang::new_function(alist(... = ), rlang::call2(name, !!!args))\n}\n\n#' @export\n`[[.channelGrob` <- `$.channelGrob`\n\n# https://www.stat.auckland.ac.nz/~paul/Reports/CustomGrobs/custom-grob.html\n# preDraw:\n# - makeContext\n# - pushvpgp\n# - preDrawDetails: by default, do noting\n# makeContent:\n# drawDetails:\n# postDraw:\n# - postDrawDetails: by default, do noting\n# - popgrobvp\n#' @importFrom grid makeContent drawDetails viewport is.grob gTree grob\n#' @export\nmakeContent.channelGrob <- function(x) {\n channel <- .subset2(x, \"channel\")\n # If no signals, do nothing\n if (channel$n == 0L) return(x) # styler: off\n\n if (inherits(x, \"channelSenderGrob\")) {\n # we use the viewport from the signals sender\n channel$vp <- grid::current.viewport()\n } else if (inherits(x, \"channelSignalGrob\")) {\n if (is.null(channel$locations)) {\n channel$locations <- vector(\"list\", channel$n)\n names(channel$locations) <- names(channel$signals)\n }\n\n # convert the viewport coordinates to the device coordinates\n i <- .subset2(x, \"i\")\n signal <- .subset2(channel$signals, i)\n channel$locations[[i]] <- grid::deviceLoc(signal$x, signal$y)\n if (all(!vapply(channel$locations, is.null, logical(1L), # styler: off\n USE.NAMES = FALSE))) { # styler: off\n # When all locations have been prepared\n # we output the grob with all device locations\n x <- grob(\n channel = channel,\n vp = .subset2(x, \"vp\"), # Don't change the viewport\n cl = c(\"channelReceiverGrob\", \"channelGrob\")\n )\n }\n }\n x\n}\n\n#' @export\ndrawDetails.channelGrob <- function(x, recording) {\n}\n\n#' @importFrom grid grid.draw viewport gTree is.grob\n#' @export\ndrawDetails.channelReceiverGrob <- function(x, recording) {\n # we always reset the locations after drawing\n old <- grid::current.viewport()$name\n on.exit(grid::seekViewport(old), add = TRUE)\n channel <- .subset2(x, \"channel\")\n locations <- channel$locations\n on.exit(channel$locations <- NULL, add = TRUE)\n if (!is.null(vp <- channel$vp)) {\n grid::seekViewport(vp$name)\n # convert the device cooridnates into the drawing viewport coordinates\n trans <- solve(grid::current.transform())\n locations <- lapply(locations, grid_solve_loc, trans = trans)\n } else { # If no viewport, we use the `ROOT` viewport\n grid::upViewport(0)\n grid::pushViewport(viewport())\n }\n grob <- rlang::inject(channel$make_content(locations, !!!channel$dots))\n if (is.gList(grob)) grob <- gTree(children = grob)\n if (is.grob(grob)) grid.draw(grob, recording = recording)\n}\n"], ["/ggalign/R/grid-utils.R", "#' @importFrom grid gpar\n#' @export\ngrid::gpar\n\n#' @importFrom grid unit\n#' @export\ngrid::unit\n\nis.gList <- function(x) inherits(x, \"gList\")\n\nis.gTree <- function(x) inherits(x, \"gTree\")\n\n#' @importFrom grid unitType absolute.size\nis_absolute_unit <- function(x) unitType(absolute.size(x)) != \"null\"\n\n#' @importFrom grid unitType\nis_null_unit <- function(x) unitType(x) == \"null\"\n\nis_null_grob <- function(x) inherits(x, c(\"zeroGrob\", \"null\"))\n\n#' @importFrom grid is.grob nullGrob\nensure_grob <- function(x, default = nullGrob()) {\n if (is.gList(x)) x <- gTree(children = x)\n if (is.grob(x)) x else default\n}\n\n# `current.transform()` transforms from *inches* within the current viewport to\n# *inches* on the overall device.\ngrid_solve_loc <- function(loc, trans, valueOnly = FALSE) {\n x <- grid::convertX(loc$x, \"inches\", valueOnly = TRUE)\n y <- grid::convertY(loc$y, \"inches\", valueOnly = TRUE)\n out <- matrix(c(x, y, rep_len(1, length(x))), ncol = 3L) %*%\n trans\n out <- list(x = out[, 1L, drop = TRUE], y = out[, 2L, drop = TRUE])\n if (!valueOnly) out <- lapply(out, unit, \"inches\")\n out\n}\n\nloc_device2vp <- function(x, y, valueOnly = FALSE) {\n assert_s3_class(x, \"unit\")\n assert_s3_class(y, \"unit\")\n if (length(x) != length(y)) {\n cli_abort(\"{.arg x} and {.arg y} must have the same length\")\n }\n assert_bool(valueOnly)\n grid_solve_loc(\n list(x = x, y = y),\n solve(grid::current.transform()),\n valueOnly = valueOnly\n )\n}\n\nloc_vp2device <- function(x, y, valueOnly = FALSE) {\n assert_s3_class(x, \"unit\")\n assert_s3_class(y, \"unit\")\n if (length(x) != length(y)) {\n cli_abort(\"{.arg x} and {.arg y} must have the same length\")\n }\n assert_bool(valueOnly)\n grid::deviceLoc(x, y, valueOnly = valueOnly)\n}\n\n# # allow the missing value in the unit for `str` method\n# ggalign_unit <- function(x, ...) UseMethod(\"ggalign_unit\")\n# #' @export\n# ggalign_unit.default <- function(x, ...) ggalign_unit(as.numeric(x), ...)\n# #' @export\n# ggalign_unit.numeric <- function(x, units = \"null\", data = NULL, ...) {\n# add_class(unit(x, units, data = data), \"ggalign_unit\")\n# }\n# #' @export\n# ggalign_unit.unit <- function(x, ...) add_class(x, \"ggalign_unit\")\n# is_ggalign_unit <- function(x) inherits(x, \"ggalign_unit\")\n\n# # allow the missing value in the unit for `str` method\n#' @importFrom utils str\n#' @export\nstr.unit <- function(object, ...) obj_str(object, ...)\n\n#' @export\nvec_ptype_abbr.unit <- function(x, ...) fclass(x)\n\n#' @importFrom utils str\n#' @export\nobj_str_footer.unit <- function(x, ..., indent.str = \" \", nest.lev = 0,\n give.attr = TRUE) {\n if (!isTRUE(give.attr)) {\n return(invisible(x))\n }\n attr <- attributes(x)\n attr[[\"class\"]] <- NULL\n attr[[\"names\"]] <- NULL\n if (length(attr) == 0) {\n return(invisible(x))\n }\n indent.str <- paste0(\" \", indent.str)\n for (nm in names(attr)) {\n cat(indent.str, paste0(\"- attr(*, \\\"\", nm, \"\\\"):\"), sep = \"\")\n str(\n attr[[nm]],\n no.list = TRUE, ...,\n nest.lev = nest.lev + 1L,\n indent.str = indent.str\n )\n }\n invisible(x)\n}\n\n#' @importFrom gtable gtable_trim\nsubset_gt <- function(gt, index, trim = TRUE) {\n gt$layout <- vec_slice(.subset2(gt, \"layout\"), index)\n gt$grobs <- .subset(.subset2(gt, \"grobs\"), index)\n if (trim) gtable_trim(gt) else gt\n}\n\ngtable_trim_widths <- function(gt) {\n layout <- .subset2(gt, \"layout\")\n w <- range(.subset2(layout, \"l\"), .subset2(layout, \"r\"))\n gt$widths <- .subset2(gt, \"widths\")[seq.int(w[1L], w[2L])]\n if (is.matrix(respect <- .subset2(gt, \"respect\"))) {\n respect <- respect[, seq.int(w[1L], w[2L]), drop = FALSE]\n if (all(respect == 0L)) respect <- FALSE\n gt$respect <- respect\n }\n layout$l <- .subset2(layout, \"l\") - w[1L] + 1L\n layout$r <- .subset2(layout, \"r\") - w[1L] + 1L\n gt$layout <- layout\n gt\n}\n\ngtable_trim_heights <- function(gt) {\n layout <- .subset2(gt, \"layout\")\n h <- range(.subset2(layout, \"t\"), .subset2(layout, \"b\"))\n gt$heights <- .subset2(gt, \"heights\")[seq.int(h[1L], h[2L])]\n if (is.matrix(respect <- .subset2(gt, \"respect\"))) {\n respect <- respect[seq.int(h[1L], h[2L]), , drop = FALSE]\n if (all(respect == 0L)) respect <- FALSE\n gt$respect <- respect\n }\n layout$t <- .subset2(layout, \"t\") - h[1L] + 1L\n layout$b <- .subset2(layout, \"b\") - h[1L] + 1L\n gt$layout <- layout\n gt\n}\n\nliberate_area <- function(gt, top, left, bottom, right,\n clip = \"inherit\", name = NULL, vp = NULL) {\n if (any(remove <- grob_in_area(gt, top, right, bottom, left))) {\n liberated <- gt[top:bottom, left:right]\n if (is.function(vp <- allow_lambda(vp))) {\n liberated$vp <- vp(liberated)\n } else if (inherits(vp, \"viewport\")) {\n liberated$vp <- vp\n }\n liberated$respect <- FALSE\n name <- name %||%\n paste(\n .subset2(.subset2(liberated, \"layout\"), \"name\"),\n collapse = \"; \"\n )\n gt <- subset_gt(gt, !remove, trim = FALSE)\n gt <- gtable_add_grob(\n gt,\n list(liberated),\n top,\n left,\n bottom,\n right,\n z = max(.subset2(.subset2(liberated, \"layout\"), \"z\")),\n clip = clip,\n name = name\n )\n }\n gt\n}\n\ngrob_in_area <- function(gt, top, right, bottom, left) {\n .subset2(.subset2(gt, \"layout\"), \"l\") >= left &\n .subset2(.subset2(gt, \"layout\"), \"t\") >= top &\n .subset2(.subset2(gt, \"layout\"), \"r\") <= right &\n .subset2(.subset2(gt, \"layout\"), \"b\") <= bottom\n}\n\ncompute_null_width <- function(x, unitTo = \"mm\", valueOnly = FALSE) {\n compute_null_unit(x, \"width\", unitTo = unitTo, valueOnly = valueOnly)\n}\n\ncompute_null_height <- function(x, unitTo = \"mm\", valueOnly = FALSE) {\n compute_null_unit(x, \"height\", unitTo = unitTo, valueOnly = valueOnly)\n}\n\n#' @importFrom grid unit convertHeight convertWidth\ncompute_null_unit <- function(x, type = c(\"width\", \"height\"), unitTo = \"mm\",\n valueOnly = FALSE) {\n null <- is_null_unit(x) # null unit\n if (type == \"width\") {\n ans <- convertWidth(x, unitTo, valueOnly = TRUE)\n total <- convertWidth(unit(1, \"npc\"), unitTo = unitTo, valueOnly = TRUE)\n } else {\n ans <- convertHeight(x, unitTo, valueOnly = TRUE)\n total <- convertHeight(\n unit(1, \"npc\"),\n unitTo = unitTo,\n valueOnly = TRUE\n )\n }\n if (any(null)) {\n null_size <- total - sum(ans[!null])\n # other units in the same row/ column also have unit null\n coef <- as.numeric(x[null])\n ans[null] <- (null_size / sum(coef)) * coef\n }\n if (!valueOnly) ans <- unit(ans, unitTo)\n ans\n}\n"], ["/ggalign/R/ggcross.R", "#' Connect two layout crosswise\n#'\n#' @description\n#' `ggcross` resets the layout ordering index of a [`stack_cross()`]. This\n#' allows you to add other `align_*` objects to define a new layout ordering\n#' index. Any objects added after `ggcross` will use this updated layout\n#' ordering index. This feature is particularly useful for creating `tanglegram`\n#' visualizations. `ggcross()` is an alias of `ggcross()`.\n#'\n#' @inheritParams ggalign\n#' @section ggplot2 specification:\n#' `ggcross()` initializes a ggplot `data` and `mapping`.\n#'\n#' `ggcross()` always applies a default mapping for the axis of the data index\n#' in the layout. This mapping is `aes(y = .data$.y)` for horizontal stack\n#' layout (including left and right annotation) and `aes(x = .data$.x)` for\n#' vertical stack layout (including top and bottom annotation).\n#'\n#' The data in the underlying `ggplot` object will contain following columns:\n#'\n#' - `.panel`: The panel for the aligned axis. Refers to the `x-axis` for\n#' vertical `stack_layout()` (including top and bottom annotations), and the\n#' `y-axis` for horizontal `stack_layout()` (including left and right\n#' annotations).\n#'\n#' - `.names` ([`vec_names()`][vctrs::vec_names]) and `.index`\n#' ([`vec_size()`][vctrs::vec_size()]/[`NROW()`]): Character names (if\n#' available) and the integer index of the original data.\n#'\n#' - `.hand`: a factor indicates the index groups.\n#'\n#' - `.x`/`.y` and `.discrete_x`/`.discrete_y`: Integer indices for `x`/`y`\n#' coordinates, and a factor of the data labels (only applicable when names\n#' exist).\n#'\n#' It is recommended to use `.x`/`.y`, or `.discrete_x`/`.discrete_y` as the\n#' `x`/`y` mapping.\n#'\n#' @importFrom ggplot2 ggplot aes\n#' @export\nggcross <- function(mapping = aes(), size = NULL,\n no_axes = NULL, active = NULL) {\n active <- update_active(active, new_active(use = TRUE))\n no_axes <- no_axes %||%\n getOption(sprintf(\"%s.align_no_axes\", pkg_nm()), default = TRUE)\n cross(\n CrossGg,\n plot = ggplot(mapping = mapping),\n schemes = default_schemes(th = theme_no_strip()),\n size = size, no_axes = no_axes, active = active\n )\n}\n\n#' @importFrom ggplot2 ggproto\nCrossGg <- ggproto(\"CrossGg\", \n CraftCross,\n interact_layout = function(self, layout) {\n if (!is_cross_layout(layout)) {\n cli_abort(c(\n sprintf(\n \"Cannot add %s to %s\",\n object_name(self), self$layout_name\n ),\n i = sprintf(\n \"%s can only be used in {.fn stack_cross}\",\n object_name(self)\n )\n ))\n }\n\n # udpate cross_points\n layout@cross_points <- c(layout@cross_points, length(layout@plot_list))\n\n # update old design list\n layout@odesign <- c(layout@odesign, list(layout@design))\n\n # we keep the names from the layout data for usage\n self$labels <- vec_names(layout@data)\n layout\n },\n setup_design = function(self, design) {\n design[\"index\"] <- list(NULL) # always reset the index\n design\n },\n setup_plot = function(self, plot) {\n ggadd_default(plot, mapping = switch_direction(\n self$direction, aes(y = .data$.y), aes(x = .data$.x)\n ))\n },\n #' @importFrom stats reorder\n build_plot = function(self, plot, design, extra_design = NULL,\n previous_design = NULL) {\n if (is.null(.subset2(design, \"nobs\"))) {\n cli_abort(sprintf(\n \"you must initialize %s before drawing %s\",\n self$layout_name, object_name(self)\n ), call = self$call)\n }\n direction <- self$direction\n index <- vec_c(\n .subset2(previous_design, \"index\"),\n .subset2(design, \"index\")\n )\n data <- data_frame0(\n .panel = vec_c(\n .subset2(previous_design, \"panel\"),\n .subset2(design, \"panel\")\n ),\n .index = index,\n # ggcross() only reset ordering index, labels should be the same\n .names = .subset(self$labels, index),\n .hand = if (is_horizontal(direction)) {\n factor(\n vec_rep_each(\n c(\"left\", \"right\"),\n c(\n .subset2(previous_design, \"nobs\"),\n .subset2(design, \"nobs\")\n )\n ),\n c(\"left\", \"right\")\n )\n } else {\n factor(\n vec_rep_each(\n c(\"top\", \"bottom\"),\n c(\n .subset2(previous_design, \"nobs\"),\n .subset2(design, \"nobs\")\n )\n ),\n c(\"bottom\", \"top\")\n )\n }\n )\n axis <- to_coord_axis(direction)\n coord_name <- paste0(\".\", axis)\n data[[coord_name]] <- vec_c(\n seq_len(.subset2(previous_design, \"nobs\")),\n seq_len(.subset2(design, \"nobs\"))\n )\n if (!is.null(.subset2(data, \".names\"))) {\n data[[paste0(\".discrete_\", axis)]] <- reorder(\n .subset2(data, \".names\"),\n .subset2(data, coord_name),\n order = FALSE\n )\n }\n plot <- gguse_data(plot, data)\n plot + switch_direction(\n direction,\n default_expansion(x = expansion()),\n default_expansion(y = expansion())\n )\n },\n finish_plot = function(self, plot, schemes, theme) {\n direction <- self$direction\n # remove axis titles, text, ticks used for alignment\n if (isTRUE(self$no_axes)) {\n schemes$scheme_theme <- .subset2(schemes, \"scheme_theme\") +\n theme_no_axes(switch_direction(direction, \"y\", \"x\"))\n }\n plot <- plot_add_schemes(plot, schemes)\n if (is_horizontal(direction)) {\n theme <- theme(\n panel.spacing.y = calc_element(\"panel.spacing.y\", theme)\n )\n } else {\n theme <- theme(\n panel.spacing.x = calc_element(\"panel.spacing.x\", theme)\n )\n }\n plot <- plot + theme\n ggremove_margin(plot, direction) + theme_recycle()\n },\n summary = function(self, plot) {\n header <- ggproto_parent(Craftsman, self)$summary(plot)\n c(header, \" Reset the ordering index and Add plot\")\n }\n)\n"], ["/ggalign/R/layout-operator.R", "#' Layout operator\n#'\n#' @description\n#' `r lifecycle::badge('experimental')`\n#'\n#' - `+`: Adds elements to the active plot in the active layout.\n#' - `&`: Applies elements to all plots in the layout.\n#' - `-`: Adds elements to multiple plots in the layout.\n#'\n#' @details\n#' The `+` operator is straightforward and should be used as needed.\n#'\n#' In order to reduce code repetition `ggalign` provides two operators for\n#' adding ggplot elements (geoms, themes, facets, etc.) to multiple/all plots in\n#' `r rd_layout()`: `-` and `&`.\n#'\n#' @param e1 A `r rd_layout()`.\n#' @param e2 An object to be added to the plot.\n#' @return A modified `Layout` object.\n#' @examples\n#' set.seed(123)\n#' small_mat <- matrix(rnorm(56), nrow = 7)\n#' ggheatmap(small_mat) +\n#' anno_top() +\n#' ggalign() +\n#' geom_point(aes(y = value))\n#'\n#' # `&` operator apply it to all plots\n#' ggheatmap(small_mat) +\n#' anno_top() +\n#' align_dendro() &\n#' theme(panel.border = element_rect(\n#' colour = \"red\", fill = NA, linewidth = unit(2, \"mm\")\n#' ))\n#'\n#' # If the active layout is the annotation stack, the `-` operator will only\n#' # add the elements to all plots in the active annotation stack:\n#' ggheatmap(small_mat) +\n#' anno_left(size = 0.2) +\n#' align_dendro(aes(color = branch), k = 3L) +\n#' align_dendro(aes(color = branch), k = 3L) -\n#' # Modify the the color scales of all plots in the left annotation\n#' scale_color_brewer(palette = \"Dark2\")\n#'\n#' # If the active layout is the `stack_layout()` itself, `-`\n#' # applies the elements to all plots in the layout except the nested\n#' # `ggheatmap()`/`quad_layout()`.\n#' stack_alignv(small_mat) +\n#' align_dendro() +\n#' ggtitle(\"I'm from the parent stack\") +\n#' ggheatmap() +\n#' # remove any active context\n#' stack_active() +\n#' align_dendro() +\n#' ggtitle(\"I'm from the parent stack\") -\n#' # Modify the the color scales of all plots in the stack layout except the\n#' # heatmap layout\n#' scale_color_brewer(palette = \"Dark2\") -\n#' # set the background of all plots in the stack layout except the heatmap\n#' # layout\n#' theme(plot.background = element_rect(fill = \"red\"))\n#'\n#' @name layout-operator\nNULL\n\nutils::globalVariables(\".Generic\")\n\nmethods::setMethod(\"Ops\", c(\"LayoutProto\", \"ANY\"), function(e1, e2) {\n if (missing(e2)) {\n cli_abort(c(\n \"Cannot use {.code {.Generic}} with a single argument.\",\n \"i\" = \"Did you accidentally put {.code {.Generic}} on a new line?\"\n ))\n }\n\n if (is.null(e2)) return(e1) # styler: off\n\n # Get the name of what was passed in as e2, and pass along so that it\n # can be displayed in error messages\n e2name <- deparse(substitute(e2))\n switch(.Generic, # nolint\n `+` = layout_add(e1, e2, e2name),\n `-` = layout_subtract(e1, e2, e2name),\n `&` = layout_and_add(e1, e2, e2name),\n stop_incompatible_op(.Generic, e1, e2)\n )\n})\n\n#################################################################\nlayout_add <- function(layout, object, object_name) {\n UseMethod(\"layout_add\")\n}\n\n#' @export\nlayout_add.QuadLayout <- function(layout, object, object_name) {\n quad_layout_add(object, layout, object_name)\n}\n\n#' @export\nlayout_add.ChainLayout <- function(layout, object, object_name) {\n chain_layout_add(object, layout, object_name)\n}\n\n#################################################################\nlayout_subtract <- function(layout, object, object_name) {\n UseMethod(\"layout_subtract\")\n}\n\n#' @export\nlayout_subtract.QuadLayout <- function(layout, object, object_name) {\n quad_layout_subtract(object, layout, object_name)\n}\n\n#' @export\nlayout_subtract.ChainLayout <- function(layout, object, object_name) {\n chain_layout_subtract(object, layout, object_name)\n}\n\n#################################################################\n# we use and_add suffix here, since `and` is very similar with `add`.\nlayout_and_add <- function(layout, object, object_name) {\n UseMethod(\"layout_and_add\")\n}\n\n#' @export\nlayout_and_add.QuadLayout <- function(layout, object, object_name) {\n quad_layout_and_add(object, layout, object_name)\n}\n\n#' @export\nlayout_and_add.ChainLayout <- function(layout, object, object_name) {\n chain_layout_and_add(object, layout, object_name)\n}\n\n# For objects cannot be used with `-` or `&`\n#' @include layout-quad-operator.R\n#' @include layout-chain-operator.R\nlapply(\n c(\n \"quad_layout_subtract\", \"chain_layout_subtract\",\n \"quad_layout_and_add\", \"chain_layout_and_add\"\n ),\n function(genname) {\n params <- .subset2(strsplit(genname, \"_\"), 1L)\n\n # function argument list\n pairlist <- rlang::pairlist2(object = , layout = , object_name = )\n names(pairlist) <- c(\"object\", .subset(params, 1L), \"object_name\")\n operator <- switch(.subset(params, 3L),\n subtract = \"-\",\n and = \"&\"\n )\n # styler: off\n for (class in c(\"ggplot\", \"quad_active\", \"quad_anno\", \"layout_title\",\n \"layout_theme\", \"CraftBox\", \"ChainLayout\",\n \"QuadLayout\", \"continuous_limits\")) {\n # styler: on\n registerS3method(\n genname, class,\n rlang::new_function(pairlist, substitute(\n {\n cli_abort(c(\n sprintf(\n \"Cannot add %s with {.code %s}\",\n name, operator\n ),\n i = \"Try to use {.code +} instead\"\n ))\n },\n list(\n name = switch(class,\n CraftBox = ,\n ChainLayout = ,\n QuadLayout = quote(object_name(object)),\n # for all others\n \"{.var {object_name}}\"\n ),\n operator = operator\n )\n ))\n )\n }\n }\n)\n"], ["/ggalign/R/with_quad.R", "#' Modify operated Context in `quad_layout()`\n#'\n#' @description\n#' `r lifecycle::badge('experimental')`\n#'\n#' The `with_quad()` function modifies the application context of elements in\n#' `ggheatmap()`/`quad_layout()`. It controls how objects like themes, scales,\n#' or other plot modifications apply to specific annotation stacks or the main\n#' plot without altering the currently active layout or plot.\n#'\n#' @param x An object which can be added to the ggplot, including\n#' **schemes**. See [`scheme_align()`], [`scheme_data()`], and\n#' [`scheme_theme()`]\n#' @param position A string specifying one or more positions-\n#' `r oxford_and(.tlbr)`- to indicate the annotation stack context for `x`. If\n#' `NULL`, will change the operated context to the `quad_layout()` itself. For\n#' default behaivours, see `details` section.\n#' @param main A single boolean value indicating whether `x` should apply to the\n#' main plot, used only when `position` is not `NULL`. By default, if `position`\n#' is `waiver()` and the active context of `quad_layout()` is an annotation\n#' stack or the active context of `stack_layout()` is itself, `main` will be set\n#' to `TRUE`; otherwise, it defaults to `FALSE`.\n#' @return The original object with an added attribute that sets the specified\n#' context.\n#' @details\n#' Default Behavior when adding object wrapped with `with_quad()`:\n#'\n#' For `quad_layout()` object:\n#'\n#' - When `ggheatmap()`/`quad_layout()` has no active annotation stack, objects\n#' added via `+` or `-` operate normally without `with_quad()`.\n#' - When the active annotation stack is set, `with_quad()` ensures the applied\n#' object also modifies:\n#' * The main plot (by default).\n#' * Opposite annotation stacks when using `-`.\n#'\n#' For `stack_layout()` object:\n#'\n#' - When the active layout is the `stack_layout()` itself:\n#' * `-` operator will apply changes to all plots along the\n#' `stack_layout()`, which means if the stack layout is in `horizontal`,\n#' `-` operator will also add the element to the `left` and `right`\n#' annotation, if the stack layout is in `vertical`, `-` operator will\n#' also add element to the `top` and `bottom` annotation.\n#' * `+` operator won't do anything special.\n#' - When the active layout is the nested `ggheatmap()`/`quad_layout()`, the\n#' `+`/`-` operator applies the elements to this nested layout, following the\n#' same principles as for `ggheatmap()`/`quad_layout()`.\n#'\n#' @examples\n#' set.seed(123)\n#' small_mat <- matrix(rnorm(56), nrow = 7)\n#'\n#' # By wrapping object with `with_quad()`, the `+` operator will apply the\n#' # object not only to the active plot in the annotation stack, but also to\n#' # the main plot unless specified by `main` argument otherwise.\n#' ggheatmap(small_mat) +\n#' # initialize the left annotation\n#' anno_left(size = 0.2) +\n#' align_dendro() +\n#' # apply the object not only to the active plot in the annotation stack,\n#' # but also to the main plot\n#' with_quad(theme(plot.background = element_rect(fill = \"red\")))\n#'\n#' # the `-` operator will apply changes not only to the active annotation\n#' # stack but also to the opposite one (i.e., bottom if top is active, and\n#' # vice versa). The same principle applies to the left and right annotation.\n#' ggheatmap(small_mat) +\n#' anno_left(size = 0.2) +\n#' align_dendro(aes(color = branch), k = 3L) +\n#' # Change the active layout to the left annotation\n#' anno_top(size = 0.2) +\n#' align_dendro(aes(color = branch), k = 3L) +\n#' anno_bottom(size = 0.2) +\n#' align_dendro(aes(color = branch), k = 3L) -\n#' # Modify the color scale of all plots in the bottom and the opposite\n#' # annotation, in this way, the `main` argument by default would be `TRUE`\n#' with_quad(scale_color_brewer(palette = \"Dark2\", name = \"Top and bottom\"))\n#'\n#' # When the `position` argument is manually set, the\n#' # default value of the `main` argument will be `FALSE`.\n#' ggheatmap(small_mat) +\n#' anno_left(size = 0.2) +\n#' align_dendro(aes(color = branch), k = 3L) +\n#' anno_top(size = 0.2) +\n#' align_dendro(aes(color = branch), k = 3L) +\n#' anno_bottom(size = 0.2) +\n#' align_dendro(aes(color = branch), k = 3L) -\n#' # Modify the background of all plots in the left and top annotation\n#' with_quad(theme(plot.background = element_rect(fill = \"red\")), \"tl\")\n#' @export\nwith_quad <- function(x, position = waiver(), main = NULL) {\n UseMethod(\"with_quad\")\n}\n\n#' @export\nwith_quad.default <- function(x, position = waiver(), main = NULL) {\n assert_layout_position(position)\n assert_bool(main, allow_null = TRUE)\n structure(\n list(\n object = x,\n object_name = paste(deparse(substitute(x)), collapse = \" \"),\n position = position, main = main\n ),\n class = \"ggalign_with_quad\"\n )\n}\n\n#' @export\nprint.ggalign_with_quad <- function(x, ...) {\n print(.subset2(x, \"object\"))\n invisible(x)\n}\n\n#' @export\nwith_quad.CraftBox <- function(x, position = waiver(), main = NULL) {\n cli_abort(sprintf(\"Cannot used with %s\", object_name(x)))\n}\n\n#' @export\nwith_quad.layout_title <- function(x, position = waiver(), main = NULL) {\n cli_abort(\"Cannot used with {.obj_type_friendly {x}}\")\n}\n\n#' @export\nwith_quad.layout_theme <- with_quad.layout_title\n\n#' @export\nwith_quad.layout_annotation <- with_quad.layout_title\n\n#' @export\nwith_quad.quad_active <- with_quad.layout_title\n\n#' @export\nwith_quad.quad_anno <- with_quad.layout_title\n\n#' @export\nwith_quad.stack_switch <- with_quad.layout_title\n\nquad_operated_context <- function(with, active, operator) {\n if (is.waive(ans <- .subset2(with, \"position\"))) {\n if (operator == \"-\") {\n # if wrap with `with_quad`\n # we determine the `context` from current actual active position\n if (is.null(active)) {\n ans <- NULL\n } else {\n ans <- c(active, opposite_pos(active))\n if (is.null(main <- .subset2(with, \"main\")) || main) {\n ans <- c(ans, list(NULL))\n }\n }\n } else if (operator == \"+\") {\n ans <- active\n if (!is.null(ans)) {\n if (is.null(main <- .subset2(with, \"main\")) || main) {\n ans <- c(ans, list(NULL))\n }\n }\n } else {\n cli_abort(\"Not implement for {operator}\")\n }\n } else if (!is.null(ans)) { # if set manually\n ans <- setup_pos(ans)\n if (!is.null(main <- .subset2(with, \"main\")) && main) {\n ans <- c(ans, list(NULL))\n }\n }\n ans\n}\n\n#' @importFrom ggplot2 ggplot_add\n#' @export\nggplot_add.ggalign_with_quad <- function(object, plot, object_name, ...) {\n object <- .subset2(object, \"object\")\n object_name <- .subset2(object, \"object_name\")\n ggplot_add(object, plot, object_name)\n}\n"], ["/ggalign/R/alignpatch-guides.R", "#' Returns a list of guide boxes collected from all plots.\n#' Each element in the list corresponds to a specific position, containing a\n#' sub-list of guide boxes, where each guide box represents a single plot.\n#' @noRd\ncollect_guides_list <- function(guides_list, empty = NULL) {\n ans <- lapply(c(.TLBR, \"inside\"), function(guide_pos) {\n guides <- lapply(guides_list, function(guides) {\n # IF no guide-box, a single `zeroGrob()` will be given\n # here, we regard each position is a `zeroGrob()`\n if (is_null_grob(guides)) return(list(guides)) # styler: off\n o <- .subset2(guides, guide_pos)\n # A guide-box should be a `zeroGrob()` or a `gtable` object\n if (maybe_guide_box(o)) {\n return(list(o))\n }\n # For other grobs, we just removed them silently\n if (is.grob(o)) {\n list(NULL)\n } else if (is.list(o)) {\n o[\n vapply(o, maybe_guide_box, # styler: off\n logical(1L), USE.NAMES = FALSE # styler: off\n )\n ]\n } else {\n list(NULL)\n }\n })\n guides <- unlist(guides, FALSE, FALSE)\n guides <- guides[\n !vapply(guides, is.null, logical(1L), USE.NAMES = FALSE)\n ]\n if (is_empty(guides)) empty else guides\n })\n names(ans) <- c(.TLBR, \"inside\")\n ans[!vapply(ans, is.null, logical(1L), USE.NAMES = FALSE)]\n}\n\n#' @param guides A list of guide-box\n#' @importFrom ggplot2 zeroGrob\n#' @importFrom gtable gtable gtable_add_grob\n#' @noRd\nassemble_guides <- function(guides, guide_pos, theme) {\n if (guide_pos == \"inside\") {\n # for `zeroGrob()`, it doesn't record the `viewport` information\n # used to identify the inside guide groups, we just removed them\n guides <- guides[\n !vapply(guides, is_null_grob, logical(1L), USE.NAMES = FALSE)\n ]\n if (is_empty(guides)) {\n guide_box <- zeroGrob()\n } else {\n positions <- justs <- vector(\"list\", length(guides))\n for (i in seq_along(guides)) {\n guide <- .subset2(guides, i)\n # for inside guides, it may contain multiple guide-box\n is_box <- grepl(\"guide-box-inside\", guide$layout$name)\n if (any(is_box)) {\n guides[[i]] <- guide$grobs[is_box]\n } else {\n guides[[i]] <- list(guide)\n }\n positions[[i]] <- lapply(guides[[i]], function(guide_box) {\n unit.c(guide_box$vp$x, guide_box$vp$y)\n })\n justs[[i]] <- lapply(guides[[i]], function(guide_box) {\n guide_box$vp$justification\n })\n }\n guides <- unlist(guides, FALSE, FALSE)\n groups <- data_frame0(\n positions = unlist(positions, FALSE, FALSE),\n justs = unlist(justs, FALSE, FALSE)\n )\n groups <- vec_group_loc(groups)\n index <- vec_seq_along(groups)\n\n # pakcage each group into a guide-box\n box_list <- vector(\"list\", vec_size(index))\n for (i in index) {\n box_list[[i]] <- assemble_box(\n guides[groups$loc[[i]]], guide_pos,\n theme = theme + theme(\n legend.position.inside = groups$key$positions[[i]],\n legend.justification.inside = groups$key$justs[[i]]\n )\n )\n }\n if (vec_size(box_list) > 1L) {\n guide_box <- gtable(unit(1L, \"npc\"), unit(1L, \"npc\"))\n guide_box <- gtable_add_grob(\n guide_box, box_list,\n t = 1L, l = 1L, clip = \"off\",\n name = paste(\"guide-box-collected-inside\", index, sep = \"-\")\n )\n } else {\n guide_box <- box_list[[1L]]\n }\n }\n } else {\n guide_box <- assemble_box(guides, guide_pos, theme = theme)\n }\n guide_box\n}\n\n#' @param guides A list of guide-box\n#' @importFrom rlang try_fetch\n#' @importFrom ggplot2 zeroGrob\n#' @noRd\nassemble_box <- function(guides, guide_pos, theme) {\n guides <- guides[\n !vapply(guides, is_null_grob, logical(1L), USE.NAMES = FALSE)\n ]\n if (is_empty(guides)) {\n zeroGrob()\n } else {\n # Remove the guide box background\n grobs <- lapply(guides, function(box) {\n box$grobs[grepl(\"guides\", box$layout$name)]\n })\n grobs <- unlist(grobs, FALSE, FALSE)\n\n # remove duplicated guides\n grobs <- collapse_guides(grobs)\n if (is_empty(grobs)) return(zeroGrob()) # styler: off\n # for every position, collect all individual guides and arrange them\n # into a guide box which will be inserted into the main gtable\n package_box <- try_fetch(\n .subset2(ggfun(\"Guides\"), \"package_box\"),\n error = function(cnd) package_box\n )\n package_box(grobs, guide_pos, theme)\n }\n}\n\n# The following code was used in earlier versions of ggplot2; \n# coverage is not calculated here.\n# nocov start\n#' @importFrom gtable gtable_add_rows gtable_add_cols\n#' @importFrom ggplot2 calc_element\n#' @importFrom grid valid.just editGrob viewport\npackage_box <- function(guides, guide_pos, theme) {\n theme <- complete_guide_theme(guide_pos, theme)\n guides <- guides_build(guides, theme)\n\n # Set the justification of the legend box\n # First value is xjust, second value is yjust\n just <- valid.just(calc_element(\"legend.justification\", theme))\n xjust <- just[1L]\n yjust <- just[2L]\n guides <- editGrob(guides,\n vp = viewport(x = xjust, y = yjust, just = c(xjust, yjust))\n )\n guides <- gtable_add_rows(guides, unit(yjust, \"null\"))\n guides <- gtable_add_rows(guides, unit(1L - yjust, \"null\"), 0L)\n guides <- gtable_add_cols(guides, unit(xjust, \"null\"), 0L)\n guides <- gtable_add_cols(guides, unit(1L - xjust, \"null\"))\n guides\n}\n\n#' @importFrom gtable gtable_width gtable_height gtable gtable_add_grob\n#' @importFrom grid editGrob heightDetails widthDetails valid.just unit.c unit\n#' @importFrom ggplot2 margin element_grob element_blank calc_element element_render\nguides_build <- function(guides, theme) {\n legend.spacing.y <- .subset2(theme, \"legend.spacing.y\")\n legend.spacing.x <- .subset2(theme, \"legend.spacing.x\")\n legend.box.margin <- calc_element(\"legend.box.margin\", theme) %||%\n margin()\n widths <- do.call(`unit.c`, lapply(guides, gtable_width))\n heights <- do.call(`unit.c`, lapply(guides, gtable_height))\n\n just <- valid.just(.subset2(theme, \"legend.box.just\"))\n xjust <- just[1]\n yjust <- just[2]\n vert <- identical(.subset2(theme, \"legend.box\"), \"horizontal\")\n guides <- lapply(guides, function(g) {\n editGrob(g, vp = viewport(\n x = xjust, y = yjust, just = c(xjust, yjust),\n height = if (vert) heightDetails(g) else 1,\n width = if (!vert) widthDetails(g) else 1\n ))\n })\n guide_ind <- seq(by = 2, length.out = length(guides))\n sep_ind <- seq(2, by = 2, length.out = length(guides) - 1)\n if (vert) {\n heights <- max(heights)\n if (length(widths) != 1) {\n w <- unit(rep_len(0, length(widths) * 2 - 1), \"mm\")\n w[guide_ind] <- widths\n w[sep_ind] <- legend.spacing.x\n widths <- w\n }\n } else {\n widths <- max(widths)\n if (length(heights) != 1) {\n h <- unit(rep_len(0, length(heights) * 2 - 1), \"mm\")\n h[guide_ind] <- heights\n h[sep_ind] <- legend.spacing.y\n heights <- h\n }\n }\n widths <- unit.c(legend.box.margin[4], widths, legend.box.margin[2])\n heights <- unit.c(legend.box.margin[1], heights, legend.box.margin[3])\n guides <- gtable_add_grob(\n gtable(widths, heights, name = \"guide-box\"),\n guides,\n t = 1 + if (!vert) guide_ind else 1,\n l = 1 + if (vert) guide_ind else 1,\n name = \"guides\"\n )\n gtable_add_grob(\n guides,\n element_render(theme, \"legend.box.background\"),\n t = 1, l = 1, b = -1, r = -1,\n z = -Inf, clip = \"off\", name = \"legend.box.background\"\n )\n}\n\n#' @importFrom ggplot2 calc_element\ncomplete_guide_theme <- function(guide_pos, theme) {\n if (guide_pos %in% c(\"top\", \"bottom\")) {\n theme$legend.box <- calc_element(\"legend.box\", theme) %||% \"horizontal\"\n theme$legend.direction <- calc_element(\"legend.direction\", theme) %||%\n \"horizontal\"\n theme$legend.box.just <- calc_element(\"legend.box.just\", theme) %||%\n c(\"center\", \"top\")\n } else {\n theme$legend.box <- calc_element(\"legend.box\", theme) %||% \"vertical\"\n theme$legend.direction <- calc_element(\"legend.direction\", theme) %||%\n \"vertical\"\n theme$legend.box.just <- calc_element(\"legend.box.just\", theme) %||%\n c(\"left\", \"top\")\n }\n theme\n}\n# nocov end\n\n################################################################ 3\n# Copied from patchwork\ncollapse_guides <- function(guides) {\n unnamed <- lapply(guides, unname_grob)\n for (i in rev(seq_along(unnamed)[-1])) {\n for (j in seq_len(i - 1)) {\n if (isTRUE(all.equal(unnamed[[i]], unnamed[[j]],\n check.names = FALSE, check.attributes = FALSE\n ))) {\n guides[i] <- NULL\n break\n }\n }\n }\n guides\n}\n\n#' @importFrom grid is.unit absolute.size\nunname_vp <- function(x) {\n if (inherits(x, \"vpTree\")) {\n x$parent <- unname_vp(x$parent)\n x$children <- lapply(x$children, unname_vp)\n } else if (inherits(x, \"viewport\")) {\n x$name <- \"\"\n if (!is.null(x$layout$widths)) {\n x$layout$widths <- absolute.size(x$layout$widths)\n }\n if (!is.null(x$layout$heights)) {\n x$layout$heights <- absolute.size(x$layout$heights)\n }\n }\n unit_elements <- vapply(x, is.unit, logical(1), USE.NAMES = FALSE)\n x[unit_elements] <- lapply(.subset(x, unit_elements), absolute.size)\n x\n}\n\n#' @importFrom grid is.grob is.unit absolute.size\n#' @importFrom gtable is.gtable\nunname_grob <- function(x) {\n if (is.gtable(x)) {\n x$name <- \"\"\n x$rownames <- NULL\n x$vp <- unname_vp(x$vp)\n names(x$grobs) <- NULL\n x$grobs <- lapply(x$grobs, unname_grob)\n } else if (is.grob(x)) {\n x$name <- \"\"\n x$vp <- unname_vp(x$vp)\n x$children <- unname(lapply(x$children, unname_grob))\n x$childrenOrder <- rep_len(\"\", length(x$childrenOrder))\n }\n unit_elements <- vapply(x, is.unit, logical(1), USE.NAMES = FALSE)\n x[unit_elements] <- lapply(.subset(x, unit_elements), absolute.size)\n x\n}\n"], ["/ggalign/R/raster-magick.R", "#' Rasterize the ggplot layers\n#'\n#' The function rasterizes input graphical objects (e.g., grob, layer, ggplot)\n#' and optionally processes the resulting raster using magick, a powerful image\n#' manipulation library. This allows for advanced graphical transformations\n#' directly within the plotting pipeline.\n#'\n#' @param x An object to rasterize, can be a [`grob()`][grid::grob],\n#' [`layer()`][ggplot2::layer], [`ggplot()`][ggplot2::ggplot], or a list of such\n#' objects.\n#'\n#' @inheritParams rlang::args_dots_empty\n#' @inheritParams magickGrob\n#' @examples\n#' # Currently, `magick` package require R >= 4.1.0\n#' if (requireNamespace(\"magick\")) {\n#' # data generated code was copied from `ComplexHeatmap`\n#' set.seed(123)\n#' small_mat <- matrix(rnorm(56), nrow = 7)\n#' rownames(small_mat) <- paste0(\"row\", seq_len(nrow(small_mat)))\n#' colnames(small_mat) <- paste0(\"column\", seq_len(ncol(small_mat)))\n#' ggheatmap(small_mat, aes(.x, .y), filling = NULL) +\n#' raster_magick(geom_tile(aes(fill = value)), res = 20)\n#'\n#' ggheatmap(small_mat, aes(.x, .y), filling = NULL) +\n#' # Use `magick::filter_types()` to check available `filter` arguments\n#' raster_magick(\n#' geom_tile(aes(fill = value)),\n#' magick = function(image) {\n#' magick::image_resize(image,\n#' geometry = \"50%x\", filter = \"Lanczos\"\n#' )\n#' }\n#' )\n#' }\n#' @return An object with the same class of the input.\n#' @seealso [`magickGrob()`]\n#' @export\nraster_magick <- function(x, magick = NULL, ...,\n res = NULL, interpolate = FALSE,\n vp = NULL) {\n rlang::check_installed(\"magick\", \"to use `raster_magick()`\")\n if (!is.null(magick) && !is.function(magick <- allow_lambda(magick))) {\n cli_abort(\"{.arg magick} must be a function\")\n }\n assert_number_whole(res, min = 1, allow_null = TRUE)\n assert_bool(interpolate)\n raster_magick0(\n x = x, ..., magick = magick,\n res = res, interpolate = interpolate,\n vp = vp\n )\n}\n\n# Used to do the actual process, but won't check the arguments\n#' @keywords internal\nraster_magick0 <- function(x, ...) {\n UseMethod(\"raster_magick0\")\n}\n\n#' @importFrom ggplot2 ggproto ggproto_parent\n#' @export\nraster_magick0.Layer <- function(x, ...) {\n ggproto(\n NULL, x,\n draw_geom = function(self, data, layout) {\n grobs <- ggproto_parent(x, self)$draw_geom(data, layout)\n if (!inherits(layout$coord, \"CoordCartesian\")) {\n cli_warn(\n \"{.fn raster_magick} only works with {.fn coord_cartesian}.\"\n )\n return(grobs)\n }\n raster_magick0(grobs, ...)\n }\n )\n}\n\n#' @export\nraster_magick0.ggplot <- function(x, ...) {\n x$layers <- lapply(x$layers, raster_magick0, ...)\n x\n}\n\n#' @export\nraster_magick0.list <- function(x, ...) lapply(x, raster_magick0, ...)\n\n#' @export\nraster_magick0.grob <- function(x, magick = NULL, ...,\n res = NULL, interpolate = FALSE,\n vp = NULL) {\n rlang::check_dots_empty()\n magickGrob0(\n grob = x, magick = magick,\n res = res, interpolate = interpolate, vp = vp\n )\n}\n\n#' @export\nraster_magick0.gList <- raster_magick0.grob\n\n#' @export\nraster_magick0.default <- function(x, ...) {\n cli_abort(\"Cannot rasterize {.obj_type_friendly {x}}\")\n}\n"], ["/ggalign/R/layout-chain-circle-genomic.R", "#' Create a Circular Layout for Genomic Data\n#'\n#' `circle_genomic()` constructs a circular layout specifically for genomic\n#' data. It is a specialized variant of `circle_continuous()` that applies\n#' default axis limits and coerces the first column of each plot’s data to use\n#' chromosome (`seqname`) identifiers—matching those in the layout data—as\n#' factor levels.\n#'\n#' @param data The input data, which can be:\n#' - A `character` string (\"hg19\" or \"hg38\") to load a predefined cytoband\n#' reference.\n#' - A `data.frame` with at least three columns: `chromosome`, `start`, and\n#' `end` positions.\n#' - A genomic object convertible via `fortify_data_frame()`.\n#' @param ... Additional arguments passed to specific methods or\n#' `fortify_data_frame()`.\n#' @inheritParams circle_continuous\n#' @return A `circle_layout` object representing the genomic layout.\n#' @export\ncircle_genomic <- function(data, ..., radial = NULL,\n direction = \"outward\",\n sector_spacing = NULL,\n theme = NULL) {\n UseMethod(\"circle_genomic\")\n}\n\n#' @export\ncircle_genomic.NULL <- function(data, ...) {\n cli_abort(\"{.arg data} must be provided to initialize `circle_genomic()`\")\n}\n\n#' @export\ncircle_genomic.waiver <- circle_genomic.NULL\n\n#' @export\ncircle_genomic.character <- function(data, ...) {\n data <- arg_match0(data, c(\"hg19\", \"hg38\"))\n data <- readRDS(\n pkg_extdata(\n switch(data,\n hg19 = \"ref_cytoband_hg19.rds\",\n hg38 = \"ref_cytoband_hg38.rds\"\n ),\n mustWork = TRUE\n )\n )\n circle_genomic(data, ...)\n}\n\n#' @export\n#' @keywords internal\ncircle_genomic.data.frame <- function(data, ..., radial = NULL,\n direction = \"outward\",\n sector_spacing = NULL,\n theme = NULL) {\n rlang::check_dots_empty()\n if (ncol(data) < 3L) {\n cli_abort(\"{.arg data} must have at least 3 columns: chromosome, start, and end\")\n }\n if (anyNA(data[[1L]]) || anyNA(data[[2L]]) || anyNA(data[[3L]])) {\n cli_abort(\"Columns 1, 2, and 3 of {.arg data} must not contain missing values\")\n }\n if (!is.numeric(data[[2L]]) || !is.numeric(data[[3L]])) {\n cli_abort(\"Columns 2 and 3 of {.arg data} must be numeric (start and end positions)\")\n }\n if (any(data[[2L]] > data[[3L]])) {\n cli_abort(\"Column 2 (start) must not be greater than column 3 (end) in any row of {.arg data}\")\n }\n data[[1L]] <- as.factor(data[[1L]])\n # seqnames, start, end\n # Special considerations for `data.table`, we cannot use `data[1:2]`\n groups <- vec_split(\n data.frame(start = data[[2L]], end = data[[3L]]),\n data[[1L]]\n )\n ranges <- lapply(\n .subset2(groups, \"val\"),\n function(d) genomic_range(.subset2(d, 1L), .subset2(d, 2L))\n )\n lvls <- levels(data[[1L]])\n names(ranges) <- .subset2(groups, \"key\")\n ranges <- ranges[lvls]\n limits <- continuous_limits(!!!ranges)\n ranges <- vec_rbind(!!!ranges, .names_to = \"seqnames\")\n ranges$seqnames <- factor(ranges$seqnames, levels = lvls)\n new_circle_layout(\n data = ggalign_data_set(data, seqnames = lvls, ranges = ranges),\n design = limits,\n radial = radial, direction = direction,\n sector_spacing = sector_spacing,\n schemes = default_schemes(data), theme = theme,\n name = \"circle_genomic\"\n )\n}\n\n#' @export\ncircle_genomic.default <- function(data, ..., radial = NULL,\n direction = \"outward\",\n sector_spacing = NULL,\n theme = NULL) {\n data <- fortify_data_frame(data = data, ...)\n circle_genomic(data,\n radial = radial, direction = direction,\n sector_spacing = sector_spacing, theme = theme\n )\n}\n\ngenomic_range <- function(start, end) {\n if (length(start) == 1) return(c(start = start, end = end)) # styler: off\n ordering <- order(start)\n s <- start[ordering[1L]]\n e <- end[ordering[1L]]\n for (i in ordering[-1L]) {\n if (start[ordering[i]] - e > 1) {\n cli_abort(\"Input genomic ranges cannot contain intervals\")\n }\n e <- end[ordering[i]]\n }\n c(start = s, end = e)\n}\n\n#' @export\nchain_decorate.CircleLayout <- function(layout, plot) {\n if (!identical(layout@name, \"circle_genomic\")) {\n return(plot)\n }\n if (is.data.frame(data <- plot$data)) {\n data[[1L]] <- factor(\n data[[1L]],\n levels = ggalign_attr(layout@data, \"seqnames\")\n )\n missing <- is.na(data[[1L]])\n if (any(missing)) {\n cli_warn(\"Removing {.val {sum(missing)}} rows contain missing {.field seqnames}\")\n data <- vec_slice(data, !missing)\n }\n plot$data <- data\n }\n plot\n}\n"], ["/ggalign/R/ggplot-facet-sector.R", "#' Polar coordinates with Facet support\n#'\n#' Draw each panel in a sector of the polar coordinate system. If\n#' `facet_sector()` is used in a ggplot, the coordinate system must be created\n#' with [`coord_circle()`] or [`coord_radial()`][ggplot2::coord_radial].\n#'\n#' @inheritParams ggplot2::facet_wrap\n#' @param sector_spacing The size of spacing between different panel. A numeric\n#' of the radians or a [`rel()`][ggplot2::rel] object.\n#' @param radial `r lifecycle::badge(\"deprecated\")` Please add the coordinate\n#' system directly to the ggplot instead.\n#' @param spacing_theta `r lifecycle::badge(\"deprecated\")` Please use\n#' `sector_spacing` instead.\n#' @examples\n#' ggplot(mtcars, aes(disp, mpg)) +\n#' geom_point() +\n#' facet_sector(vars(cyl)) +\n#' coord_circle(\n#' start = -0.4 * pi, end = 0.4 * pi, inner.radius = 0.3,\n#' outer.radius = 0.8, expand = TRUE\n#' )\n#' @importFrom ggplot2 ggproto\n#' @export\nfacet_sector <- function(facets, sector_spacing = pi / 180, drop = TRUE,\n radial = deprecated(), spacing_theta = deprecated()) {\n if (packageVersion(\"ggplot2\") > \"3.5.2\") {\n facets <- ggfun(\"compact_facets\")(facets)\n } else {\n facets <- ggfun(\"wrap_as_facets_list\")(facets)\n }\n if (inherits(sector_spacing, \"CoordRadial\") ||\n lifecycle::is_present(radial)) {\n lifecycle::deprecate_stop(\n \"1.0.2\",\n \"facet_sector(radial = )\",\n details = \"Please add the coordinate to the ggplot instead\"\n )\n }\n if (lifecycle::is_present(spacing_theta)) {\n lifecycle::deprecate_warn(\n \"1.0.2\",\n \"facet_sector(spacing_theta = )\",\n \"facet_sector(sector_spacing = )\"\n )\n sector_spacing <- spacing_theta\n }\n\n # @param strip.position By default, the labels are displayed on the\n # `\"outer\"` of the plot. Allowed values are `r oxford_or(c(\"outer\",\n # \"inner\"))`\n # strip.position <- arg_match0(strip.position, c(\"outer\", \"inner\"))\n # strip.position <- switch(strip.position,\n # outer = \"top\",\n # inner = \"bottom\"\n # )\n # labeller <- ggfun(\"fix_labeller\")(labeller)\n assert_bool(drop)\n\n # TO-DO: remove this line and update to\n # the next version of ggplot2 (> 3.5.2)\n if (packageVersion(\"ggplot2\") > \"3.5.2\") {\n dir <- \"lt\"\n } else {\n dir <- \"h\"\n }\n ggproto(\n NULL,\n FacetSector,\n sector_spacing = sector_spacing,\n params = list(\n facets = facets,\n free = list(x = TRUE, y = FALSE),\n strip.position = \"top\",\n drop = drop, ncol = NULL, nrow = 1L,\n space_free = list(x = TRUE, y = FALSE),\n labeller = ggplot2::label_value, dir = dir,\n draw_axes = list(x = TRUE, y = FALSE),\n axis_labels = list(x = TRUE, y = FALSE),\n as.table = TRUE\n )\n )\n}\n\n#' @importFrom ggplot2 ggplot_add\n#' @export\nggplot_add.FacetSector <- function(object, plot, object_name, ...) {\n plot <- NextMethod()\n if (!inherits(plot, \"ggalign_facet_sector_plot\")) {\n plot <- add_class(plot, \"ggalign_facet_sector_plot\")\n }\n plot\n}\n\n#' @importFrom ggplot2 ggplot_build ggproto ggproto_parent\n#' @export\nggplot_build.ggalign_facet_sector_plot <- function(plot, ...) {\n if (inherits(plot$facet, \"FacetSector\")) {\n if (!inherits(plot$coordinates, \"CoordRadial\")) {\n if (!isTRUE(plot$coordinates$default)) {\n cli_abort(c(\n paste(\n \"Cannot use {.fn {snake_class(plot$coordinates)}}\",\n \"coordinate with {.fn facet_sector}\"\n ),\n i = \"Please use {.fn coord_circle}/{.fn coord_radial} instead\"\n ))\n }\n plot$coordinates <- coord_circle()\n }\n ParentLayout <- plot$layout\n plot$layout <- ggproto(\n \"FacetSectorLayout\", ParentLayout,\n setup_panel_params = function(self) {\n ggproto_parent(ParentLayout, self)$setup_panel_params()\n if (is.null(ggplot2::Facet$setup_panel_params) &&\n !is.null(self$facet$setup_panel_params)) {\n self$panel_params <- self$facet$setup_panel_params(\n self$panel_params, self$coord\n )\n }\n invisible()\n }\n )\n }\n NextMethod()\n}\n\n#' @importFrom rlang inject\n#' @importFrom grid gTree editGrob viewport\n#' @importFrom ggplot2 ggproto ggproto_parent\nFacetSector <- ggproto(\n \"FacetSector\", ggplot2::FacetWrap,\n setup_panel_params = function(self, panel_params, coord, ...) {\n # total theta for panel area and panel spacing\n arc_theta <- abs(diff(coord$arc))\n sector_spacing <- self$sector_spacing\n if (inherits(sector_spacing, \"rel\")) {\n sector_spacing <- sector_spacing * arc_theta\n }\n panel_weights <- vapply(panel_params, function(panel_param) {\n abs(diff(.subset2(panel_param, \"theta.range\")))\n }, numeric(1L), USE.NAMES = FALSE)\n\n # total theta for panel area\n panel_theta <- arc_theta -\n # substract the number of spacing between panels\n sector_spacing *\n # for the whole circle, arc_theta == 2 * pi\n # there should be as many panels as the number of panel spacing\n if (abs(arc_theta - 2 * pi) < .Machine$double.eps^0.5) {\n length(panel_weights)\n } else {\n length(panel_weights) - 1L\n }\n if (panel_theta <= 0L) {\n cli_abort(\"No panel area, try to reduce {.arg sector_spacing}\")\n }\n\n # re-distribute the arc for each panel\n panel_point <- vec_interleave(\n panel_theta * panel_weights / sum(panel_weights),\n rep_len(sector_spacing, length(panel_weights))\n )\n panel_point <- cumsum(c(coord$arc[1L], utils::head(panel_point, -1L)))\n for (i in seq_along(panel_params)) {\n panel_param <- .subset2(panel_params, i)\n panel_param$arc <- panel_point[i * 2L - 1:0]\n panel_param$bbox <- ggfun(\"polar_bbox\")(\n panel_param$arc, margin = c(0, 0, 0, 0),\n inner_radius = coord$inner_radius\n )\n panel_params[[i]] <- panel_param\n }\n panel_params\n },\n draw_panels = function(self, panels, layout, x_scales, y_scales, ranges,\n coord, data, theme, params) {\n # merge different sector into one panel\n bbox <- ggfun(\"polar_bbox\")(\n coord$arc, margin = c(0, 0, 0, 0),\n inner_radius = coord$inner_radius\n )\n for (i in seq_along(panels)) {\n panel_param <- .subset2(ranges, i)\n vp <- list(\n x = scales::rescale(panel_param$bbox$x, from = bbox$x),\n y = scales::rescale(panel_param$bbox$y, from = bbox$y)\n )\n panels[[i]] <- editGrob(\n .subset2(panels, i),\n vp = viewport(\n x = vp$x[1L], y = vp$y[1L],\n width = abs(diff(vp$x)),\n height = abs(diff(vp$y)),\n just = c(0, 0),\n clip = \"off\",\n default.units = \"native\"\n )\n )\n }\n panels <- gTree(children = inject(gList(!!!panels)))\n ranges <- lapply(ranges, function(panel_param) {\n panel_param$arc <- coord$arc\n panel_param$bbox <- bbox\n panel_param\n })\n ggplot2::FacetNull$draw_panels(\n panels = list(panels),\n layout = layout, x_scales = x_scales, y_scales = y_scales,\n ranges = ranges, coord = coord, data = data,\n theme = theme, params = params\n )\n }\n)\n"], ["/ggalign/R/craft-cross-link.R", "#' Add a plot to connect selected observations\n#'\n#' @param link A [`link_draw()`] object that defines how to draw the links,\n#' such as [`link_line()`].\n#' @param on_top A boolean value indicating whether to draw the link on top of\n#' the plot panel (`TRUE`) or below (`FALSE`).\n#' @inheritParams cross_none\n#' @inheritParams ggmark\n#'\n#' @section ggplot2 Specification:\n#' The `cross_link` function initializes a `ggplot` object but does not\n#' initialize any data. Using [`scheme_data()`] to change the internal data if\n#' needed.\n#'\n#' @export\ncross_link <- function(link, data = waiver(), ...,\n on_top = TRUE, obs_size = 1,\n inherit_index = NULL, inherit_panel = NULL,\n inherit_nobs = NULL,\n size = NULL, active = NULL) {\n if (!inherits(link, \"ggalign_link_draw\")) {\n cli_abort(\"{.arg link} must be a {.fn link_draw} object\")\n }\n assert_obs_size(obs_size)\n assert_active(active)\n active <- update_active(active, new_active(use = TRUE))\n cross(CrossLink,\n data = data, data_params = list2(...),\n link = link, obs_size = obs_size,\n plot = ggplot(), size = size,\n schemes = default_schemes(),\n active = active,\n on_top = on_top,\n inherit_nobs = inherit_nobs,\n inherit_panel = inherit_panel,\n inherit_index = inherit_index\n )\n}\n\n#' @importFrom ggplot2 ggproto ggproto_parent\n#' @importFrom grid gTree\n#' @include craft-cross-.R\nCrossLink <- ggproto(\"CrossLink\", CraftCross,\n interact_layout = function(self, layout) {\n if (!self$in_linear) { # only used for linear coordinate\n cli_abort(c(\n sprintf(\n \"Cannot add %s to %s\",\n object_name(self), layout_name\n ),\n i = sprintf(\n \"%s can only be used in linear layout\",\n object_name(self)\n )\n ))\n }\n ggproto_parent(CraftCross, self)$interact_layout(layout)\n },\n build_plot = function(self, plot, design, extra_design = NULL,\n previous_design = NULL) {\n if (is.null(.subset2(previous_design, \"nobs\"))) {\n cli_abort(\n sprintf(\n \"layout {.field nobs} for %s before %s is not initialized \",\n self$layout_name, object_name(self)\n )\n )\n }\n if (is.null(.subset2(design, \"nobs\"))) {\n cli_abort(\n sprintf(\n \"layout {.field nobs} for %s after %s is not initialized \",\n self$layout_name, object_name(self)\n )\n )\n }\n\n direction <- self$direction\n position <- self$position\n\n # parse links --------------------------------------------\n link <- self$link\n design1 <- previous_design\n design2 <- design\n full_data1 <- split(\n seq_len(.subset2(design1, \"nobs\")),\n .subset2(design1, \"panel\")\n )\n full_data2 <- split(\n seq_len(.subset2(design2, \"nobs\")),\n .subset2(design2, \"panel\")\n )\n links <- .subset2(link, \"links\")\n # set default links for link_line()\n if (is_empty(links) &&\n inherits(link, \"ggalign_link_line\") &&\n identical(.subset2(design1, \"nobs\"), .subset2(design2, \"nobs\"))) {\n links <- lapply(seq_len(.subset2(design1, \"nobs\")), function(i) {\n rlang::new_formula(i, i)\n })\n links <- pair_links(!!!links)\n }\n link_index <- make_links_data(\n links,\n design1 = design1, design2 = design2,\n labels1 = self$labels0, labels2 = self$labels\n )\n data_index <- lapply(link_index, function(index) {\n if (is.null(index)) {\n return(NULL)\n }\n hand1 <- .subset2(index, \"hand1\")\n hand2 <- .subset2(index, \"hand2\")\n list(\n hand1 = .subset2(design1, \"index\")[hand1],\n hand2 = .subset2(design2, \"index\")[hand2]\n )\n })\n plot$ggalign_link_data <- list(\n full_data1 = full_data1,\n full_data2 = full_data2,\n link_index = link_index,\n data_index = data_index,\n direction = direction,\n draw = .subset2(link, \"draw\"),\n obs_size = self$obs_size\n )\n plot\n },\n finish_plot = function(self, plot, schemes, theme) {\n plot <- plot_add_schemes(plot, schemes)\n\n # save spacing for usage\n spacing <- calc_element(\n switch_direction(\n self$direction,\n \"panel.spacing.y\",\n \"panel.spacing.x\"\n ),\n theme\n ) %||% unit(0, \"mm\")\n\n # setup the grob\n grob <- inject(gTree(\n !!!plot$ggalign_link_data,\n spacing1 = spacing,\n spacing2 = spacing,\n cl = \"ggalignLinkTree\"\n ))\n plot$ggalign_link_data <- NULL\n\n # insert the grob\n plot <- plot + inset(grob, on_top = self$on_top)\n ggremove_margin(plot, self$direction) + theme_recycle()\n },\n summary = function(self, plot) {\n header <- ggproto_parent(CraftCross, self)$summary(plot)\n c(header, \" Add plot to connect selected observations\")\n }\n)\n"], ["/ggalign/R/import-standalone-pkg.R", "# Standalone file: do not edit by hand\n# Source: https://github.com/Yunuuuu/standalone/blob/HEAD/R/standalone-pkg.R\n# Generated by: usethis::use_standalone(\"Yunuuuu/standalone\", \"pkg\")\n# ----------------------------------------------------------------------\n#\n# ---\n# repo: Yunuuuu/standalone\n# file: standalone-pkg.R\n# last-updated: 2025-04-10\n# license: https://unlicense.org\n# imports: [utils]\n# ---\n\n# This file contains various helper utilities, including common functions\n# used across multiple packages I have developed. Some functions depend on\n# other packages that are not listed in Imports, so use them with caution.\n\n# ## Changelog\n# 2025-04-10\n# - simplify `from_namespace`\n#\n# 2025-03-30\n# - Add `use_github_release`\n#\n# 2025-03-12\n# - Add `from_namespace`\n#\n# 2025-03-10:\n# - Add `on_exit`\n#\n# 2025-03-08:\n# - Add `pkg_extdata`\n# - Add `defer`\n#\n# 2025-03-04:\n# - Add `%||%`\n#\n# 2025-03-03:\n# - Add `rd_collect_family`\n# - Add `oxford_and`\n# - Add `oxford_or`\n# - Add `code_quote`\n# - Add `oxford_comma`\n#\n# 2025-02-26:\n# - Add `is_installed`\n# - Add `install_pkgs`\n# - Add `pkg_nm`\n# - Add `pkg_namespace`\n#\n# nocov start\n\n`%||%` <- function(x, y) if (is.null(x)) y else x\n\nis_installed <- local({\n cache <- new.env(parent = emptyenv())\n function(pkg, version = NULL) {\n id <- if (is.null(version)) pkg else paste(pkg, version, sep = \":\")\n out <- cache[[id]]\n if (is.null(out)) {\n if (is.null(version)) {\n out <- requireNamespace(pkg, quietly = TRUE)\n } else {\n out <- requireNamespace(pkg, quietly = TRUE) &&\n utils::packageVersion(pkg) >= version\n }\n assign(id, out, envir = cache, inherits = FALSE)\n }\n out\n }\n})\n\ninstall_pkgs <- function(pkgs) {\n if (is_installed(\"pak\")) {\n getExportedValue(\"pak\", \"pkg_install\")(pkgs, ask = FALSE)\n } else {\n utils::install.packages(pkgs)\n }\n}\n\npkg_nm <- function() utils::packageName(environment())\n\npkg_namespace <- function() topenv(environment())\n\npkg_extdata <- function(..., mustWork = TRUE) {\n system.file(\"extdata\", ..., package = pkg_nm(), mustWork = mustWork)\n}\n\n############################################################\n# I’m having trouble connecting to GitHub, and it seems that `gert` does not\n# respect the proxy settings in my Git config. To work around this, I modified\n# `usethis::use_github_release()` to skip the check that relies on the `gert`\n# package.\nuse_github_release <- function(publish = TRUE) {\n usethis_ns <- getNamespace(\"usethis\")\n usethis <- function(fun, ...) {\n get(x = fun, envir = usethis_ns, inherits = FALSE, ...)\n }\n usethis(\"check_is_package\")(\"use_github_release()\")\n tr <- usethis(\"target_repo\")(\n github_get = TRUE,\n ok_configs = c(\"ours\", \"fork\")\n )\n usethis(\"check_can_push\")(tr = tr, \"to create a release\")\n dat <- usethis(\"get_release_data\")(tr)\n release_name <- paste(dat$Package, dat$Version)\n tag_name <- sprintf(\"v%s\", dat$Version)\n usethis(\"kv_line\")(\"Release name\", release_name)\n usethis(\"kv_line\")(\"Tag name\", tag_name)\n usethis(\"kv_line\")(\"SHA\", dat$SHA)\n usethis(\"check_github_has_SHA\")(SHA = dat$SHA, tr = tr)\n on_cran <- !is.null(usethis(\"cran_version\")())\n news <- usethis(\"get_release_news\")(\n SHA = dat$SHA, tr = tr, on_cran = on_cran\n )\n gh <- usethis(\"gh_tr\")(tr)\n usethis(\"ui_bullets\")(\"Publishing {tag_name} release to GitHub\")\n release <- gh( # nolint\n \"POST /repos/{owner}/{repo}/releases\",\n name = release_name,\n tag_name = tag_name,\n target_commitish = dat$SHA,\n body = news,\n draft = !publish\n )\n usethis(\"ui_bullets\")(\"Release at {.url {release$html_url}}\")\n if (!is.null(dat$file)) {\n usethis(\"ui_bullets\")(\"Deleting {.path {dat$file}}\")\n getExportedValue(\"fs\", \"file_delete\")(dat$file)\n }\n invisible()\n}\n\n############################################################\nfrom_namespace <- local({\n namespace <- NULL\n function(package, name, mode = \"any\") {\n if (is.null(namespace)) namespace <<- getNamespace(package)\n get(x = name, envir = namespace, inherits = FALSE, mode = mode)\n }\n})\n\n# Need `rlang` package, can support `quosure`\non_exit <- function(expr, envir = parent.frame(), after = TRUE, add = TRUE) {\n expr <- getExportedValue(\"rlang\", \"enquo\")(expr)\n defer(\n getExportedValue(\"rlang\", \"eval_tidy\")(expr),\n envir = envir,\n after = after,\n add\n )\n}\n\n# Just like `withr::defer()`, don't depend on `rlang` package\ndefer <- function(expr, envir = parent.frame(), after = TRUE, add = TRUE) {\n thunk <- as.call(list(function() expr))\n do.call(base::on.exit, list(thunk, add = add, after = after), envir = envir)\n}\n\n# utils function to collapse characters ---------------------------\noxford_and <- function(x, code = TRUE, quote = TRUE, sep = \", \") {\n oxford_comma(code_quote(x, code, quote), sep = sep, final = \"and\")\n}\n\noxford_or <- function(x, code = TRUE, quote = TRUE, sep = \", \") {\n oxford_comma(code_quote(x, code, quote), sep = sep, final = \"or\")\n}\n\ncode_quote <- function(x, code = TRUE, quote = TRUE) {\n if (quote) x <- paste0(\"\\\"\", x, \"\\\"\")\n if (code) x <- paste0(\"`\", x, \"`\")\n x\n}\n\noxford_comma <- function(x, sep = \", \", final = \"and\") {\n n <- length(x)\n\n if (n < 2L) return(x) # styler: off\n\n head <- x[seq_len(n - 1L)]\n last <- x[n]\n\n head <- paste(head, collapse = sep)\n\n # Write a or b. But a, b, or c.\n if (n > 2L) {\n paste0(head, sep, final, \" \", last)\n } else {\n paste0(head, \" \", final, \" \", last)\n }\n}\n\n# Need `roxygen2` package\n#' @description add `@eval rd_collect_family(\"myfamily\")` to the functions in\n#' your package. This will automatically generate a section listing all\n#' functions tagged with `@family myfamily`.\n#' @param family A string specifying the family name.\n#' @param section_title A string specifying the section title.\n#' @param code_style A boolean indicating whether to apply code formatting\n#' to function names.\n#' @noRd\nrd_collect_family <- function(\n family,\n section_title = paste(family, \"family\"),\n code_style = TRUE) {\n # get blocks objects from the roxygenize function\n blocks <- NULL\n pos <- sys.nframe()\n while (pos > 0L) {\n if (!is.null(call <- sys.call(-pos))) {\n fn <- eval(.subset2(call, 1L), sys.frame(-(pos + 1L)))\n env <- sys.frame(-pos)\n if (\n identical(fn, getExportedValue(\"roxygen2\", \"roxygenize\")) &&\n exists(\"blocks\", envir = env, inherits = FALSE)\n ) {\n blocks <- get(\"blocks\", envir = env, inherits = FALSE)\n break\n }\n }\n pos <- pos - 1L\n }\n\n # identify the blocks with family of the same tag specified in `family`\n blocks <- blocks[\n vapply(\n blocks,\n function(block) {\n getExportedValue(\"roxygen2\", \"block_has_tags\")(\n block,\n \"family\"\n ) &&\n identical(\n getExportedValue(\"roxygen2\", \"block_get_tag_value\")(\n block,\n \"family\"\n ),\n family\n )\n },\n logical(1L),\n USE.NAMES = FALSE\n )\n ]\n if (length(blocks) == 0L) return(character()) # styler: off\n\n # extracted the function name\n funs <- vapply(\n blocks,\n function(block) {\n as.character(.subset2(block$call, 2L))\n },\n character(1L),\n USE.NAMES = FALSE\n )\n if (code_style) {\n items <- sprintf(\"\\\\code{\\\\link[=%s]{%s()}}\", funs, funs)\n } else {\n items <- sprintf(\"\\\\link[=%s]{%s()}\", funs, funs)\n }\n c(\n sprintf(\"@section %s:\", section_title),\n \"\\\\itemize{\",\n sprintf(\" \\\\item %s\", items),\n \"}\"\n )\n}\n\n# nocov end\n"], ["/ggalign/R/scheme-data.R", "#' Plot data Specifications\n#'\n#' @description\n#' `r lifecycle::badge('experimental')`\n#'\n#' Transforms the plot data. Many functions in this package require a specific\n#' data format to align observations, `scheme_data()` helps reformat data frames\n#' as needed.\n#'\n#' @param data A function to transform the plot data before rendering.\n#' Acceptable values include:\n#'\n#' - `NULL`: No action taken.\n#' - [`waiver()`][ggplot2::waiver()]: Inherits from the parent layout.\n#' - A `function` or purrr-style `formula`: Used to transform the plot data,\n#' which should accept a data frame and return a data frame. You can apply\n#' this after the parent layout `scheme_data` function, using the `inherit`\n#' argument.\n#'\n#' Use this hook to modify the data for all `geoms` after the layout is created\n#' (for matrix data, it has been melted to a long format data frame) but before\n#' rendering by `ggplot2`. The returned data must be a data frame for ggplot.\n#'\n#' @param inherit A single boolean value indicates whether to apply the parent\n#' `scheme_data` first and then apply the specified `scheme_data` for the plot.\n#' Defaults to `FALSE`.\n#'\n#' @details\n#' Defaults will attempt to inherit from the parent layout if the actual data is\n#' inherited from the parent layout, with one exception: `align_dendro()`, which\n#' will not inherit the `scheme_data` by default.\n#'\n#' @export\nscheme_data <- function(data, inherit = FALSE) {\n data <- check_scheme_data(data)\n assert_bool(inherit)\n new_scheme_data(data, inherit)\n}\n\nnew_scheme_data <- function(data = NULL, inherit = FALSE) {\n new_scheme(\n name = \"scheme_data\",\n list(data = data, inherit = inherit),\n class = \"scheme_data\"\n )\n}\n\n#' @export\ninherit_scheme.scheme_data <- function(scheme, pscheme) {\n if (is.null(o <- .subset2(scheme, \"data\"))) return(scheme) # styler: off\n if (is.waive(o)) return(pscheme) # inherit from parent; styler: off\n if (!is.function(p_function <- .subset2(pscheme, \"data\"))) {\n return(scheme)\n }\n # if both are function, we check if we should call parent first then call\n # itself\n if (.subset2(scheme, \"inherit\")) {\n user_scheme_data <- o # current action data function\n scheme$data <- function(data) {\n # we always restore the attached attribute\n ans <- ggalign_data_restore(p_function(data), data)\n user_scheme_data(ans)\n }\n }\n scheme\n}\n\n#' @export\nplot_add_scheme.scheme_data <- function(plot, scheme) {\n # by default, we won't change the data\n if (!is.null(scheme_data <- .subset2(scheme, \"data\") %|w|% NULL) &&\n !is.null(raw_data <- plot$data)) {\n # To be compatible with ggplot2, it must be a data frame\n if (!is.null(data <- scheme_data(raw_data)) &&\n !is.waive(data) &&\n !is.data.frame(data)) {\n cli_abort(\"{.fn scheme_data} must return a {.cls data.frame}\")\n }\n plot <- gguse_data(plot, data)\n }\n plot\n}\n"], ["/ggalign/R/ggplot-geom-rect3d.R", "#' Add z-aesthetic for geom_tile\n#'\n#' @section new aesthetics:\n#' - `z`: the third dimention (in the z direction), use\n#' [`scale_z_continuous()`] to control the ranges.\n#' - `theta`: Angle between x-axis and z-axis.\n#' @inheritParams ggplot2::layer\n#' @inheritParams ggplot2::geom_polygon\n#' @inheritParams ggplot2::geom_path\n#' @aesthetics GeomRect3d\n#' @examples\n#' set.seed(123)\n#' small_mat <- matrix(rnorm(81), nrow = 9)\n#' rownames(small_mat) <- paste0(\"row\", seq_len(nrow(small_mat)))\n#' colnames(small_mat) <- paste0(\"column\", seq_len(ncol(small_mat)))\n#' ggheatmap(small_mat,\n#' filling = FALSE,\n#' theme = theme(\n#' legend.box.spacing = unit(10, \"mm\"),\n#' plot.margin = margin(t = 15, unit = \"mm\")\n#' )\n#' ) +\n#' geom_tile3d(\n#' aes(fill = value, z = value, width = 0.8, height = 0.8),\n#' color = \"black\"\n#' ) +\n#' scale_fill_viridis_c(\n#' option = \"plasma\",\n#' breaks = scales::breaks_pretty(3L)\n#' ) +\n#' coord_cartesian(clip = \"off\")\n#'\n#' @export\ngeom_rect3d <- function(mapping = NULL, data = NULL, stat = \"identity\",\n position = \"identity\", ...,\n lineend = \"butt\", linejoin = \"round\", linemitre = 10,\n na.rm = FALSE, show.legend = NA, inherit.aes = TRUE) {\n ggplot2::layer(\n data = data,\n mapping = mapping,\n stat = stat,\n geom = GeomRect3d,\n position = position,\n show.legend = show.legend,\n inherit.aes = inherit.aes,\n params = list(\n lineend = lineend,\n linejoin = linejoin,\n linemitre = linemitre,\n na.rm = na.rm, ...\n )\n )\n}\n\n#' @importFrom ggplot2 ggproto fill_alpha\nGeomRect3d <- ggproto(\n \"GeomRect3d\",\n ggplot2::GeomRect,\n required_aes = c(ggplot2::GeomRect$required_aes, \"z\"),\n non_missing_aes = c(ggplot2::GeomRect$non_missing_aes, \"z\", \"theta\"),\n setup_data = function(self, data, params) {\n theta <- data$theta %||% .subset2(params, \"theta\")\n if (!is.null(theta) && any(theta <= 0 || theta >= 90)) {\n cli_abort(\n \"value mapped to {.field theta} aesthetic must > 0 and < 90.\"\n )\n }\n data$theta <- theta %||% 60\n ggproto_parent(ggplot2::GeomRect, self)$setup_data(data, params)\n },\n draw_panel = function(self, data, panel_params, coord, lineend = \"butt\",\n linejoin = \"round\", linemitre = 10) {\n data <- setup_3d_data(data)\n # Transform to viewport coords\n coords <- coord$transform(data, panel_params)\n\n # collapse the gpar value\n data <- .subset2(\n vec_split(\n data[setdiff(names(data), c(\"x\", \"y\", \"width\", \"height\"))],\n .subset2(data, \"polygon_id\")\n ),\n \"val\"\n )\n data <- vec_rbind(!!!lapply(data, vec_unique))\n\n # Draw as grob\n grid::polygonGrob(\n x = coords$x,\n y = coords$y,\n id = coords$polygon_id,\n default.units = \"native\",\n gp = gpar(\n col = data$colour,\n fill = fill_alpha(data$fill, data$alpha),\n lwd = data$linewidth,\n lty = data$linetype,\n lineend = lineend,\n linejoin = linejoin,\n linemitre = linemitre\n )\n )\n }\n)\n\nsetup_3d_data <- function(data) {\n data <- vec_slice(\n data,\n order(\n .subset2(data, \"xmin\"),\n .subset2(data, \"ymin\"),\n decreasing = TRUE\n )\n )\n coords <- .mapply(\n function(xmin, xmax, ymin, ymax, z, theta, ...) {\n if (z == 0L) {\n # fallback to tile\n data_frame0(\n x = vec_c(xmin, xmax, xmax, xmin),\n y = vec_rep_each(c(ymin, ymax), 2L)\n )\n } else {\n offset_x <- z * cos(theta / 180 * pi)\n z_xmin <- xmin + offset_x\n z_xmax <- xmax + offset_x\n offset_y <- z * sin(theta / 180 * pi)\n z_ymin <- ymin + offset_y\n z_ymax <- ymax + offset_y\n data_frame0(\n x = vec_c(\n xmin, z_xmin, z_xmax, xmax, xmin, xmin,\n z_xmin, z_xmin, z_xmin, z_xmax, z_xmax, z_xmin\n ),\n y = vec_c(\n ymin, z_ymin, z_ymin, ymin, ymin, ymax,\n z_ymax, z_ymin, z_ymax, z_ymax, z_ymin, z_ymin\n )\n )\n }\n },\n data,\n MoreArgs = NULL\n )\n vec_cbind(\n vec_rbind(!!!coords),\n vec_rep_each(\n data[\n vec_set_difference(\n names(data),\n c(\"x\", \"xmin\", \"xmax\", \"y\", \"ymin\", \"ymax\", \"z\")\n )\n ],\n list_sizes(coords)\n ),\n polygon_id = vec_rep_each(seq_along(coords), list_sizes(coords))\n )\n}\n\n#' @aesthetics GeomTile3d\n#' @importFrom rlang list2\n#' @export\n#' @rdname geom_rect3d\ngeom_tile3d <- function(mapping = NULL, data = NULL, stat = \"identity\",\n position = \"identity\", ...,\n lineend = \"butt\", linejoin = \"round\", linemitre = 10,\n na.rm = FALSE, show.legend = NA, inherit.aes = TRUE) {\n ggplot2::layer(\n data = data,\n mapping = mapping,\n stat = stat,\n geom = GeomTile3d,\n position = position,\n show.legend = show.legend,\n inherit.aes = inherit.aes,\n params = list(\n lineend = lineend,\n linejoin = linejoin,\n linemitre = linemitre,\n na.rm = na.rm, ...\n )\n )\n}\n\n#' @importFrom ggplot2 ggproto ggproto_parent\nGeomTile3d <- ggproto(\n \"GeomTile3d\",\n ggplot2::GeomTile,\n required_aes = c(ggplot2::GeomTile$required_aes, \"z\"),\n non_missing_aes = c(ggplot2::GeomTile$non_missing_aes, \"z\", \"theta\"),\n setup_data = function(self, data, params) {\n theta <- data$theta %||% .subset2(params, \"theta\")\n if (!is.null(theta) && any(theta <= 0 || theta >= 90)) {\n cli_abort(\n \"value mapped to {.field theta} aesthetic must > 0 and < 90.\"\n )\n }\n data$theta <- theta %||% 60\n ggproto_parent(ggplot2::GeomTile, self)$setup_data(data, params)\n },\n draw_panel = function(self, data, panel_params, coord, lineend = \"butt\",\n linejoin = \"round\", linemitre = 10) {\n ggproto_parent(GeomRect3d, self)$draw_panel(\n data = data, panel_params = panel_params, coord = coord,\n lineend = lineend, linejoin = linejoin, linemitre = linemitre\n )\n }\n)\n\n#' z scales\n#'\n#' @param ... Other arguments passed on to\n#' [`continuous_scale()`][ggplot2::continuous_scale],\n#' [`binned_scale()`][ggplot2::binned_scale], or\n#' [`discrete_scale()`][ggplot2::discrete_scale] as appropriate, to control\n#' name, limits, breaks, labels and so forth.\n#' @param range Output range of z values. Must larger than 0.\n#' @inheritParams ggplot2::continuous_scale\n#' @seealso [`geom_tile3d()`]/[`geom_rect3d()`]\n#' @export\n#' @examples\n#'\n#' set.seed(7)\n#' mat <- matrix(runif(100), 10)\n#' rownames(mat) <- LETTERS[1:10]\n#' colnames(mat) <- letters[1:10]\n#' ggheatmap(mat,\n#' filling = FALSE,\n#' theme = theme(\n#' legend.box.spacing = unit(10, \"mm\"),\n#' plot.margin = margin(t = 15, unit = \"mm\")\n#' )\n#' ) +\n#' geom_tile3d(aes(fill = value, z = value, width = 0.8, height = 0.8)) +\n#' scale_z_continuous(range = c(0.2, 1)) +\n#' coord_cartesian(clip = \"off\")\n#' @export\nscale_z_continuous <- function(name = waiver(), ..., range = c(0.1, 1),\n guide = \"none\") {\n if (min(range) < 0) {\n cli_abort(\"{.arg range} must contain only positive values\")\n }\n ggplot2::continuous_scale(\"z\",\n name = name, palette = scales::pal_rescale(range), ...,\n guide = guide\n )\n}\n\n#' @rdname scale_z_continuous\n#' @export\nscale_z_binned <- function(name = waiver(), ..., range = c(0.1, 1),\n guide = \"none\") {\n if (min(range) < 0) {\n cli_abort(\"{.arg range} must contain only positive values\")\n }\n ggplot2::binned_scale(\"z\",\n name = name, palette = scales::pal_rescale(range), ...,\n guide = guide\n )\n}\n\n#' @rdname scale_z_continuous\n#' @export\nscale_z_discrete <- function(...) {\n cli_warn(\"Using {z} for a discrete variable is not advised.\")\n args <- list2(...)\n args$call <- args$call %||% current_call()\n rlang::exec(scale_z_ordinal, !!!args)\n}\n\n#' @rdname scale_z_continuous\n#' @export\nscale_z_ordinal <- function(name = waiver(), ..., range = c(0.1, 1),\n guide = \"none\") {\n if (min(range) < 0) {\n cli_abort(\"{.arg range} must contain only positive values\")\n }\n ggplot2::discrete_scale(\n \"z\",\n name = name,\n palette = function(n) seq(range[1], range[2], length.out = n),\n ...,\n gudie = guide\n )\n}\n\n#' @rdname scale_z_continuous\n#' @export\n#' @usage NULL\nscale_z_datetime <- function(name = waiver(), ..., range = c(0.1, 1),\n guide = \"none\") {\n if (min(range) < 0) {\n cli_abort(\"{.arg range} must contain only positive values\")\n }\n ggplot2::datetime_scale(\n aesthetics = \"z\", transform = \"time\", name = name,\n palette = scales::pal_rescale(range),\n ..., guide = guide\n )\n}\n\n#' @rdname scale_z_continuous\n#' @export\n#' @usage NULL\nscale_z_date <- function(name = waiver(), ..., range = c(0.1, 1),\n guide = \"none\") {\n if (min(range) < 0) {\n cli_abort(\"{.arg range} must contain only positive values\")\n }\n ggplot2::datetime_scale(\n aesthetics = \"z\", transform = \"date\", name = name,\n palette = scales::pal_rescale(range),\n ..., guide = guide\n )\n}\n"], ["/ggalign/R/ggplot-geom-pie.R", "#' Pie charts\n#' @section new aesthetics:\n#' - `angle`: the pie circle angle.\n#' - `angle0`: the initial pie circle angle.\n#' - `radius`: the circle radius.\n#' @inheritParams ggplot2::layer\n#' @inheritParams ggplot2::geom_polygon\n#' @inheritParams ggplot2::geom_path\n#' @param steps An integer indicating the number of steps to generate the pie\n#' chart radian. Increasing this value results in a smoother pie circular.\n#' @param clockwise A single boolean value indicates clockwise or not.\n#' @aesthetics GeomPie\n#' @examples\n#' ggplot(data.frame(x = 1:10, y = 1:10, value = 1:10 / sum(1:10))) +\n#' geom_pie(aes(x, y, angle = value * 360))\n#' @export\ngeom_pie <- function(mapping = NULL, data = NULL, stat = \"identity\",\n position = \"identity\", ...,\n clockwise = TRUE, steps = 100,\n lineend = \"butt\", linejoin = \"round\", linemitre = 10,\n na.rm = FALSE,\n show.legend = NA, inherit.aes = TRUE) {\n ggplot2::layer(\n data = data,\n mapping = mapping,\n stat = stat,\n geom = GeomPie,\n position = position,\n show.legend = show.legend,\n inherit.aes = inherit.aes,\n params = list(\n lineend = lineend,\n linejoin = linejoin,\n linemitre = linemitre,\n clockwise = clockwise,\n na.rm = na.rm, steps = steps, ...\n )\n )\n}\n\n#' @importFrom grid gpar\n#' @importFrom ggplot2 ggproto aes resolution fill_alpha\n#' @importFrom rlang set_names\nGeomPie <- ggproto(\"GeomPie\",\n ggplot2::GeomPolygon,\n default_aes = aes(\n !!!set_names(\n ggplot2::GeomPolygon$default_aes,\n function(nms) {\n nms <- set_names(nms)\n vec_slice(nms, \"subgroup\") <- \"radius\"\n nms\n }\n ),\n angle0 = 0\n ),\n non_missing_aes = c(\"x\", \"y\", \"angle\", \"angle0\", \"radius\"),\n required_aes = c(\"x\", \"y\", \"angle\"),\n handle_na = ggplot2::Geom$handle_na,\n setup_params = function(self, data, params) {\n steps <- vec_cast(.subset2(params, \"steps\"), integer(),\n x_arg = \"steps\",\n call = call(snake_class(self))\n )\n assert_bool(.subset2(params, \"clockwise\"),\n arg = \"clockwise\", call = call(snake_class(self))\n )\n params$steps <- max(steps, 1L) + 1L\n params\n },\n setup_data = function(data, params) {\n # use the same strategy of geom_bar\n data$radius <- data$radius %||%\n params$radius %||% (\n min(\n vapply(\n split(data$x, data$PANEL, drop = TRUE),\n resolution, numeric(1),\n zero = FALSE,\n USE.NAMES = FALSE\n ),\n vapply(\n split(data$y, data$PANEL, drop = TRUE),\n resolution, numeric(1),\n zero = FALSE,\n USE.NAMES = FALSE\n )\n ) * 0.45)\n data\n },\n draw_panel = function(data, panel_params, coord, steps = 100L,\n clockwise = TRUE, lineend = \"butt\",\n linejoin = \"round\", linemitre = 10) {\n # Expand x, y, radius data to points along circle\n circular_data <- .mapply(\n function(x, y, radius, ang, ang0) {\n if (clockwise) {\n ang0 <- 90 - ang0\n radians <- seq(ang0, ang0 - ang, length.out = steps)[-1L]\n } else {\n ang0 <- 90 + ang0\n radians <- seq(ang0, ang0 + ang, length.out = steps)[-1L]\n }\n radians <- radians / 180 * pi\n data_frame0(\n x = c(x, cos(radians) * radius + x),\n y = c(y, sin(radians) * radius + y)\n )\n },\n list(\n x = data$x, y = data$y,\n radius = data$radius, ang = data$angle, ang0 = data$angle0\n ),\n MoreArgs = NULL\n )\n circular_data <- vec_rbind(!!!circular_data)\n\n # Transform to viewport coords\n circular_data <- coord$transform(circular_data, panel_params)\n\n # Draw as grob\n grid::polygonGrob(\n x = circular_data$x,\n y = circular_data$y,\n id.lengths = rep_len(steps, nrow(data)),\n default.units = \"native\",\n gp = gpar(\n col = data$colour,\n fill = fill_alpha(data$fill, data$alpha),\n lwd = data$linewidth,\n lty = data$linetype,\n lineend = lineend,\n linejoin = linejoin,\n linemitre = linemitre\n )\n )\n }\n)\n"], ["/ggalign/R/alignpatch-ggplot2.R", "#' @export\nggalign_gtable.ggplot <- function(x) alignpatch(x)$patch_gtable()\n\n#' @export\nggalign_build.ggplot <- function(x) x\n\n##################################################\n#' @export\n#' @include alignpatch-build.R\nprint.patch_ggplot <- print.alignpatches\n\n#' @importFrom grid grid.draw\n#' @exportS3Method\ngrid.draw.patch_ggplot <- grid.draw.alignpatches\n\n#################################################\n#' @importFrom ggplot2 ggproto\n#' @export\nalignpatch.ggplot <- function(x) ggproto(NULL, PatchGgplot, plot = x)\n\n# ggplot2 has following grobs:\n# panel\n# axis: must follow panel\n# strip: must follow the panel\n# xlab/ylab: can be aligned or follow the panel\n# subtitle\n# title\n# caption\n# guide: can be collected or kept\n#' @importFrom ggplot2 ggplotGrob update_labels\n#' @include alignpatch-.R\nPatchGgplot <- ggproto(\"PatchGgplot\", Patch,\n set_guides = function(guides) guides,\n patch_gtable = function(self, theme, guides, plot = self$plot) {\n # extract patch titles --------------------------------\n patch_titles <- plot$ggalign_patch_labels\n\n # complete_theme() will ensure elements exist --------\n theme <- complete_theme(plot$theme)\n # here: we remove tick length when the tick is blank\n theme <- setup_tick_length_element(theme)\n plot$theme <- theme\n\n # build the grob -------------------------------------\n ans <- ggplotGrob(plot)\n strip_pos <- find_strip_pos(ans)\n # always add strips columns and/or rows\n ans <- add_strips(ans, strip_pos)\n setup_patch_titles(ans, patch_titles = patch_titles, theme = theme)\n },\n respect = function(self, gt = self$gt) .subset2(gt, \"respect\"),\n\n #' @importFrom ggplot2 find_panel\n align_panel_sizes = function(self, panel_width, panel_height,\n gt = self$gt) {\n panel_pos <- find_panel(gt)\n rows <- c(.subset2(panel_pos, \"t\"), .subset2(panel_pos, \"b\"))\n cols <- c(.subset2(panel_pos, \"l\"), .subset2(panel_pos, \"r\"))\n respect <- .subset2(gt, \"respect\")\n if (rows[1L] == rows[2L] && cols[1L] == cols[2L]) {\n if (respect) {\n can_set_width <- is.na(as.numeric(panel_width))\n can_set_height <- is.na(as.numeric(panel_height))\n w <- .subset2(gt, \"widths\")[LEFT_BORDER + 1L]\n h <- .subset2(gt, \"heights\")[TOP_BORDER + 1L]\n if (can_set_width && can_set_height) {\n panel_width <- w\n panel_height <- h\n } else if (can_set_width) {\n panel_width <- as.numeric(w) / as.numeric(h) * panel_height\n } else if (can_set_height) {\n panel_height <- as.numeric(h) / as.numeric(w) * panel_width\n } else {\n respect <- FALSE\n }\n }\n } else {\n respect <- FALSE\n }\n list(width = panel_width, height = panel_height, respect = respect)\n },\n\n #' @importFrom gtable gtable_add_grob gtable_height gtable_width\n #' @importFrom grid unit viewport\n #' @importFrom ggplot2 find_panel\n free_border = function(self, borders, gt = self$gt) {\n panel_pos <- find_panel(gt)\n for (border in borders) {\n if (border == \"top\") {\n gt <- liberate_area(\n gt,\n 1L,\n 1L,\n .subset2(panel_pos, \"t\") - 1L,\n ncol(gt),\n clip = \"off\",\n name = \"free-border-top\",\n vp = ~ viewport(\n y = 0L, just = \"bottom\",\n height = gtable_height(.x)\n )\n )\n } else if (border == \"left\") {\n gt <- liberate_area(\n gt,\n 1L,\n 1L,\n nrow(gt),\n .subset2(panel_pos, \"l\") - 1L,\n clip = \"off\",\n name = \"free-border-left\",\n vp = ~ viewport(\n x = 1L, just = \"right\",\n width = gtable_width(.x)\n )\n )\n } else if (border == \"bottom\") {\n gt <- liberate_area(\n gt,\n .subset2(panel_pos, \"b\") + 1L,\n 1L,\n nrow(gt),\n ncol(gt),\n clip = \"off\",\n name = \"free-border-bottom\",\n vp = ~ viewport(\n y = 1L, just = \"top\",\n height = gtable_height(.x)\n )\n )\n } else if (border == \"right\") {\n gt <- liberate_area(\n gt,\n 1L,\n .subset2(panel_pos, \"r\") + 1L,\n nrow(gt),\n ncol(gt),\n clip = \"off\",\n name = \"free-border-right\",\n vp = ~ viewport(\n x = 0L, just = \"left\",\n width = gtable_width(.x)\n )\n )\n }\n }\n gt\n },\n align_free_border = function(self, borders,\n t = NULL, l = NULL, b = NULL, r = NULL,\n gt = self$gt) {\n if (is.null(t) && is.null(l) && is.null(b) && is.null(r)) {\n return(gt)\n }\n # For free borders, we also align the margins\n for (border in borders) {\n i <- .subset2(.subset2(gt, \"layout\"), \"name\") ==\n sprintf(\"free-border-%s\", border)\n if (any(i)) {\n i <- which(i)\n gt$grobs[[i]] <- switch_position(\n border,\n Patch$align_border(l = l, r = r, gt = gt$grobs[[i]]),\n Patch$align_border(t = t, b = b, gt = gt$grobs[[i]])\n )\n }\n }\n gt\n },\n\n #' @importFrom ggplot2 find_panel\n #' @importFrom gtable is.gtable gtable_height gtable_width gtable_add_grob\n #' @importFrom grid grobHeight grobWidth viewport\n free_lab = function(self, labs, gt = self$gt) {\n panel_pos <- find_panel(gt)\n for (lab in labs) {\n name <- paste(\n switch_position(lab, \"xlab\", \"ylab\"),\n \"axis\", lab,\n sep = \"-\"\n )\n if (lab == \"top\") {\n panel_border <- .subset2(panel_pos, \"t\")\n gt <- liberate_area(\n gt,\n panel_border - 3L,\n .subset2(panel_pos, \"l\"),\n panel_border - 1L,\n .subset2(panel_pos, \"r\"),\n name = name,\n vp = ~ viewport(\n y = 0L, just = \"bottom\",\n height = gtable_height(.x)\n )\n )\n } else if (lab == \"left\") {\n panel_border <- .subset2(panel_pos, \"l\")\n gt <- liberate_area(\n gt,\n .subset2(panel_pos, \"t\"),\n panel_border - 3L,\n .subset2(panel_pos, \"b\"),\n panel_border - 1L,\n name = name,\n vp = ~ viewport(\n x = 1L, just = \"right\",\n width = gtable_width(.x)\n )\n )\n } else if (lab == \"bottom\") {\n panel_border <- .subset2(panel_pos, \"b\")\n gt <- liberate_area(\n gt,\n panel_border + 1L,\n .subset2(panel_pos, \"l\"),\n panel_border + 3L,\n .subset2(panel_pos, \"r\"),\n name = name,\n vp = ~ viewport(\n y = 1L, just = \"top\",\n height = gtable_height(.x)\n )\n )\n } else if (lab == \"right\") {\n panel_border <- .subset2(panel_pos, \"r\")\n gt <- liberate_area(\n gt,\n .subset2(panel_pos, \"t\"),\n panel_border + 1L,\n .subset2(panel_pos, \"b\"),\n panel_border + 3L,\n name = name,\n vp = ~ viewport(\n x = 0L, just = \"left\",\n width = gtable_width(.x)\n )\n )\n }\n }\n gt\n }\n)\n\n#' @importFrom ggplot2 calc_element\n#' @importFrom grid unit\nsetup_tick_length_element <- function(theme) {\n for (tick in c(\"x.top\", \"y.left\", \"x.bottom\", \"y.right\")) {\n for (axis in c(\"axis.minor\", \"axis\")) {\n blank <- inherits(calc_element(\n paste(axis, \"ticks\", tick, sep = \".\"), theme\n ), \"element_blank\")\n if (blank) { # No ticks, no length\n element <- paste(axis, \"ticks.length\", tick, sep = \".\")\n theme[[element]] <- unit(0, \"mm\")\n }\n }\n }\n theme\n}\n\n#' @importFrom gtable gtable_add_rows gtable_add_cols\n#' @importFrom ggplot2 find_panel\n#' @importFrom grid unit\nadd_strips <- function(gt, strip_pos) {\n panel_loc <- find_panel(gt)\n strip_pos <- switch(strip_pos, inside = 0L, outside = 2L) # styler: off\n layout <- .subset2(gt, \"layout\")\n if (!any(grepl(\"strip-b\", layout$name))) { # No strips\n gt <- gtable_add_rows(\n gt, unit(0L, \"mm\"),\n panel_loc$b + strip_pos\n )\n } else if (strip_pos == 2L && !any(layout$b == panel_loc$b + 2L)) {\n # Merge the strip-gap height into the axis and remove it. Only performed\n # if an axis exist\n gt$heights[panel_loc$b + 1L] <- sum(gt$heights[panel_loc$b + 1:2])\n gt <- gt[-(panel_loc$b + 2L), ]\n }\n if (!any(grepl(\"strip-t\", layout$name))) {\n gt <- gtable_add_rows(\n gt, unit(0L, \"mm\"),\n panel_loc$t - 1L - strip_pos\n )\n } else if (strip_pos == 2L && !any(layout$t == panel_loc$t - 2L)) {\n gt$heights[panel_loc$t - 1L] <- sum(gt$heights[panel_loc$t - 1:2])\n gt <- gt[-(panel_loc$t - 2L), ]\n }\n if (!any(grepl(\"strip-r\", layout$name))) {\n gt <- gtable_add_cols(\n gt, unit(0L, \"mm\"),\n panel_loc$r + strip_pos\n )\n } else if (strip_pos == 2L && !any(layout$r == panel_loc$r + 2L)) {\n gt$widths[panel_loc$r + 1L] <- sum(gt$widths[panel_loc$r + 1:2])\n gt <- gt[, -(panel_loc$r + 2L)]\n }\n if (!any(grepl(\"strip-l\", layout$name))) {\n gt <- gtable_add_cols(\n gt, unit(0L, \"mm\"),\n panel_loc$l - 1L - strip_pos\n )\n } else if (strip_pos == 2L && !any(layout$l == panel_loc$l - 2L)) {\n gt$widths[panel_loc$l - 1L] <- sum(gt$widths[panel_loc$l - 1:2])\n gt <- gt[, -(panel_loc$l - 2L)]\n }\n gt\n}\n\n# theme(strip.placement)\n#' @importFrom ggplot2 find_panel\nfind_strip_pos <- function(gt) {\n panel_loc <- find_panel(gt)\n layout <- .subset2(gt, \"layout\")\n nms <- .subset2(layout, \"name\")\n ind <- grep(\"strip-t\", nms)\n if (length(ind) != 0L && panel_loc$t - min(layout$t[ind]) != 1L) {\n return(\"outside\")\n }\n ind <- grep(\"strip-l\", nms)\n if (length(ind) != 0L && panel_loc$l - min(layout$l[ind]) != 1L) {\n return(\"outside\")\n }\n ind <- grep(\"strip-r\", nms)\n if (length(ind) != 0L && max(layout$r[ind]) - panel_loc$r != 1L) {\n return(\"outside\")\n }\n ind <- grep(\"strip-b\", nms)\n if (length(ind) != 0L && max(layout$b[ind]) - panel_loc$b != 1L) {\n return(\"outside\")\n }\n \"inside\"\n}\n"], ["/ggalign/R/ggplot-geom-subrect.R", "#' Subdivide Rectangles\n#'\n#' @description\n#' These geoms subdivide rectangles with shared borders into a grid. Both geoms\n#' achieve the same result but differ in how the rectangles are parameterized:\n#' - **`geom_subrect()`**: Defines rectangles using their four corners (`xmin`,\n#' `xmax`, `ymin`, `ymax`).\n#' - **`geom_subtile()`**: Defines rectangles using the center (`x`, `y`) and\n#' dimensions (`width`, `height`).\n#'\n#' @param byrow A single boolean value indicates whether we should arrange the\n#' divided rectangles in the row-major order.\n#' @param nrow,ncol A single positive integer specifying the number of rows or\n#' columns in the layout of the subdivided cell. By default, the layout\n#' dimensions are determined automatically using logic similar to\n#' [`facet_wrap()`][ggplot2::facet_wrap].\n#' @param direction `r lifecycle::badge(\"deprecated\")` A string specifying the\n#' arrangement direction:\n#' - `\"h\"`(`horizontal`): Creates a single row (one-row layout).\n#' - `\"v\"`(`vertical`): Creates a single column (one-column layout).\n#' @inheritParams ggplot2::geom_rect\n#' @inheritParams ggplot2::geom_segment\n#' @aesthetics GeomSubrect\n#' @examples\n#' # arranges by row\n#' ggplot(data.frame(value = letters[seq_len(5)])) +\n#' geom_subtile(aes(x = 1, y = 1, fill = value), byrow = TRUE)\n#'\n#' # arranges by column\n#' ggplot(data.frame(value = letters[seq_len(9)])) +\n#' geom_subtile(aes(x = 1, y = 1, fill = value))\n#'\n#' # one-row\n#' ggplot(data.frame(value = letters[seq_len(4)])) +\n#' geom_subtile(aes(x = 1, y = 1, fill = value), nrow = 1)\n#'\n#' # one-column\n#' ggplot(data.frame(value = letters[seq_len(4)])) +\n#' geom_subtile(aes(x = 1, y = 1, fill = value), ncol = 1)\n#'\n#' @importFrom rlang list2\n#' @export\ngeom_subrect <- function(mapping = NULL, data = NULL,\n stat = \"identity\", position = \"identity\",\n ...,\n byrow = FALSE, nrow = NULL, ncol = NULL,\n lineend = \"butt\", linejoin = \"mitre\",\n na.rm = FALSE, show.legend = NA, inherit.aes = TRUE,\n direction = deprecated()) {\n assert_bool(byrow)\n assert_number_whole(nrow, min = 1, allow_null = TRUE)\n assert_number_whole(ncol, min = 1, allow_null = TRUE)\n if (lifecycle::is_present(direction)) {\n lifecycle::deprecate_warn(\n \"1.0.2\",\n \"geom_subtile(direction = )\",\n details = \"Please use the `nrow`/`ncol` argument instead.\"\n )\n if (is_horizontal(direction)) {\n nrow <- 1L\n ncol <- NULL\n } else {\n nrow <- NULL\n ncol <- 1L\n }\n }\n ggplot2::layer(\n data = data,\n mapping = mapping,\n stat = stat,\n geom = GeomSubrect,\n position = position,\n show.legend = show.legend,\n inherit.aes = inherit.aes,\n params = list2(\n byrow = byrow,\n nrow = nrow,\n ncol = ncol,\n lineend = lineend,\n linejoin = linejoin,\n na.rm = na.rm,\n ...\n )\n )\n}\n\n#' @importFrom ggplot2 ggproto ggproto_parent wrap_dims\nGeomSubrect <- ggproto(\n \"GeomSubrect\",\n ggplot2::GeomRect,\n extra_params = c(ggplot2::GeomRect$extra_params, \"byrow\", \"nrow\", \"ncol\"),\n setup_data = function(self, data, params) {\n data <- ggproto_parent(ggplot2::GeomRect, self)$setup_data(data, params)\n indices <- vec_group_loc(data[c(\"xmin\", \"xmax\", \"ymin\", \"ymax\")])\n data_list <- vec_chop(data, indices = .subset2(indices, \"loc\"))\n max_n_tiles <- max(list_sizes(data_list))\n if (max_n_tiles == 1L) return(data) # styler: off\n cli_inform(paste(\n \"{.fn {snake_class(self)}} subdivide tile into a maximal\",\n \"of {max_n_tiles} rectangles\"\n ))\n nrow <- .subset2(params, \"nrow\")\n ncol <- .subset2(params, \"ncol\")\n vec_rbind(!!!lapply(data_list, function(data) {\n n <- vec_size(data)\n if (n == 1L) return(data) # styler: off\n dims <- wrap_dims(n, nrow = nrow, ncol = ncol)\n n_rows <- dims[1L]\n n_cols <- dims[2L]\n one_row <- vec_slice(data, 1L)\n width <- (one_row$xmax - one_row$xmin) / n_cols\n height <- (one_row$ymax - one_row$ymin) / n_rows\n\n if (.subset2(params, \"byrow\")) {\n # we arrange the rectangles from from left to\n # right, then from top to bottom\n data$xmin <- data$xmin +\n vec_rep(width * (seq_len(n_cols) - 1L), n_rows)[\n seq_len(n)\n ]\n data$xmax <- data$xmax -\n vec_rep(width * rev(seq_len(n_cols) - 1L), n_rows)[\n seq_len(n)\n ]\n\n data$ymin <- data$ymin +\n vec_rep_each(height * rev(seq_len(n_rows) - 1L), n_cols)[\n seq_len(n)\n ]\n data$ymax <- data$ymax -\n vec_rep_each(height * (seq_len(n_rows) - 1L), n_cols)[\n seq_len(n)\n ]\n } else {\n # we arrange the rectangles from top to bottom,\n # then from left to right\n data$xmin <- data$xmin +\n vec_rep_each(width * (seq_len(n_cols) - 1L), n_rows)[\n seq_len(n)\n ]\n data$xmax <- data$xmax -\n vec_rep_each(width * rev(seq_len(n_cols) - 1L), n_rows)[\n seq_len(n)\n ]\n\n data$ymin <- data$ymin +\n vec_rep(height * rev(seq_len(n_rows) - 1L), n_cols)[\n seq_len(n)\n ]\n data$ymax <- data$ymax -\n vec_rep(height * (seq_len(n_rows) - 1L), n_cols)[\n seq_len(n)\n ]\n }\n\n data\n }))\n }\n)\n\n#' @aesthetics GeomSubtile\n#' @importFrom rlang list2\n#' @export\n#' @rdname geom_subrect\ngeom_subtile <- function(mapping = NULL, data = NULL,\n stat = \"identity\", position = \"identity\",\n ...,\n byrow = TRUE, nrow = NULL, ncol = NULL,\n lineend = \"butt\", linejoin = \"mitre\",\n na.rm = FALSE, show.legend = NA, inherit.aes = TRUE,\n direction = deprecated()) {\n assert_bool(byrow)\n assert_number_whole(nrow, min = 1, allow_null = TRUE)\n assert_number_whole(ncol, min = 1, allow_null = TRUE)\n if (lifecycle::is_present(direction)) {\n lifecycle::deprecate_warn(\n \"1.0.2\",\n \"geom_subtile(direction = )\",\n details = \"Please use the `nrow`/`ncol` argument instead.\"\n )\n if (is_horizontal(direction)) {\n nrow <- 1L\n ncol <- NULL\n } else {\n nrow <- NULL\n ncol <- 1L\n }\n }\n ggplot2::layer(\n data = data,\n mapping = mapping,\n stat = stat,\n geom = GeomSubtile,\n position = position,\n show.legend = show.legend,\n inherit.aes = inherit.aes,\n params = list2(\n byrow = byrow,\n nrow = nrow,\n ncol = ncol,\n lineend = lineend,\n linejoin = linejoin,\n na.rm = na.rm,\n ...\n )\n )\n}\n\n#' @importFrom ggplot2 ggproto ggproto_parent\nGeomSubtile <- ggproto(\n \"GeomSubtile\",\n ggplot2::GeomTile,\n extra_params = c(ggplot2::GeomRect$extra_params, \"byrow\", \"nrow\", \"ncol\"),\n setup_data = function(self, data, params) {\n data <- ggproto_parent(ggplot2::GeomTile, self)$setup_data(data, params)\n ggproto_parent(GeomSubrect, self)$setup_data(data, params)\n }\n)\n"], ["/ggalign/R/layout-chain-circle-switch.R", "#########################################################\n#' Determine the active context of circle layout\n#'\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' @inheritParams rlang::args_dots_empty\n#' @inheritParams circle_discrete\n#' @param what What should get activated for the [`circle_layout()`]?\n#' `r rd_chain_what()`.\n#' @return A `circle_switch` object which can be added to [`circle_layout()`].\n#' @examples\n#' set.seed(123)\n#' small_mat <- matrix(rnorm(56), nrow = 7)\n#' rownames(small_mat) <- paste0(\"row\", seq_len(nrow(small_mat)))\n#' colnames(small_mat) <- paste0(\"column\", seq_len(ncol(small_mat)))\n#' circle_discrete(small_mat) +\n#' ggalign() +\n#' geom_tile(aes(y = .column_index, fill = value)) +\n#' scale_fill_viridis_c() +\n#' align_dendro(aes(color = branch), k = 3L) +\n#' scale_color_brewer(palette = \"Dark2\")\n#' @export\ncircle_switch <- function(radial = waiver(), direction = NULL,\n what = waiver(), ...) {\n rlang::check_dots_empty()\n if (!is.waive(radial) && !is.null(radial)) {\n assert_s3_class(radial, \"CoordRadial\")\n if (abs(diff(radial$arc)) < pi / 2L) {\n cli_abort(\"Cannot use circle of acute angle < 90 in {.arg radial}\")\n }\n }\n if (!is.null(direction)) {\n direction <- arg_match0(direction, c(\"inward\", \"outward\"))\n }\n if (!is.waive(what)) what <- check_stack_context(what)\n structure(list(what = what, radial = radial, direction = direction),\n class = \"circle_switch\"\n )\n}\n"], ["/ggalign/R/ggplot-geom-draw.R", "#' Layer with Grid or Function\n#'\n#' Draw a ggplot2 layer using a grob or a function.\n#'\n#' @param draw Either a [grob][grid::grob] object or a function (can be\n#' purrr-style) that accepts at least one argument (a data frame of\n#' transformed coordinates) and returns a [grob][grid::grob].\n#'\n#' @param type A single string of `r oxford_or(c(\"group\", \"panel\"))`, `\"group\"`\n#' draws geoms with `draw_group`, which displays multiple observations as one\n#' geometric object, and `\"panel\"` draws geoms with `draw_panel`, displaying\n#' individual graphical objects for each observation (row). Default:\n#' `\"group\"`.\n#'\n#' @inheritParams ggplot2::layer\n#' @inheritParams ggplot2::geom_point\n#' @details If you want to combine the functionality of multiple geoms, it can\n#' typically be achieved by preparing the data for each geom inside the\n#' `draw_*()` call and sending it off to the different geoms, collecting the\n#' output in a [`grid::gList`] (a list of grobs) for `draw_group()` or a\n#' [`grid::gTree`] (a grob containing multiple child grobs) for\n#' `draw_panel()`.\n#' @seealso \n#' @examples\n#' text <- grid::textGrob(\n#' \"ggdraw\",\n#' x = c(0, 0, 0.5, 1, 1),\n#' y = c(0, 1, 0.5, 0, 1),\n#' hjust = c(0, 0, 0.5, 1, 1),\n#' vjust = c(0, 1, 0.5, 0, 1)\n#' )\n#' ggplot(data.frame(x = 1, y = 2)) +\n#' geom_draw(text)\n#' @importFrom rlang list2 arg_match0\n#' @importFrom ggplot2 ggproto aes\n#' @export\ngeom_draw <- function(draw, mapping = NULL, data = NULL,\n type = \"group\", stat = \"identity\",\n position = \"identity\", ...,\n na.rm = FALSE, show.legend = FALSE, inherit.aes = TRUE) {\n type <- arg_match0(type, c(\"group\", \"panel\"))\n if (!is.grob(draw) && !is.gList(draw)) draw <- rlang::as_function(draw)\n dots <- list2(...)\n ggplot2::layer(\n data = data,\n mapping = mapping,\n stat = stat,\n geom = switch(type,\n panel = ggproto(\n \"GeomDraw\",\n ggplot2::Geom,\n default_aes = GeomGshape$default_aes,\n setup_data = draw_setup_data,\n draw_panel = draw_geom_draw,\n draw_key = ggplot2::draw_key_blank\n ),\n group = ggproto(\n \"GeomDraw\",\n ggplot2::Geom,\n default_aes = GeomGshape$default_aes,\n setup_data = draw_setup_data,\n draw_group = draw_geom_draw,\n draw_key = ggplot2::draw_key_blank\n )\n ),\n position = position,\n show.legend = show.legend,\n inherit.aes = inherit.aes,\n params = c(\n list(na.rm = na.rm, draw = draw, .__draw_dots__ = dots), dots\n )\n )\n}\n\n# GeomTile will respect width and height\ndraw_setup_data <- function(self, data, params) {\n data$x <- data$x %||% 0.5\n data$y <- data$y %||% 0.5\n ggplot2::GeomTile$setup_data(data, params)\n}\n\ndraw_geom_draw <- function(data, panel_params, coord, draw, .__draw_dots__) {\n if (is.function(draw)) {\n data <- coord$transform(data, panel_params)\n # restore colour\n if (!is.null(data$colour) && is.null(data$color)) {\n data$color <- data$colour\n }\n if (!is.null(data$color) && is.null(data$colour)) {\n data$colour <- data$color\n }\n\n # restore width and height\n if (!is.null(data$xmin) && !is.null(data$xmax)) {\n data$width <- data$xmax - data$xmin\n }\n if (!is.null(data$ymin) && !is.null(data$ymax)) {\n data$height <- data$ymax - data$ymin\n }\n }\n make_draw_grob(draw, data, .__draw_dots__)\n}\n\n#' @return A [grob][grid::grob] object.\n#' @importFrom rlang inject\n#' @importFrom methods formalArgs\n#' @importFrom ggplot2 zeroGrob\n#' @keywords internal\n#' @noRd\nmake_draw_grob <- function(draw, data, dots) {\n if (is.function(draw)) {\n args <- formalArgs(draw)\n if (any(args == \"...\")) {\n draw <- inject(draw(!!!data, !!!dots))\n } else {\n draw <- inject(draw(\n !!!.subset(data, intersect(names(data), args)),\n !!!.subset(dots, intersect(\n setdiff(names(dots), names(data)), args\n ))\n ))\n }\n }\n ensure_grob(draw, zeroGrob())\n}\n"], ["/ggalign/R/ggplot-geom-gshape.R", "#' Layer with a customized shape graphic using grid functions.\n#'\n#' @description\n#' `r lifecycle::badge('questioning')`\n#'\n#' `geom_gshape` depends on the new aesthetics `gshape` (shape with grid\n#' functions), which should always be provided with [`scale_gshape_manual()`],\n#' in which, we can provide a list of grobs or functions that define how each\n#' value should be drawn. Any ggplot2 aesthetics can be used as the arguments.\n#'\n#' @inheritParams ggplot2::layer\n#' @inheritParams ggplot2::geom_point\n#' @section Life cycle:\n#' We're unsure whether this function is truly necessary, which is why it is\n#' marked as questioning. So far, we've found that [`geom_subrect()`] and\n#' [`geom_subtile()`] handle most use cases effectively.\n#'\n#' @aesthetics GeomGshape\n#' @examples\n#' library(grid)\n#' ggplot(data.frame(value = letters[seq_len(5)], y = seq_len(5))) +\n#' geom_gshape(aes(x = 1, y = y, gshape = value, fill = value)) +\n#' scale_gshape_manual(values = list(\n#' a = function(x, y, width, height, fill) {\n#' rectGrob(x, y,\n#' width = width, height = height,\n#' gp = gpar(fill = fill),\n#' default.units = \"native\"\n#' )\n#' },\n#' b = function(x, y, width, height, fill) {\n#' rectGrob(x, y,\n#' width = width, height = height,\n#' gp = gpar(fill = fill),\n#' default.units = \"native\"\n#' )\n#' },\n#' c = function(x, y, width, height, fill) {\n#' rectGrob(x, y,\n#' width = width, height = height,\n#' gp = gpar(fill = fill),\n#' default.units = \"native\"\n#' )\n#' },\n#' d = function(x, y, width, height, shape) {\n#' gList(\n#' pointsGrob(x, y, pch = shape),\n#' # To ensure the rectangle color is shown in the legends, you\n#' # must explicitly provide a color argument and include it in\n#' # the `gpar()` of the graphical object\n#' rectGrob(x, y, width, height,\n#' gp = gpar(col = \"black\", fill = NA)\n#' )\n#' )\n#' },\n#' e = function(xmin, xmax, ymin, ymax) {\n#' segmentsGrob(\n#' xmin, ymin,\n#' xmax, ymax,\n#' gp = gpar(lwd = 2)\n#' )\n#' }\n#' )) +\n#' scale_fill_brewer(palette = \"Dark2\") +\n#' theme_void()\n#'\n#' @importFrom rlang list2\n#' @export\ngeom_gshape <- function(mapping = NULL, data = NULL, stat = \"identity\",\n position = \"identity\", ..., na.rm = FALSE,\n show.legend = NA, inherit.aes = TRUE) {\n dots <- list2(...)\n ggplot2::layer(\n data = data,\n mapping = mapping,\n stat = stat,\n geom = GeomGshape,\n position = position,\n show.legend = show.legend,\n inherit.aes = inherit.aes,\n params = c(list(na.rm = na.rm), dots, list(.__gshape_dots__ = dots))\n )\n}\n\n#' @inherit ggplot2::draw_key_point\n#' @description\n#' Each geom has an associated function that draws the key when the geom needs\n#' to be displayed in a legend. These functions are called `draw_key_*()`, where\n#' `*` stands for the name of the respective key glyph. The key glyphs can be\n#' customized for individual geoms by providing a geom with the `key_glyph`\n#' argument. The `draw_key_gshape` function provides this interface for custom\n#' key glyphs used with [`geom_gshape()`].\n#'\n#' @importFrom rlang inject\n#' @importFrom methods formalArgs\n#' @importFrom grid gTree\n#' @export\ndraw_key_gshape <- function(data, params, size) {\n gshape <- .subset2(data$gshape, 1L)\n data$gshape <- NULL\n if (is.function(gshape)) {\n for (d in formalArgs(gshape)) {\n if (is.null(.subset2(data, d))) {\n data[[d]] <- switch(d,\n x = ,\n y = 0.5,\n xmin = ,\n ymin = 0,\n xmax = ,\n ymax = 1,\n width = ,\n height = 1,\n color = data$colour %||% GeomGshape$default_aes[[\"colour\"]],\n fill = data$colour %||% GeomGshape$default_aes[[\"fill\"]],\n GeomGshape$default_aes[[d]]\n )\n }\n }\n }\n make_draw_grob(gshape, data, .subset2(params, \".__gshape_dots__\"))\n}\n\n#' @importFrom ggplot2 ggproto zeroGrob\n#' @importFrom rlang inject\n#' @importFrom grid gList\nGeomGshape <- ggproto(\n \"GeomGshape\",\n ggplot2::Geom,\n required_aes = c(\"x\", \"y\", \"gshape\"),\n default_aes = aes(\n shape = 19,\n colour = \"black\",\n size = 1.5,\n fill = NA,\n alpha = NA,\n stroke = 0.5,\n linewidth = 0.5,\n linetype = 1\n ),\n setup_data = ggplot2::GeomTile$setup_data,\n draw_panel = function(data, panel_params, coord, .__gshape_dots__) {\n coords <- coord$transform(data, panel_params)\n\n if (!is.null(coords$colour) && is.null(coords$color)) {\n coords$color <- coords$colour\n }\n if (!is.null(coords$color) && is.null(coords$colour)) {\n coords$colour <- coords$color\n }\n\n # restore width and height\n if (!is.null(coords$xmin) && !is.null(coords$xmax)) {\n coords$width <- coords$xmax - coords$xmin\n }\n if (!is.null(coords$ymin) && !is.null(coords$ymax)) {\n coords$height <- coords$ymax - coords$ymin\n }\n\n groups <- vec_group_loc(.subset2(coords, \"gshape\"))\n coords$gshape <- NULL\n\n # reordering by drawing order\n ordering <- vapply(\n .subset2(groups, \"key\"),\n function(gshape) {\n attr(gshape, \"gshape_ordering\", exact = TRUE) %||% NA_integer_\n },\n integer(1L),\n USE.NAMES = FALSE\n )\n groups <- vec_slice(groups, order(ordering))\n coords <- vec_chop(coords, indices = .subset2(groups, \"loc\"))\n\n grobs <- .mapply(\n make_draw_grob,\n list(draw = .subset2(groups, \"key\"), data = coords),\n list(dots = .__gshape_dots__)\n )\n grobs <- grobs[vapply(grobs, is.grob, logical(1L), USE.NAMES = FALSE)]\n if (is_empty(grobs)) {\n zeroGrob()\n } else {\n gTree(children = inject(gList(!!!grobs)))\n }\n },\n draw_key = draw_key_gshape\n)\n\n#' Scale for `gshape` aesthetic\n#'\n#' @inheritDotParams ggplot2::discrete_scale -expand -position -aesthetics -palette -scale_name\n#' @param values A list of grobs or functions (including purrr-like lambda\n#' syntax) that define how each cell's grob (graphical object) should be drawn.\n#' @inheritParams ggplot2::scale_discrete_manual\n#' @inherit geom_gshape\n#' @export\nscale_gshape_manual <- function(..., values, breaks = waiver(), na.value = NA) {\n ggplot2::scale_discrete_manual(\n aesthetics = \"gshape\",\n values = .mapply(function(f, i) {\n f <- allow_lambda(f)\n attr(f, \"gshape_ordering\") <- i # save the drawing order\n f\n }, list(values, seq_along(values)), NULL),\n breaks = breaks,\n na.value = na.value,\n ...\n )\n}\n\n# `gshape` should be provided manually\nscale_gshape_discrete <- function(name = waiver(), ...) {\n cli_abort(paste(\n \"You must provide {.fn scale_gshape_manual}\",\n \"to use {.field draw} aesthetic\"\n ))\n}\n\n# `gshape` should be provided manually\nscale_gshape_continuous <- scale_gshape_discrete\n"], ["/ggalign/R/layout-chain-stack-composer.R", "#' @keywords internal\nstack_composer <- function(direction) {\n structure(\n list(\n t = integer(), l = integer(),\n b = integer(), r = integer(),\n plots = list(), sizes = list(),\n direction = direction,\n align = 1L,\n # attributes used by `stack_layout()`\n left_or_top = FALSE, right_or_bottom = FALSE\n ),\n class = \"stack_composer\"\n )\n}\n\nstack_composer_add_plot <- function(composer, plot, t, l, b = t, r = l) {\n composer$t <- c(.subset2(composer, \"t\"), t)\n composer$l <- c(.subset2(composer, \"l\"), l)\n composer$b <- c(.subset2(composer, \"b\"), b)\n composer$r <- c(.subset2(composer, \"r\"), r)\n composer$plots <- c(.subset2(composer, \"plots\"), list(plot))\n composer\n}\n\n#' @importFrom rlang is_empty\nstack_composer_align_plot <- function(composer, plot, size) {\n if (is.null(plot)) {\n return(composer)\n }\n if (is_horizontal(.subset2(composer, \"direction\"))) {\n r_border <- .subset2(composer, \"r\")\n if (is_empty(r_border)) {\n l <- 1L\n } else {\n l <- max(r_border) + 1L\n }\n t <- .subset2(composer, \"align\")\n } else {\n b_border <- .subset2(composer, \"b\")\n if (is_empty(b_border)) {\n t <- 1L\n } else {\n t <- max(b_border) + 1L\n }\n l <- .subset2(composer, \"align\")\n }\n composer$sizes <- c(.subset2(composer, \"sizes\"), list(size))\n stack_composer_add_plot(composer, plot, t, l)\n}\n\nstack_composer_add <- function(plot, stack, composer, ...) {\n UseMethod(\"stack_composer_add\")\n}\n\n#' @importFrom utils packageVersion\n#' @export\nstack_composer_add.CraftBox <- function(plot, stack, composer, design, ...,\n schemes, theme,\n released_spaces,\n direction, position) {\n size <- plot@size\n\n # for `released_spaces`, release the `free_spaces` in a single plot\n plot_schemes <- inherit_schemes(plot@schemes, schemes)\n if (!is.null(released_spaces)) {\n plot_spaces <- .subset2(\n .subset2(plot_schemes, \"scheme_align\"), \"free_spaces\"\n )\n if (is_string(plot_spaces)) {\n plot_spaces <- setdiff_position(plot_spaces, released_spaces)\n if (!nzchar(plot_spaces)) plot_spaces <- NULL\n plot_schemes$scheme_align[\"free_spaces\"] <- list(plot_spaces)\n }\n }\n\n # let `Align` to determine how to build the plot\n craftsman <- plot@craftsman # `Craftsman` object\n plot <- plot@plot\n if (!craftsman$free_facet && is_discrete_design(design)) {\n if (nlevels(.subset2(design, \"panel\")) > 1L) {\n if (is_horizontal(direction)) {\n facet <- ggplot2::facet_grid(\n rows = ggplot2::vars(.data$.panel),\n scales = \"free_y\", space = \"free\",\n drop = FALSE, as.table = FALSE\n )\n free_row <- FALSE\n free_column <- TRUE\n } else {\n facet <- ggplot2::facet_grid(\n cols = ggplot2::vars(.data$.panel),\n scales = \"free_x\", space = \"free\",\n drop = FALSE, as.table = FALSE\n )\n free_row <- TRUE\n free_column <- FALSE\n }\n } else {\n facet <- facet_stack(direction, craftsman$layout_name)\n }\n plot <- ggmelt_facet(plot, facet,\n free_row = free_row, free_column = free_column\n )\n }\n if (!craftsman$free_coord) {\n plot <- gguse_linear_coord(plot, layout_name = craftsman$layout_name)\n }\n\n # set limits and default scales\n if (!craftsman$free_limits) {\n if (is_horizontal(direction)) {\n plot <- plot + ggalign_design(\n y = design,\n ylabels = .subset(craftsman$labels, .subset2(design, \"index\"))\n )\n } else {\n plot <- plot + ggalign_design(\n x = design,\n xlabels = .subset(craftsman$labels, .subset2(design, \"index\"))\n )\n }\n }\n\n # let `Craftsman` add other components\n plot <- craftsman$build_plot(plot, design = design, ...)\n plot <- craftsman$finish_plot(plot, plot_schemes, theme)\n\n # Let layout finally modify the plot\n plot <- chain_decorate(stack, plot)\n\n # add the plot to the composer\n stack_composer_align_plot(composer, plot, size)\n}\n\n#' @importFrom grid unit.c unit\nstack_composer_add.QuadLayout <- function(plot, stack, composer, schemes, theme,\n direction, ...) {\n patches <- quad_build(plot, schemes, theme, direction)\n plots <- .subset2(patches, \"plots\")\n sizes <- .subset2(patches, \"sizes\")\n\n if (is_horizontal(.subset2(composer, \"direction\"))) {\n composer$left_or_top <- .subset2(composer, \"left_or_top\") ||\n !is.null(.subset2(plots, \"top\"))\n composer$right_or_bottom <- .subset2(composer, \"right_or_bottom\") ||\n !is.null(.subset2(plots, \"bottom\"))\n composer <- stack_composer_align_plot(\n composer,\n .subset2(plots, \"left\"),\n .subset2(sizes, \"left\")\n )\n composer <- stack_composer_align_plot(\n composer,\n .subset2(plots, \"main\"),\n .subset2(.subset2(sizes, \"main\"), \"width\")\n )\n l <- max(.subset2(composer, \"r\"))\n if (!is.null(top <- .subset2(plots, \"top\"))) {\n if (.subset2(composer, \"align\") == 1L) {\n composer$t <- .subset2(composer, \"t\") + 1L\n composer$b <- .subset2(composer, \"b\") + 1L\n composer$align <- .subset2(composer, \"align\") + 1L\n }\n if (!is_null_unit(size <- .subset2(sizes, \"top\"))) {\n attr(top, \"vp\")$height <- size\n }\n composer <- stack_composer_add_plot(composer, top, t = 1L, l = l)\n }\n if (!is.null(bottom <- .subset2(plots, \"bottom\"))) {\n if (!is_null_unit(size <- .subset2(sizes, \"bottom\"))) {\n attr(bottom, \"vp\")$height <- size\n }\n composer <- stack_composer_add_plot(composer, bottom,\n t = .subset2(composer, \"align\") + 1L, l = l\n )\n }\n composer <- stack_composer_align_plot(\n composer,\n .subset2(plots, \"right\"),\n .subset2(sizes, \"right\")\n )\n } else {\n composer$left_or_top <- .subset2(composer, \"left_or_top\") ||\n !is.null(.subset2(plots, \"left\"))\n composer$right_or_bottom <- .subset2(composer, \"right_or_bottom\") ||\n !is.null(.subset2(plots, \"right\"))\n composer <- stack_composer_align_plot(\n composer,\n .subset2(plots, \"top\"),\n .subset2(sizes, \"top\")\n )\n composer <- stack_composer_align_plot(\n composer,\n .subset2(plots, \"main\"),\n .subset2(.subset2(sizes, \"main\"), \"height\")\n )\n t <- max(.subset2(composer, \"b\"))\n if (!is.null(left <- .subset2(plots, \"left\"))) {\n if (.subset2(composer, \"align\") == 1L) {\n composer$l <- .subset2(composer, \"l\") + 1L\n composer$r <- .subset2(composer, \"r\") + 1L\n composer$align <- .subset2(composer, \"align\") + 1L\n }\n if (!is_null_unit(size <- .subset2(sizes, \"left\"))) {\n attr(left, \"vp\")$width <- size\n }\n composer <- stack_composer_add_plot(composer, left, t = t, l = 1L)\n }\n if (!is.null(right <- .subset2(plots, \"right\"))) {\n if (!is_null_unit(size <- .subset2(sizes, \"right\"))) {\n attr(right, \"vp\")$width <- size\n }\n composer <- stack_composer_add_plot(composer, right,\n t = t, l = .subset2(composer, \"align\") + 1L\n )\n }\n composer <- stack_composer_align_plot(\n composer,\n .subset2(plots, \"bottom\"),\n .subset2(sizes, \"bottom\")\n )\n }\n composer\n}\n\n#' @export\nstack_composer_add.list <- function(plot, stack, composer, ...) {\n for (p in plot) {\n composer <- stack_composer_add(\n plot = p, stack = stack, composer = composer, ...\n )\n }\n composer\n}\n"], ["/ggalign/R/layout-chain-stack-cross.R", "#' Arrange plots crosswise horizontally or vertically\n#'\n#' @description\n#' `r lifecycle::badge('experimental')`\n#'\n#' The `stack_cross` function is derived from [`stack_discrete()`] and allows\n#' for different layout ordering indices within a single layout.\n#'\n#' Two aliases are provided for convenience:\n#' - `stack_crossv`: A special case of `stack_cross` that sets\n#' `direction = \"v\"` for vertical alignment.\n#' - `stack_crossh`: A special case of `stack_cross` that sets\n#' `direction = \"h\"` for horizontal alignment.\n#'\n#' @param data `r rd_layout_data()`, [`fortify_matrix()`] will be used to\n#' convert the data to a matrix.\n#' @param ... Additional arguments passed to [`fortify_matrix()`].\n#' @inheritParams stack_layout\n#' @seealso [`ggcross()`]\n#' @export\nstack_cross <- function(direction, data = NULL, ...,\n theme = NULL, sizes = NA) {\n UseMethod(\"stack_cross\", data)\n}\n\n#' @export\n#' @rdname stack_cross\nstack_crossv <- function(data = NULL, ...) {\n stack_cross(data = data, direction = \"v\", ...)\n}\n\n#' @export\n#' @rdname stack_cross\nstack_crossh <- function(data = NULL, ...) {\n stack_cross(data = data, direction = \"h\", ...)\n}\n\n#' @include layout-chain-stack-.R\nmethods::setClass(\n \"StackCross\",\n contains = \"StackLayout\",\n # A list of old design\n list(odesign = \"list\", cross_points = \"integer\", break_points = \"integer\"),\n prototype = list(\n odesign = list(),\n cross_points = integer(),\n break_points = integer()\n )\n)\n\n#' @export\nstack_cross.default <- function(direction, data = NULL, ...) {\n ans <- stack_discrete(data = data, direction = direction, ...)\n ans <- methods::as(ans, \"StackCross\")\n ans@name <- \"stack_cross\"\n ans\n}\n\n#' @importFrom grid unit.c\n#' @importFrom rlang is_empty is_string\nresolve_stack_layout.StackCross <- function(stack, schemes, theme,\n extra_design) {\n # check if we should initialize the layout observations\n layout_design <- stack@design\n if (is_discrete_design(layout_design) &&\n is.null(.subset2(layout_design, \"nobs\")) &&\n any(vapply(plot_list, is_cross_plot, logical(1L), USE.NAMES = FALSE))) {\n cli_abort(sprintf(\n \"You must initialize the layout observations to plot the %s\",\n object_name(stack)\n ))\n }\n plot_list <- stack@plot_list\n\n direction <- stack@direction\n position <- .subset2(stack@heatmap, \"position\")\n plot_list <- vec_chop(\n plot_list,\n sizes = diff(c(0L, stack@cross_points, length(plot_list)))\n )\n design_list <- c(stack@odesign, list(layout_design))\n\n # build the stack\n composer <- stack_composer(direction)\n\n # for `free_spaces`, if we have applied it in the whole stack layout we\n # shouln't use it for a single plot. Otherwise, the guide legends collected\n # by the layout will overlap with the axis of the plot in the layout.\n #\n # this occurs in the annotation stack (`position` is not `NULL`).\n stack_spaces <- .subset2(.subset2(schemes, \"scheme_align\"), \"free_spaces\")\n if (is_string(stack_spaces) && !is.null(position)) {\n released_spaces <- stack_spaces\n } else {\n released_spaces <- NULL\n }\n previous_design <- NULL\n for (i in seq_along(plot_list)) {\n plots <- .subset2(plot_list, i)\n\n # prepare design for current group\n design <- .subset2(design_list, i)\n design <- setup_design(design)\n\n if (is_empty(plots)) {\n previous_design <- design\n next\n }\n\n # we remove the plot without actual plot area\n keep <- vapply(plots, function(plot) {\n # we remove objects without plot area\n # Now, only `CraftBox` will contain `NULL`\n !is_craftbox(plot) || !is.null(plot@plot)\n }, logical(1L), USE.NAMES = FALSE)\n plots <- .subset(plots, keep)\n\n if (is_empty(plots)) {\n previous_design <- design\n next\n }\n\n # we reorder the plots based on the `order` slot\n plot_order <- vapply(plots, function(plot) {\n # always keep cross() in the start\n if (is_cross_plot(plot)) {\n 1L\n } else if (is_craftbox(plot)) {\n .subset2(plot@active, \"order\")\n } else {\n .subset2(plot@plot_active, \"order\")\n }\n }, integer(1L), USE.NAMES = FALSE)\n plots <- .subset(plots, make_order(plot_order))\n composer <- stack_composer_add(\n plots,\n stack = stack,\n composer,\n schemes = schemes,\n theme = theme,\n design = design,\n extra_design = extra_design,\n direction = direction,\n position = position,\n released_spaces = released_spaces,\n previous_design = previous_design\n )\n previous_design <- design\n }\n composer\n}\n"], ["/ggalign/R/scheme-align.R", "#' Align Specifications in the Layout\n#'\n#' @description\n#' `r lifecycle::badge('experimental')`\n#'\n#' The `scheme_align()` function defines the align Specifications for plots.\n#'\n#' @param guides A string with one or more of `r oxford_and(c(.tlbr, \"i\"))`\n#' indicating which side of guide legends should be collected. Defaults to\n#' [`waiver()`][ggplot2::waiver()], which inherits from the parent layout. If no\n#' parent layout, all guides will be collected. If `NULL`, no guides will be\n#' collected.\n#'\n#' @param free_spaces A string with one or more of `r oxford_and(.tlbr)`\n#' indicating which border spaces should be removed. Defaults to\n#' [`waiver()`][ggplot2::waiver()], which inherits from the parent layout. If no\n#' parent, the default is `NULL`, meaning no spaces are removed.\n#'\n#' Usually you want to apply this with the whole layout, instead of individual\n#' plots.\n#'\n#' @param free_labs A string with one or more of `r oxford_and(.tlbr)`\n#' indicating which axis titles should be free from alignment. Defaults to\n#' [`waiver()`][ggplot2::waiver()], which inherits from the parent layout. If no\n#' parent layout, no axis titles will be aligned. If `NULL`, all axis titles\n#' will be aligned.\n#'\n#' @return A `scheme_align` object.\n#' @examples\n#' set.seed(123)\n#' mat <- matrix(rnorm(72), nrow = 8)\n#' # used in the layout, define the default action for all plots in the layout\n#' ggheatmap(mat) -\n#' scheme_align(guides = NULL) +\n#' anno_right() +\n#' align_dendro(aes(color = branch), k = 3)\n#'\n#' # You can also add it for a single plot\n#' ggheatmap(mat) -\n#' # for all plots in the layout, we default won't collect any guide legends\n#' scheme_align(guides = NULL) +\n#' # for the heatmap body, we collect guide legends in the right\n#' # note, the guide legends will be collected to the right side of the\n#' # layout which will overlap the legends in the right annotation\n#' scheme_align(guides = \"r\") +\n#' anno_right() +\n#' align_dendro(aes(color = branch), k = 3)\n#'\n#' # to avoid overlapping, we can also collect the guide legends in the\n#' # right annotation\n#' ggheatmap(mat) -\n#' scheme_align(guides = NULL) +\n#' scheme_align(guides = \"r\") +\n#' anno_right() +\n#' align_dendro(aes(color = branch), k = 3) +\n#' scheme_align(guides = \"r\")\n#' @export\nscheme_align <- function(guides = NA, free_spaces = NA, free_labs = NA) {\n if (!identical(guides, NA)) assert_layout_guides(guides)\n if (!identical(free_spaces, NA)) assert_layout_position(free_spaces)\n if (!identical(free_labs, NA)) assert_layout_position(free_labs)\n new_scheme_align(\n free_spaces = free_spaces,\n free_labs = free_labs,\n guides = guides\n )\n}\n\nnew_scheme_align <- function(guides = waiver(), free_spaces = waiver(),\n free_labs = waiver()) {\n new_scheme(\n name = \"scheme_align\",\n list(free_spaces = free_spaces, free_labs = free_labs, guides = guides),\n class = \"scheme_align\"\n )\n}\n\n#' @importFrom utils modifyList\n#' @export\nupdate_scheme.scheme_align <- function(new, old, object_name) {\n modifyList(old,\n new[!vapply(new, identical, logical(1L), y = NA, USE.NAMES = FALSE)],\n keep.null = TRUE\n )\n}\n\n#' @export\ninherit_scheme.scheme_align <- function(scheme, pscheme) {\n # `align_plots` control how to inherit `guides` from the layout\n # we don't need to inherit it here\n scheme[\"free_spaces\"] <- list(.subset2(scheme, \"free_spaces\") %|w|%\n .subset2(pscheme, \"free_spaces\"))\n scheme[\"free_labs\"] <- list(.subset2(scheme, \"free_labs\") %|w|%\n .subset2(pscheme, \"free_labs\"))\n scheme\n}\n\n#' @param theme Additional default theme elements to be added for the plot\n#' @noRd\nplot_add_scheme.scheme_align <- function(plot, scheme) {\n if (!is.waive(free_guides <- .subset2(scheme, \"guides\"))) {\n plot <- free_guide(plot, free_guides)\n }\n # by default, we'll attach all labs to the axis\n if (!is.null(free_labs <- .subset2(scheme, \"free_labs\") %|w|% \"tlbr\")) {\n plot <- free_lab(plot, free_labs)\n }\n # by default, we won't remove any spaces\n if (!is.null(free_spaces <- .subset2(scheme, \"free_spaces\") %|w|% NULL)) {\n plot <- free_space(free_border(plot, free_spaces), free_spaces)\n }\n plot\n}\n"], ["/ggalign/R/layout-quad-upset.R", "#' Create an UpSet plot\n#'\n#' @description\n#' `r lifecycle::badge('experimental')`\n#'\n#' `ggupset` is a specialized version of [`quad_discrete()`], which simplifies\n#' the creation of Upset plot.\n#'\n#' @param data Data used to create the UpSet plot. [`fortify_matrix()`] will be\n#' used to convert the data to a matrix. Currently, only\n#' [`fortify_matrix.list_upset`] and [`fortify_matrix.matrix_upset`] are\n#' suitable for creating an UpSet plot.\n#' @param ... Additional arguments passed to [`fortify_matrix()`].\n#' @inheritParams quad_layout\n#' @param direction A string indicating the direction of the UpSet plot,\n#' `\"h\"`(`horizontal`) or `\"v\"`(`vertical`). In a vertical UpSet plot, the\n#' columns of the matrix correspond to the sets, and the rows correspond to the\n#' intersections. By default, the horizontal UpSet plot is used, where the rows\n#' of the matrix correspond to the sets and the columns correspond to the\n#' intersections.\n#' @param point A list of parameters passed to\n#' [`geom_point()`][ggplot2::geom_point()].\n#' @param line A list of parameters passed to\n#' [`geom_line()`][ggplot2::geom_line()].\n#' @param rect A list of parameters passed to\n#' [`geom_rect()`][ggplot2::geom_rect()].\n#'\n#' @inheritSection heatmap_layout ggplot2 specification\n#' @examples\n#' set.seed(123)\n#' lt <- list(\n#' a = sample(letters, 5),\n#' b = sample(letters, 10),\n#' c = sample(letters, 15)\n#' )\n#' ggupset(tune(lt)) +\n#' scale_fill_manual(values = c(\"#F0F0F0\", \"white\"), guide = \"none\") +\n#' scale_color_manual(values = c(\"grey\", \"black\"), guide = \"none\") +\n#' anno_top() +\n#' ggalign(data = function(d) ggalign_attr(d, \"intersection_sizes\")) +\n#' ggplot2::geom_bar(aes(y = .data$value), stat = \"identity\") +\n#' anno_right() +\n#' ggalign(data = function(d) ggalign_attr(d, \"set_sizes\")) +\n#' ggplot2::geom_bar(aes(x = .data$value),\n#' stat = \"identity\",\n#' orientation = \"y\"\n#' )\n#' @importFrom ggplot2 aes\n#' @export\nggupset <- function(data = NULL, mapping = aes(),\n ...,\n direction = \"h\",\n point = NULL, line = NULL, rect = NULL,\n width = NA, height = NA,\n theme = NULL, active = NULL) {\n UseMethod(\"ggupset\")\n}\n\n# Don't allow inherit from the parent layout, since data for upset plot is\n# usually different with others\n#' @export\nggupset.NULL <- function(data, ...) {\n cli_abort(\"{.arg data} must be provided to create upset plot\")\n}\n\n#' @export\nggupset.waiver <- ggupset.NULL\n\n#' @importFrom ggplot2 aes\n#' @export\nggupset.default <- function(data = NULL, mapping = aes(),\n ...,\n direction = \"h\",\n point = NULL, line = NULL, rect = NULL,\n width = NA, height = NA,\n theme = NULL, active = NULL) {\n direction <- check_direction(direction)\n # we need a matrix to melted into long formated data frame\n data <- fortify_matrix(data = data, ...)\n if (is_vertical(direction)) data <- ggalign_data_restore(t(data), data)\n ans <- new_quad_layout(\n name = \"ggupset\",\n data = data,\n mapping = mapping,\n theme = theme,\n active = active\n )\n ans@plot <- ggadd_default(ans@plot, mapping = aes(.data$.x, .data$.y)) +\n ggplot2::labs(x = NULL, y = NULL) +\n upset_rect(direction, rect) +\n upset_point(point) +\n upset_line(direction, line)\n ans\n}\n\nmerge_mapping <- function(x, y) {\n if (is.null(x)) {\n return(y)\n }\n for (i in names(y)) {\n x[[i]] <- .subset2(y, i)\n }\n x\n}\n\nmerge_data_fn <- function(plot_data, user_data) {\n if (is.null(user_data) || is.waive(user_data)) {\n plot_data\n } else if (is.function(user_data <- allow_lambda(user_data))) {\n force(plot_data)\n function(data) user_data(plot_data(data))\n } else {\n user_data\n }\n}\n\nupset_rect <- function(direction, rect) {\n if (is_horizontal(direction)) {\n rect$mapping <- merge_mapping(rect$mapping, aes(\n ymin = .data$.ymin, ymax = .data$.ymax, fill = .data$rect_group\n ))\n rect$data <- merge_data_fn(function(data) {\n column <- c(\n \".y\", \".panel_x\", \".panel_y\",\n \".row_index\", \".row_names\", \".discrete_y\"\n )\n o <- vec_unique(data[vec_set_intersect(column, names(data))])\n o$rect_group <- (.subset2(o, \".y\") %% 2L) == 0L\n o$.ymin <- o$.y - 0.5\n o$.ymax <- o$.y + 0.5\n o\n }, rect$data)\n inject(ggplot2::geom_rect(!!!rect,\n xmin = -Inf, xmax = Inf, inherit.aes = FALSE\n ))\n } else {\n rect$mapping <- merge_mapping(rect$mapping, aes(\n xmin = .data$.xmin, xmax = .data$.xmax,\n fill = .data$rect_group\n ))\n rect$data <- merge_data_fn(function(data) {\n column <- c(\n \".x\", \".panel_x\", \".panel_y\",\n \".column_index\", \".column_names\", \".discrete_x\"\n )\n o <- vec_unique(data[vec_set_intersect(column, names(data))])\n o$rect_group <- (.subset2(o, \".x\") %% 2L) == 0L\n o$.xmin <- o$.x - 0.5\n o$.xmax <- o$.x + 0.5\n o\n }, rect$data)\n inject(ggplot2::geom_rect(!!!rect,\n ymin = -Inf, ymax = Inf, inherit.aes = FALSE\n ))\n }\n}\n\nupset_point <- function(point) {\n point$mapping <- merge_mapping(point$mapping, aes(\n x = .data$.x, y = .data$.y, color = .data$point_group\n ))\n point$data <- merge_data_fn(function(data) {\n data$point_group <- .subset2(data, \"value\")\n data\n }, point$data)\n inject(ggplot2::geom_point(!!!point, inherit.aes = FALSE))\n}\n\nupset_line <- function(direction, line) {\n line$mapping <- merge_mapping(line$mapping, switch_direction(\n direction,\n aes(.data$.x, .data$.y, group = paste(.data$.panel_x, .data$.x)),\n aes(.data$.x, .data$.y, group = paste(.data$.panel_y, .data$.y))\n ))\n line$data <- merge_data_fn(function(data) {\n if (is_horizontal(direction)) {\n dlist <- vec_split(data, data[c(\".panel_x\", \".x\")])\n dlist <- lapply(.subset2(dlist, \"val\"), function(d) {\n o <- vec_slice(d, .subset2(d, \"value\"))\n if (vec_size(o) < 2L) {\n return(NULL)\n }\n vec_slice(o, c(\n which.min(.subset2(o, \".y\")),\n which.max(.subset2(o, \".y\"))\n ))\n })\n vec_rbind(!!!dlist)\n } else {\n dlist <- vec_split(data, data[c(\".panel_y\", \".y\")])\n dlist <- lapply(.subset2(dlist, \"val\"), function(d) {\n o <- vec_slice(d, .subset2(d, \"value\"))\n if (vec_size(o) < 2L) {\n return(NULL)\n }\n vec_slice(o, c(\n which.min(.subset2(o, \".x\")),\n which.max(.subset2(o, \".x\"))\n ))\n })\n vec_rbind(!!!dlist)\n }\n }, line$data)\n inject(ggplot2::geom_line(!!!line, inherit.aes = FALSE))\n}\n"], ["/ggalign/R/grid-grob-magick.R", "#' Rasterize a grob object with magick\n#'\n#' @param grob A [`grob()`][grid::grob]. Use [`patch()`] to convert any objects\n#' into a `grob`.\n#' @param magick A function (purrr-style formula is accepted) that takes an\n#' [`image_read()`][magick::image_read] object as input and returns an object\n#' compatible with [`as.raster()`][grDevices::as.raster]. You can use any of\n#' the `image_*()` functions from the **magick** package to process the raster\n#' image.\n#' @param res An integer sets the desired resolution in pixels.\n#' @inheritParams rlang::args_dots_empty\n#' @inheritParams grid::rasterGrob\n#' @return A `magickGrob` object.\n#' @export\nmagickGrob <- function(grob, magick = NULL, ...,\n res = NULL, interpolate = FALSE,\n name = NULL, vp = NULL) {\n rlang::check_installed(\"magick\", \"to use `magickGrob()`\")\n if (!is.null(magick) && !is.function(magick <- allow_lambda(magick))) {\n cli_abort(\"{.arg magick} must be a function\")\n }\n assert_number_whole(res, min = 1, allow_null = TRUE)\n assert_bool(interpolate)\n magickGrob0(\n grob = grob, magick = magick, ..., res = res,\n interpolate = interpolate, name = name, vp = vp\n )\n}\n\nmagickGrob0 <- function(grob, ...) UseMethod(\"magickGrob0\")\n\n#' @importFrom grid gTree\n#' @export\nmagickGrob0.grob <- function(grob, magick = NULL, ...,\n res = NULL, interpolate = FALSE,\n name = NULL, vp = NULL) {\n rlang::check_dots_empty()\n gTree(\n grob = grob, magick = magick, res = res,\n interpolate = interpolate, name = name, vp = vp,\n cl = \"magickGrob\"\n )\n}\n\n#' @importFrom grid gTree\n#' @export\nmagickGrob0.gList <- function(grob, ...) {\n magickGrob0(grob = gTree(children = grob), ...)\n}\n\n#' @importFrom grid editGrob\n#' @importFrom rlang inject\n#' @export\nmagickGrob0.magickGrob <- function(grob, magick = waiver(), ...,\n res = waiver(), interpolate = waiver(),\n name = waiver(), vp = waiver()) {\n rlang::check_dots_empty()\n params <- list(\n magick = magick, res = res,\n interpolate = interpolate, name = name, vp = vp\n )\n params <- params[!vapply(params, is.waive, logical(1L), USE.NAMES = FALSE)]\n inject(editGrob(grob, !!!params))\n}\n\n#' @export\nmagickGrob0.default <- function(grob, ...) {\n cli_abort(\"{.arg grob} must be a {.cls grob} object\")\n}\n\n# preDraw:\n# - makeContext\n# - pushvpgp\n# - preDrawDetails: by default, do noting\n# makeContent:\n# drawDetails:\n# postDraw:\n# - postDrawDetails: by default, do noting\n# - popgrobvp\n#' @importFrom grid makeContent unit convertHeight convertWidth viewport gList\n#' @export\nmakeContent.magickGrob <- function(x) {\n # Grab viewport information\n width <- convertWidth(unit(1, \"npc\"), \"pt\", valueOnly = TRUE)\n height <- convertHeight(unit(1, \"npc\"), \"pt\", valueOnly = TRUE)\n\n # Grab grob metadata\n plot_res <- convertWidth(unit(1, \"inch\"), \"pt\", valueOnly = TRUE)\n res <- .subset2(x, \"res\") %||% plot_res\n\n magick <- .subset2(x, \"magick\")\n interpolate <- .subset2(x, \"interpolate\")\n\n # Track current device\n old_dev <- grDevices::dev.cur()\n\n # Reset current device upon function exit\n on.exit(grDevices::dev.set(old_dev), add = TRUE)\n\n # open the magick raster device\n image <- magick::image_graph(\n width = width * res / plot_res,\n height = height * res / plot_res,\n bg = NA_character_, res = res,\n clip = FALSE, antialias = FALSE\n )\n\n # Render the grob\n grid::pushViewport(viewport())\n\n # Clean up the grob for rendering\n grid::grid.draw(.subset2(x, \"grob\")) # should respect the viewport of `x`\n grid::popViewport()\n grDevices::dev.off()\n on.exit(magick::image_destroy(image), add = TRUE)\n\n # run `magick` when necessary\n if (!is.null(magick)) image <- magick(image)\n\n # Use native raster instead\n raster <- grDevices::as.raster(image, native = TRUE)\n\n # Forward raster grob\n setChildren(x, children = gList(\n grid::rasterGrob(\n raster, # should contain current area of full viewport\n x = 0.5, y = 0.5,\n height = unit(height, \"pt\"),\n width = unit(width, \"pt\"),\n default.units = \"npc\",\n just = \"center\",\n interpolate = interpolate\n )\n ))\n}\n"], ["/ggalign/R/alignpatch-free-align.R", "#' Free from alignment\n#'\n#' [align_plots] will try to align plot panels, and every elements of the plot,\n#' following functions romove these restrictions:\n#' - `free_align`: if we want to compose plots without alignment of some panel\n#' axes (panel won't be aligned). we can wrap the plot with `free_align`.\n#' - `free_border`: attaches borders (e.g., axis titles, tick marks) directly to\n#' the plot panel. This keeps them visually close to the panel during\n#' alignment.\n#' - `free_lab()`: Similar to `free_border()`, but only attaches axis titles\n#' and tick labels, not full borders. It’s mainly included for completeness;\n#' in most cases, combining `free_border()` and `free_space()` is sufficient.\n#' - `free_space`: Removing the ggplot element sizes when aligning.\n#' - `free_vp`: Customize the [viewport][grid::viewport] when aligning.\n#' - `free_guide`: If we want to override the behaviour of the overall guides\n#' behaviour, we can wrap the plot with `free_guide`.\n#'\n#' @param plot A [ggplot][ggplot2::ggplot] or [alignpatches][align_plots]\n#' object.\n#' @param axes Which axes shouldn't be aligned? A string containing\n#' one or more of `r oxford_and(.tlbr)`.\n#' @return\n#' - `free_align`: A modified version of `plot` with a `free_align` class.\n#' @examples\n#' # directly copied from `patchwork`\n#' # Sometimes you have a plot that defies good composition alginment, e.g. due\n#' # to long axis labels\n#' p1 <- ggplot(mtcars) +\n#' geom_bar(aes(y = factor(gear), fill = factor(gear))) +\n#' scale_y_discrete(\n#' \"\",\n#' labels = c(\n#' \"3 gears are often enough\",\n#' \"But, you know, 4 is a nice number\",\n#' \"I would def go with 5 gears in a modern car\"\n#' )\n#' )\n#'\n#' # When combined with other plots it ends up looking bad\n#' p2 <- ggplot(mtcars) +\n#' geom_point(aes(mpg, disp))\n#'\n#' align_plots(p1, p2, ncol = 1L)\n#'\n#' # We can fix this be using `free_align`\n#' align_plots(free_align(p1), p2, ncol = 1L)\n#'\n#' # If we still want the panels to be aligned to the right, we can choose to\n#' # free only the left side\n#' align_plots(free_align(p1, axes = \"l\"), p2, ncol = 1L)\n#'\n#' # We could use `free_lab` to fix the layout in a different way\n#' align_plots(p1, free_lab(p2), ncol = 1L)\n#'\n#' # `free_border` is similar with `free_lab`, they have a distinction in terms\n#' # of placement on either the top or bottom side of the panel. Specifically,\n#' # the top side contains the `title` and `subtitle`, while the bottom side\n#' # contains the `caption`. free_lab() does not attach these elements in the\n#' # panel area.\n#' p3 <- ggplot(mtcars) +\n#' geom_point(aes(hp, wt, colour = mpg)) +\n#' ggtitle(\"Plot 3\")\n#' p_axis_top <- ggplot(mtcars) +\n#' geom_point(aes(mpg, disp)) +\n#' ggtitle(\"Plot axis in top\") +\n#' scale_x_continuous(position = \"top\")\n#' align_plots(p_axis_top, free_lab(p3))\n#' align_plots(p_axis_top, free_border(p3))\n#'\n#' # Another issue is that long labels can occupy much spaces\n#' align_plots(NULL, p1, p2, p2)\n#'\n#' # This can be fixed with `free_space`\n#' align_plots(NULL, free_space(p1, \"l\"), p2, p2)\n#'\n#' @export\n#' @rdname free\nfree_align <- function(plot, axes = \"tlbr\") {\n UseMethod(\"free_align\")\n}\n\n# free_guides: set_guides\n# free_lab: collect_guides\n# free_border: collect_guides and align_border\n# free_space: get_sizes\n# free_align: get_sizes and align_border\n# free_vp: align_border\n\n#' @export\nfree_align.ggplot <- function(plot, axes = \"tlbr\") {\n assert_position(axes)\n attr(plot, \"free_axes\") <- axes\n add_class(plot, \"free_align\")\n}\n\n#' @export\nfree_align.alignpatches <- free_align.ggplot\n\n#' @importFrom rlang is_empty\n#' @export\nfree_align.free_lab <- function(plot, axes = \"tlbr\") {\n assert_position(axes)\n # if axes are free, it's not necessary to free the labs\n free_labs <- setdiff_position(attr(plot, \"free_labs\"), axes)\n if (nzchar(free_labs)) {\n attr(plot, \"free_labs\") <- free_labs\n } else {\n attr(plot, \"free_labs\") <- NULL\n plot <- remove_class(plot, \"free_lab\")\n }\n NextMethod()\n}\n\n#' @importFrom rlang is_empty\n#' @export\nfree_align.free_space <- function(plot, axes = \"tlbr\") {\n assert_position(axes)\n free_spaces <- setdiff_position(attr(plot, \"free_spaces\"), axes)\n if (nzchar(free_spaces)) {\n attr(plot, \"free_spaces\") <- free_spaces\n } else {\n attr(plot, \"free_spaces\") <- NULL\n plot <- remove_class(plot, \"free_space\")\n }\n NextMethod()\n}\n\n#' @importFrom rlang is_empty\n#' @export\nfree_align.free_border <- function(plot, axes = \"tlbr\") {\n assert_position(axes)\n free_borders <- setdiff_position(attr(plot, \"free_borders\"), axes)\n if (nzchar(free_borders)) {\n attr(plot, \"free_borders\") <- free_borders\n } else {\n attr(plot, \"free_borders\") <- NULL\n plot <- remove_class(plot, \"free_border\")\n }\n NextMethod()\n}\n\n#' @export\nfree_align.free_align <- function(plot, axes = \"tlbr\") {\n assert_position(axes)\n attr(plot, \"free_axes\") <- union_position(attr(plot, \"free_axes\"), axes)\n plot\n}\n\n#' @export\nfree_align.default <- function(plot, axes = \"tlbr\") {\n cli_abort(\"Cannot use with {.obj_type_friendly {plot}}\")\n}\n\n#' @importFrom ggplot2 ggproto ggproto_parent\n#' @export\nalignpatch.free_align <- function(x) {\n Parent <- NextMethod()\n ggproto(\n \"PatchFreeAlign\", Parent,\n free_axes = split_position(attr(x, \"free_axes\")),\n get_sizes = function(self, free = NULL, gt = self$gt) {\n ggproto_parent(Parent, self)$get_sizes(\n union(free, self$free_axes),\n gt = gt\n )\n },\n align_border = function(self, t = NULL, l = NULL, b = NULL, r = NULL,\n gt = self$gt) {\n for (axis in self$free_axes) {\n assign(x = axis, value = NULL, envir = environment())\n }\n ggproto_parent(Parent, self)$align_border(\n t = t, l = l, b = b, r = r, gt = gt\n )\n }\n )\n}\n"], ["/ggalign/R/attributes.R", "#' Get Data from the Attribute Attached by ggalign\n#'\n#' @description\n#' `ggalign_attr` retrieves supplementary information stored as attributes\n#' during the layout rendering process. These attributes—typically added during\n#' data transformation by functions such as [`fortify_matrix()`] or\n#' [`fortify_data_frame()`]—may contain filtered data, auxiliary metadata, or\n#' other context essential for downstream operations.\n#'\n#' Factor level information, stored as a separate attribute, can be accessed via\n#' `ggalign_lvls`.\n#'\n#' @details\n#' Attributes attached to the data are especially useful when the input data is\n#' transformed in ways that limit access to the complete dataset. For example,\n#' [`fortify_matrix.MAF()`] might filter mutation data while adding attributes\n#' that retain important context, such as the total number of observations, for\n#' detailed or aggregated analyses. Additionally, it stores the levels of\n#' `Variant_Classification` for further usage.\n#'\n#' @param x Data used, typically inherited from the layout `r rd_layout()`.\n#' @param field A string specifying the particular data to retrieve from the\n#' attached attribute. If `NULL`, the entire attached attribute list will be\n#' returned.\n#' @param check A boolean indicating whether to check if the `field` exists. If\n#' `TRUE`, an error will be raised if the specified `field` does not exist.\n#' @return\n#' - `ggalign_attr`: The specified data from the attached supplementary data or\n#' `NULL` if it is unavailable.\n#' - `ggalign_lvls`: The attached supplementary levels or `NULL` if it is\n#' unavailable.\n#'\n#' @export\nggalign_attr <- function(x, field = NULL, check = TRUE) {\n assert_string(field, allow_empty = FALSE, allow_null = TRUE)\n if (is.null(x <- ggalign_attr_get(x)) || is.null(field)) {\n return(x)\n }\n if (isTRUE(check) && !rlang::has_name(x, field)) {\n cli_abort(\"Cannot find {field} in {.arg x}\")\n }\n .subset2(x, field)\n}\n\n#' @export\n#' @rdname ggalign_attr\nggalign_lvls <- function(x) ggalign_lvls_get(x)\n\n#' Attach supplementary data and levels for ggalign\n#'\n#' @param .data Input data for the layout.\n#' @param ... <[dyn-dots][rlang::dyn-dots]> A list of data to be attached.\n#' @param .lvls A character vector representing the attached levels.\n#' @note Used by developers in [`fortify_matrix()`], [`fortify_data_frame()`],\n#' and other related methods.\n#' @seealso [`ggalign_attr()`]/[`ggalign_lvls()`]\n#' @importFrom rlang list2\n#' @export\nggalign_data_set <- function(.data, ..., .lvls = NULL) {\n if (...length() > 0L) {\n .data <- ggalign_attr_set(.data, list2(...))\n }\n if (!is.null(.lvls)) {\n .data <- ggalign_lvls_set(.data, .lvls)\n }\n # to prevent the print of attributes\n if (!is.null(ggalign_attr_get(.data)) ||\n !is.null(ggalign_lvls_get(.data))) {\n .data <- add_class(.data, \"ggalign_data\")\n }\n .data\n}\n\n#' @export\nprint.ggalign_data <- function(x, ...) {\n print(\n remove_class(\n ggalign_lvls_remove(ggalign_attr_remove(x)),\n \"ggalign_data\"\n )\n )\n invisible(x)\n}\n\nggalign_attr_set <- function(x, values) {\n attr(x, \".__ggalign_attr__\") <- values\n x\n}\n\nggalign_attr_get <- function(x) attr(x, \".__ggalign_attr__\", exact = TRUE)\n\nggalign_attr_remove <- function(x) ggalign_attr_set(x, NULL)\n\nggalign_lvls_set <- function(x, lvls) {\n attr(x, \".__ggalign_levels__\") <- lvls\n x\n}\n\nggalign_lvls_get <- function(x) attr(x, \".__ggalign_levels__\", exact = TRUE)\n\nggalign_lvls_remove <- function(x) ggalign_lvls_set(x, NULL)\n\n# we keep a special attribute across all data\n# this is used to pass additional annotation informations\nggalign_data_restore <- function(data, original) {\n if (is.null(data) || is.waive(data)) return(data) # styler: off\n if (is.null(ggalign_attr_get(data)) && # no attached attribute\n # the original has attached attribute\n !is.null(value <- ggalign_attr_get(original))) {\n data <- ggalign_attr_set(data, value)\n }\n\n if (is.null(ggalign_lvls_get(data)) && # no attached levels\n # the original has attached levels\n !is.null(value <- ggalign_lvls_get(original))) {\n data <- ggalign_lvls_set(data, value)\n }\n # to prevent the print of attributes\n if (!is.null(ggalign_attr_get(data)) ||\n !is.null(ggalign_lvls_get(data))) {\n data <- add_class(data, \"ggalign_data\")\n }\n data\n}\n"], ["/ggalign/R/craft-align-group.R", "#' Group and align observations based on a group vector\n#'\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' Splits observations into groups, with slice ordering based on group levels.\n#'\n#' @param group A character define the groups of the observations.\n#' @inheritParams align\n#' @examples\n#' set.seed(1L)\n#' small_mat <- matrix(rnorm(81), nrow = 9)\n#' ggheatmap(small_mat) +\n#' anno_top() +\n#' align_group(sample(letters[1:4], ncol(small_mat), replace = TRUE))\n#' @export\nalign_group <- function(group, active = NULL) {\n assert_active(active)\n if (vec_size(group) == 0L) {\n cli_abort(\"{.arg group} cannot be empty\")\n }\n active <- update_active(active, new_active(use = FALSE))\n align(\n align = AlignGroup,\n group = group,\n active = active,\n check.param = TRUE\n )\n}\n\n#' @importFrom ggplot2 ggproto\nAlignGroup <- ggproto(\"AlignGroup\", CraftAlign,\n interact_layout = function(self, layout) {\n layout <- ggproto_parent(CraftAlign, self)$interact_layout(layout)\n if (is.null(layout_nobs <- .subset2(layout@design, \"nobs\"))) {\n layout@design[\"nobs\"] <- list(vec_size(self$group))\n } else {\n assert_mismatch_nobs(\n self, layout_nobs, vec_size(self$group),\n arg = \"group\"\n )\n }\n layout\n },\n align = function(self, panel, index) list(self$group, index),\n summary_align = function(self) c(FALSE, TRUE)\n)\n"], ["/ggalign/R/layout-.R", "# Will ensure serialisation includes a link to the ggalign namespace\n# Copied from patchwork\nnamespace_link <- function() NULL\n\n# https://stackoverflow.com/questions/65817557/s3-methods-extending-ggplot2-gg-function\n# Here we use S4 object to override the double dispatch of `+.gg` method\n# TO-DO: use S7\n#' A `Layout` object\n#'\n#' A `Layout` object defines how to place the plots.\n#'\n#' @keywords internal\n# add suffix \"Proto\" to avoid conflict with ggplot2\nmethods::setClass(\"LayoutProto\",\n list(\n active = \"ANY\", # current active plot\n schemes = \"list\", # used to provide global parameters for all plots\n # control the layout, `theme` will also be used by `ggsave`\n titles = \"list\",\n annotation = \"list\", # To-Do add `pacth_titles` for layout\n theme = \"ANY\",\n `_namespace` = \"ANY\"\n ),\n prototype = list(\n active = NULL, titles = list(),\n annotation = list(), theme = NULL,\n `_namespace` = namespace_link\n )\n)\n\n#' @export\nprint.LayoutProto <- print.alignpatches\n\n#' @importFrom grid grid.draw\n#' @exportS3Method\ngrid.draw.LayoutProto <- grid.draw.alignpatches\n\n#' @export\nalignpatch.LayoutProto <- function(x) alignpatch(ggalign_build(x))\n\n#' Print Layout object\n#'\n#' @param object A `r rd_layout()`.\n#' @return The input invisiblely.\n#' @importFrom methods show\n#' @export\n#' @keywords internal\nmethods::setMethod(\"show\", \"LayoutProto\", function(object) {\n print(object)\n})\n\n#' Subset a `Layout` object\n#'\n#' Used by [`ggplot_build`][ggplot2::ggplot_build] and\n#' [`ggsave`][ggplot2::ggsave]\n#'\n#' @param x A `Layout` object\n#' @param name A string of slot name in `Layout` object.\n#' @return The slot value.\n#' @importFrom methods slot\n#' @export\n#' @keywords internal\nmethods::setMethod(\"$\", \"LayoutProto\", function(x, name) {\n slot(x, name)\n})\n\n###########################################################\ndefault_layout <- function(layout) { # setup default value for the layout\n layout@theme <- complete_theme(default_theme() + layout@theme)\n\n # we by default, collect all guides\n layout@schemes$scheme_align[\"guides\"] <- list(\n .subset2(.subset2(layout@schemes, \"scheme_align\"), \"guides\") %|w|% \"tlbr\"\n )\n\n # we by default, use `default_theme()`\n layout@schemes$scheme_theme <- update_scheme(\n .subset2(layout@schemes, \"scheme_theme\"),\n new_scheme_theme(complete_theme(default_theme()))\n )\n layout\n}\n\nis_linear <- function(layout) UseMethod(\"is_linear\")\n\n#' @export\nis_linear.StackLayout <- function(layout) TRUE\n\n#' @export\nis_linear.CircleLayout <- function(layout) FALSE\n\n###########################################################\ninherit_parent_layout_schemes <- function(layout, schemes) {\n if (is.null(schemes)) {\n return(layout@schemes)\n }\n inherit_schemes(layout@schemes, schemes)\n}\n\ninherit_parent_layout_theme <- function(layout, theme, spacing = NULL) {\n if (is.null(theme)) return(layout@theme) # styler: off\n # parent theme, set the global panel spacing,\n # so that every panel aligns well\n if (is.null(layout@theme)) return(theme) # styler: off\n ans <- theme + layout@theme\n if (is.null(spacing)) return(ans) # styler: off\n switch(spacing,\n x = ans + theme(\n panel.spacing.x = calc_element(\"panel.spacing.x\", theme)\n ),\n y = ans + theme(\n panel.spacing.y = calc_element(\"panel.spacing.y\", theme)\n )\n )\n}\n\n############################################################\n#' Get the statistics from the layout\n#'\n#' @param x A `r rd_layout()`.\n#' @inheritParams rlang::args_dots_used\n#' @return The statistics\n#' @export\nggalign_stat <- function(x, ...) {\n UseMethod(\"ggalign_stat\")\n}\n\n#' @param position A string of `r oxford_or(.TLBR)`.\n#' @export\n#' @rdname ggalign_stat\nggalign_stat.QuadLayout <- function(x, position, ...) {\n ggalign_stat(x = slot(x, position), ...)\n}\n\n#' @param what A single number or string of the plot elements in the stack\n#' layout.\n#' @export\n#' @rdname ggalign_stat\nggalign_stat.StackLayout <- function(x, what, ...) {\n plot_list <- x@plot_list\n index <- vec_as_location2(\n what,\n n = length(plot_list),\n names = names(plot_list),\n missing = \"error\"\n )\n ggalign_stat(x = .subset2(plot_list, index), ...)\n}\n\n#' @export\nggalign_stat.CraftBox <- function(x, ...) {\n ggalign_stat(x@craftsman, ...)\n}\n\n#' @export\nggalign_stat.CraftAlign <- function(x, ...) {\n rlang::check_dots_empty()\n .subset2(x, \"statistics\")\n}\n\n#' @export\nggalign_stat.default <- function(x, ...) {\n cli_abort(sprintf(\"no statistics found for %s\", object_name(x)))\n}\n\n#############################################################\n#' Reports whether `x` is layout object\n#'\n#' @param x An object to test.\n#' @return A single boolean value.\n#' @examples\n#' is_layout(ggheatmap(1:10))\n#'\n#' @importFrom methods is\n#' @export\nis_layout <- function(x) is(x, \"LayoutProto\")\n\n#' @examples\n#' # for quad_layout()\n#' is_quad_layout(quad_alignb(1:10))\n#' is_quad_layout(quad_alignh(1:10))\n#' is_quad_layout(quad_alignv(1:10))\n#' is_quad_layout(quad_free(mtcars))\n#'\n#' @export\n#' @rdname is_layout\nis_quad_layout <- function(x) is(x, \"QuadLayout\")\n\n#' @examples\n#' # for stack_layout()\n#' is_stack_layout(stack_discrete(\"h\", 1:10))\n#' is_stack_layout(stack_continuous(\"h\", 1:10))\n#'\n#' @export\n#' @rdname is_layout\nis_stack_layout <- function(x) is(x, \"StackLayout\")\n\n#' @export\n#' @rdname is_layout\nis_stack_cross <- function(x) is(x, \"StackCross\")\n\n#' @export\n#' @rdname is_layout\nis_circle_layout <- function(x) is(x, \"CircleLayout\")\n\n#' @examples\n#' # for heatmap_layout()\n#' is_heatmap_layout(ggheatmap(1:10))\n#' @export\n#' @rdname is_layout\nis_heatmap_layout <- function(x) is(x, \"HeatmapLayout\")\n\n#' @examples\n#' is_ggheatmap(ggheatmap(1:10))\n#' @export\n#' @rdname is_layout\nis_ggheatmap <- is_heatmap_layout\n\nis_cross_layout <- function(x) is_stack_cross(x)\n"], ["/ggalign/R/layer-order.R", "#' Change the layer adding order\n#'\n#' @description\n#' This function allows you to change the order in which layers are added to a\n#' ggplot.\n#'\n#' @param layer A [`layer geometry`][ggplot2::layer_geoms] object to be added.\n#' @param order An integer indicating the position at which the layer should be\n#' added. If `<= 0`, the layer will be added at the beginning. If greater than\n#' the number of plot layers, it will be added at the end.\n#' @return A `layer_order` object.\n#' @examples\n#' ggplot(faithfuld, aes(waiting, eruptions)) +\n#' geom_raster(aes(fill = density)) +\n#' geom_point(color = \"red\", size = 1)\n#' ggplot(faithfuld, aes(waiting, eruptions)) +\n#' geom_raster(aes(fill = density)) +\n#' layer_order(geom_point(color = \"red\", size = 1))\n#' @export\nlayer_order <- function(layer, order = 0) {\n assert_number_decimal(order)\n UseMethod(\"layer_order\")\n}\n\n#' @export\nlayer_order.default <- function(layer, order = 0) {\n cli_abort(\"{.arg layer} must be a {.fn geom_*} object\")\n}\n\n#' @export\nlayer_order.Layer <- function(layer, order = 0) {\n if (!is.infinite(order)) order <- vec_cast(order, integer())\n structure(\n list(\n object = layer,\n order = order,\n # used for `ggplot_add`\n object_name = paste(deparse(substitute(layer)), collapse = \" \")\n ),\n class = \"ggalign_layer_order\"\n )\n}\n\n#' @export\nlayer_order.ggalign_layer_order <- function(layer, order = 0) {\n if (!is.infinite(order)) order <- vec_cast(order, integer())\n layer$order <- order\n layer\n}\n\n#' @importFrom ggplot2 ggplot_add\n#' @export\nggplot_add.ggalign_layer_order <- function(object, plot, object_name, ...) {\n # ggplot2 will do something special for the layer\n # add layer_name, we re-call the method for the layer\n ans <- ggplot_add(\n .subset2(object, \"object\"),\n plot, .subset2(object, \"object_name\")\n )\n if ((cur <- length(layers <- ans$layers)) == 1L) {\n return(ans)\n }\n order <- .subset2(object, \"order\")\n layer <- .subset2(layers, cur)\n if (order >= length(layers)) return(ans) # styler: off\n if (order <= 0L) {\n layers <- append(vec_slice(layers, -cur), layer, 0L)\n } else {\n layers <- append(vec_slice(layers, -cur), layer, order)\n }\n ans$layers <- layers\n ans\n}\n"], ["/ggalign/R/ggplot-theme.R", "#' @importFrom ggplot2 theme_bw element_blank\ndefault_theme <- function() {\n if (is_theme_unset()) {\n theme_bw() +\n theme(\n axis.text = ggplot2::element_text(color = \"black\"),\n strip.text = ggplot2::element_text(color = \"black\"),\n panel.border = element_blank(),\n panel.grid = element_blank()\n )\n } else {\n theme_get()\n }\n}\n\n# Check if user has set the theme\nis_theme_unset <- function() {\n isTRUE(all.equal(\n complete_theme(ggfun(\"ggplot_global\")$theme_default),\n complete_theme(theme_get())\n ))\n}\n\nis_theme_complete <- function(x) isTRUE(attr(x, \"complete\", exact = TRUE))\n\n#' @importFrom ggplot2 rel element_blank\ntheme_no_strip <- function() {\n theme(\n strip.text = element_blank(),\n strip.background = element_blank()\n )\n}\n\ntheme_panel_border <- function() theme(panel.border = element_rect(fill = NA))\n\n#' @importFrom utils packageVersion\n#' @importFrom rlang try_fetch\ncomplete_theme <- function(theme) {\n if (packageVersion(\"ggplot2\") > \"3.5.2\") {\n ggfun(\"complete_theme\")(theme)\n } else {\n ggfun(\"plot_theme\")(list(theme = theme))\n }\n}\n\n#' @importFrom ggplot2 register_theme_elements el_def element_line\ntheme_elements <- function() {\n register_theme_elements(\n ggalign.line = element_line(\n color = \"black\",\n linewidth = 0.5,\n linetype = 1,\n lineend = \"butt\",\n linejoin = \"round\"\n ),\n ggalign.polygon = element_polygon(\n fill = NA,\n color = \"black\",\n linewidth = 0.5,\n linetype = 1,\n alpha = NA,\n lineend = \"butt\",\n linejoin = \"round\",\n linemitre = 10\n ),\n element_tree = list(\n plot.patch_title = el_def(\"element_text\", \"text\"),\n plot.patch_title.top = el_def(\"element_text\", \"text\"),\n plot.patch_title.left = el_def(\"element_text\", \"text\"),\n plot.patch_title.bottom = el_def(\"element_text\", \"text\"),\n plot.patch_title.right = el_def(\"element_text\", \"text\"),\n plot.patch_title.position = el_def(\"character\"),\n plot.patch_title.position.top = el_def(\"character\"),\n plot.patch_title.position.left = el_def(\"character\"),\n plot.patch_title.position.bottom = el_def(\"character\"),\n plot.patch_title.position.right = el_def(\"character\"),\n panel.spacing.r = el_def(c(\"unit\", \"rel\"), \"panel.spacing\"),\n ggalign.line = el_def(\"element_line\"),\n ggalign.curve = el_def(\"element_curve\"),\n ggalign.polygon = el_def(\"element_polygon\")\n )\n )\n}\n\n#' Used to match theme\n#'\n#' @keywords internal\n#' @noRd\ntheme_recycle <- function() structure(list(), class = \"theme_recycle\")\n\n#' @importFrom ggplot2 ggplot_add ggproto ggproto_parent\n#' @export\nggplot_add.theme_recycle <- function(object, plot, object_name, ...) {\n ParentFacet <- plot$facet\n if (!inherits(ParentFacet, c(\"FacetGrid\", \"FacetWrap\"))) {\n return(plot)\n }\n # recycle axis theme elements\n plot$facet <- ggproto(\n NULL, ParentFacet,\n draw_panels = function(self, panels, layout,\n x_scales = NULL, y_scales = NULL,\n ranges, coord, data = NULL, theme, params) {\n # we recycle the theme elements of the guide axis\n theme <- recycle_theme_axis(\"x\", theme, x_scales)\n theme <- recycle_theme_axis(\"y\", theme, y_scales)\n ParentCoord <- coord\n h_tick0 <- h_text0 <- 0L\n v_tick0 <- v_text0 <- 0L\n # subset theme for each panel\n coord <- ggproto(NULL, ParentCoord,\n # `align_scales` will attach the `.__plot_index__`\n render_axis_h = function(self, panel_params, theme) {\n scale <- (.subset2(panel_params, \"x\") %||%\n .subset2(panel_params, \"theta\")\n )$scale\n h_tick1 <- h_tick0 + length(scale$get_breaks())\n h_text1 <- h_text0 + length(scale$get_labels())\n theme <- subset_theme_axis(\n \"x\", theme, h_tick0, h_text0, h_tick1, h_text1\n )\n h_tick0 <<- h_tick1\n h_text0 <<- h_text1\n ggproto_parent(ParentCoord, self)$render_axis_h(\n panel_params, theme\n )\n },\n render_axis_v = function(self, panel_params, theme) {\n scale <- (.subset2(panel_params, \"y\") %||%\n .subset2(panel_params, \"r\")\n )$scale\n v_tick1 <- v_tick0 + length(scale$get_breaks())\n v_text1 <- v_text0 + length(scale$get_labels())\n theme <- subset_theme_axis(\n \"y\", theme, v_tick0, v_text0, v_tick1, v_text1\n )\n v_tick0 <<- v_tick1\n v_text0 <<- v_text1\n ggproto_parent(ParentCoord, self)$render_axis_v(\n panel_params, theme\n )\n }\n )\n ggproto_parent(ParentFacet, self)$draw_panels(\n panels = panels, layout = layout,\n x_scales = x_scales, y_scales = y_scales,\n ranges = ranges, coord = coord, data = data,\n theme = theme, params = params\n )\n }\n )\n plot\n}\n\n#################################################################\n# Apply a function to the vectorized field of the theme object\ntheme_vec <- function(.th, .el, .fn, ...) {\n element <- calc_element(.el, .th)\n if (inherits(element, \"element\")) {\n .th[[.el]] <- element_vec(element, .fn, ...)\n } else if (!is.null(element)) {\n .th[[.el]] <- .fn(element, ...)\n }\n .th\n}\n\nrecycle_theme_axis <- function(axis, theme, scales) {\n breaks <- unlist(lapply(scales, function(s) s$get_breaks()), FALSE, FALSE)\n labels <- unlist(lapply(scales, function(x) x$get_labels()), FALSE, FALSE)\n align_theme_axis(axis, theme,\n tick_fn = function(v, arg) rep(v, length.out = length(breaks)),\n text_fn = function(v, arg) rep(v, length.out = length(labels))\n )\n}\n\nsubset_theme_axis <- function(axis, theme, tick0, text0, tick1, text1) {\n tick_index <- (tick0 + 1L):tick1\n text_index <- (text0 + 1L):text1\n align_theme_axis(\n axis, theme,\n tick_fn = function(value) vec_slice(value, tick_index),\n text_fn = function(value) vec_slice(value, text_index)\n )\n}\n\nalign_theme_axis <- function(axis, theme, text_fn, tick_fn) {\n if (axis == \"y\") {\n positions <- c(\"left\", \"right\")\n } else {\n positions <- c(\"top\", \"bottom\")\n }\n # only apply the function when the element values is not a scalar\n .text_fn <- function(v) if (length(v) > 1L) text_fn(v) else v\n .tick_fn <- function(v) if (length(v) > 1L) tick_fn(v) else v\n for (element in paste(\"axis.text\", axis, positions, sep = \".\")) {\n theme <- theme_vec(theme, element, .text_fn)\n }\n for (element in paste(\"axis.ticks\", axis, positions, sep = \".\")) {\n theme <- theme_vec(theme, element, .tick_fn)\n }\n for (element in paste(\"axis.ticks.length\", axis, positions, sep = \".\")) {\n theme <- theme_vec(theme, element, .tick_fn)\n }\n theme\n}\n"], ["/ggalign/R/import-standalone-tibble.R", "# Standalone file: do not edit by hand\n# Source: https://github.com/Yunuuuu/standalone/blob/HEAD/R/standalone-tibble.R\n# Generated by: usethis::use_standalone(\"Yunuuuu/standalone\", \"tibble\")\n# ----------------------------------------------------------------------\n#\n# ---\n# repo: Yunuuuu/standalone\n# file: standalone-tibble.R\n# last-updated: 2024-11-14\n# license: https://unlicense.org\n# imports: [vctrs (>= 0.5.0), rlang]\n# ---\n\n# when developing R package, instead of depending on `dplyr`, `tidyr`, `tibble`.\n# we prefer use the basic function from `vctrs`\n#\n# Note: these functions won't check arguments\n#\n# Since `vctrs` also depends on `rlang` and `cli`, it has no harm to use\n# function from `rlang` and `cli`.\n#\n# Please initialize the package docs and import vctrs\n# 1. run `usethis::use_package_doc()`\n# 2. in package docs, please add #' @import vctrs\n\n# ## Changelog\n# 2025-03-12\n# - Added `case_when()`\n#\n# 2024-11-14\n# - Added `column_to_rownames()`\n#\n# 2024-11-13\n# - fix wrong results in `coalesce()`: we should assign value in the missing\n# index\n#\n# 2024-11-12\n# - Added `rename`\n# - coalesce() now will return value immediately when no missing value exists.\n#\n# 2024-11-11:\n# - Added `inner_join`\n# - Added `left_join`\n# - Added `right_join`\n# - Added `cross_join`\n# - Added `replace_na`\n# - Added `coalesce`\n# - Added `deframe`\n# - Added `enframe`\n# - Added `remove_rownames`\n# - Added `rownames_to_column`\n#\n# 2024-11-10:\n# - Added `full_join`\n# - Added `if_else`\n#\n# nocov start\n\n#' @importFrom rlang set_names\nfull_join <- function(\n x,\n y,\n by = vec_set_intersect(names(x), names(y)),\n by.x = by,\n by.y = by,\n suffix = c(\".x\", \".y\")\n) {\n loc <- vec_locate_matches(x[by.x], set_names(y[by.y], by.x), remaining = NA)\n x_slicer <- .subset2(loc, \"needles\")\n y_slicer <- .subset2(loc, \"haystack\")\n ans <- join_bind(\n vec_slice(x, x_slicer),\n # drop duplicated join column\n vec_slice(y[vec_set_difference(names(y), by.y)], y_slicer),\n suffix = suffix\n )\n new_rows <- which(vec_detect_missing(x_slicer)) # should come from `y`\n if (length(new_rows)) {\n ans[new_rows, by.x] <- vec_slice(y[by.y], y_slicer[new_rows])\n }\n ans\n}\n\n#' @importFrom rlang set_names\ninner_join <- function(\n x,\n y,\n by = vec_set_intersect(names(x), names(y)),\n by.x = by,\n by.y = by,\n suffix = c(\".x\", \".y\")\n) {\n loc <- vec_locate_matches(\n x[by.x],\n set_names(y[by.y], by.x),\n no_match = \"drop\"\n )\n x_slicer <- .subset2(loc, \"needles\")\n y_slicer <- .subset2(loc, \"haystack\")\n join_bind(\n vec_slice(x, x_slicer),\n # drop duplicated join column\n vec_slice(y[vec_set_difference(names(y), by.y)], y_slicer),\n suffix = suffix\n )\n}\n\n#' @importFrom rlang set_names\nleft_join <- function(\n x,\n y,\n by = vec_set_intersect(names(x), names(y)),\n by.x = by,\n by.y = by,\n suffix = c(\".x\", \".y\")\n) {\n loc <- vec_locate_matches(x[by.x], set_names(y[by.y], by.x))\n x_slicer <- .subset2(loc, \"needles\")\n y_slicer <- .subset2(loc, \"haystack\") # can have NA value\n join_bind(\n vec_slice(x, x_slicer),\n # drop duplicated join column\n vec_slice(y[vec_set_difference(names(y), by.y)], y_slicer),\n suffix = suffix\n )\n}\n\n#' @importFrom rlang set_names\nright_join <- function(\n x,\n y,\n by = vec_set_intersect(names(x), names(y)),\n by.x = by,\n by.y = by,\n suffix = c(\".x\", \".y\")\n) {\n loc <- vec_locate_matches(\n x[by.x],\n set_names(y[by.y], by.x),\n no_match = \"drop\",\n remaining = NA\n )\n x_slicer <- .subset2(loc, \"needles\") # can have NA value\n y_slicer <- .subset2(loc, \"haystack\")\n join_bind(\n # drop duplicated join column\n vec_slice(x[vec_set_difference(names(x), by.x)], x_slicer),\n vec_slice(y, y_slicer),\n suffix = suffix\n )\n}\n\ncross_join <- function(x, y, suffix = c(\".x\", \".y\")) {\n x_size <- vec_size(x)\n y_size <- vec_size(y)\n x_out <- vec_rep_each(x, times = y_size)\n y_out <- vec_rep(y, times = x_size)\n join_bind(x_out, y_out, suffix)\n}\n\njoin_bind <- function(x, y, suffix) {\n x_names <- names(x)\n y_names <- names(y)\n common <- vec_set_intersect(x_names, y_names)\n if (length(common)) {\n # add suffix to duplicated names\n index <- vec_match(common, x_names)\n names(x)[index] <- paste0(x_names[index], .subset(suffix, 1L))\n index <- vec_match(common, y_names)\n names(y)[index] <- paste0(y_names[index], .subset(suffix, 2L))\n }\n vec_cbind(x, y, .name_repair = \"check_unique\")\n}\n\n#' Rename elements in a list, data.frame or vector\n#'\n#' This is akin to `dplyr::rename` and `plyr::rename`. It renames elements given\n#' as names in the `replace` vector to the values in the `replace` vector\n#' without touching elements not referenced.\n#'\n#' @param x A data.frame or a named vector or list\n#' @param replace A named character vector. The names identifies the elements in\n#' `x` that should be renamed and the values gives the new names.\n#'\n#' @return `x`, with new names according to `replace`\n#' @noRd\nrename <- function(x, replace) {\n nms <- names(x)\n names(x) <- vec_assign(nms, match(names(replace), nms), replace)\n x\n}\n\nif_else <- function(condition, true, false, na = NULL) {\n # output size from `condition`\n size <- vec_size(condition)\n\n # output type from `true`/`false`/`na`\n ptype <- vec_ptype_common(true = true, false = false, na = na)\n\n args <- vec_recycle_common(\n true = true,\n false = false,\n na = na,\n .size = size\n )\n args <- vec_cast_common(!!!args, .to = ptype)\n\n out <- vec_init(ptype, size)\n\n loc_true <- condition\n loc_false <- !condition\n\n out <- vec_assign(out, loc_true, vec_slice(args$true, loc_true))\n out <- vec_assign(out, loc_false, vec_slice(args$false, loc_false))\n\n if (!is.null(na)) {\n loc_na <- vec_detect_missing(condition)\n out <- vec_assign(out, loc_na, vec_slice(args$na, loc_na))\n }\n\n out\n}\n\ncase_when <- function(.default, ..., .ptype = NULL) {\n if (is.null(.ptype)) {\n .ptype <- vec_ptype(.default)\n } else {\n .default <- vec_cast(.default, .ptype)\n }\n env <- rlang::caller_env()\n dots <- rlang::list2(...)\n unused <- vec_rep(TRUE, times = vec_size(.default))\n for (i in seq_along(dots)) {\n if (!any(unused)) {\n break\n }\n dot <- .subset2(dots, i)\n loc <- unused & rlang::eval_tidy(rlang::f_lhs(dot), env = env)\n value <- rlang::eval_tidy(rlang::f_rhs(dot), env = env)\n value <- vec_cast(value, .ptype, x_arg = sprintf(\"`...` (%d)\", i))\n if (length(value) > 1L) value <- vec_slice(value, loc)\n .default <- vec_assign(\n .default,\n loc,\n value,\n value_arg = sprintf(\"`...` (%d)\", i)\n )\n unused[loc] <- FALSE\n }\n .default\n}\n\n\n#' Replace NAs with specified values\n#' @param value A single value.\n#' @noRd\nreplace_na <- function(x, value) {\n value <- vec_cast(x = value, to = x, x_arg = \"value\", to_arg = \"x\")\n vec_assign(x, vec_detect_missing(x), value)\n}\n\n#' Find the first non-missing element\n#' @param ... A list of atomic vector (You shouldn't input `NULL`).\n#' @noRd\ncoalesce <- function(...) {\n dots <- vec_recycle_common(...)\n out <- .subset2(dots, 1L)\n for (i in 2:length(dots)) {\n if (vec_any_missing(out)) {\n missing <- vec_detect_missing(out)\n out <- vec_assign(\n out,\n missing,\n vec_slice(.subset2(dots, i), missing)\n )\n } else {\n return(out)\n }\n }\n out\n}\n\n#' Convert values to `NA`\n#' @noRd\nna_if <- function(x, y) {\n y <- vec_cast(x = y, to = x, x_arg = \"y\", to_arg = \"x\")\n y <- vec_recycle(y, size = vec_size(x), x_arg = \"y\")\n na <- vec_init(x)\n vec_assign(x, vec_equal(x, y, na_equal = TRUE), na)\n}\n\ndeframe <- function(x) {\n if (ncol(x) == 1L) {\n return(x[[1]])\n }\n vec_set_names(x[[1L]], x[[2]])\n}\n\nenframe <- function(x, name = \"name\", value = \"value\") {\n if (!is.null(names(x))) {\n data <- list(names(x), unname(x))\n } else {\n data <- list(seq_along(x), unname(x))\n }\n new_data_frame(vec_set_names(data, c(name, value)))\n}\n\nremove_rownames <- function(.data) {\n rownames(.data) <- NULL\n .data\n}\n\nrownames_to_column <- function(.data, var = \"rowname\") {\n if (!is.null(var_col <- rownames(.data))) {\n nms <- names(.data)\n .data[[var]] <- var_col\n .data <- .data[c(var, nms)]\n }\n .data\n}\n\ncolumn_to_rownames <- function(.data, var = 1L) {\n rownames(.data) <- .subset2(.data, var)\n .data[[var]] <- NULL\n .data\n}\n\n# nocov end\n"], ["/ggalign/R/active.R", "#' Plot Adding Context Settings\n#'\n#' @description\n#' `r lifecycle::badge('experimental')`\n#'\n#' These settings control the behavior of the plot when added to a layout, as\n#' well as the arrangement of individual plot areas within the layout.\n#'\n#' @details\n#' By default, the active context is set only for functions that add plot areas.\n#' This allows other `ggplot2` elements-such as `geoms`, `stats`, `scales`, or\n#' `themes`- to be seamlessly added to the current plot area.\n#'\n#' The default ordering of the plot areas is from top to bottom or from left to\n#' right, depending on the layout orientation. However, users can customize this\n#' order using the `order` argument.\n#'\n#' @param order An integer specifying the order of the plot area within the\n#' layout.\n#' @param use A logical (`TRUE`/`FALSE`) indicating whether to set the\n#' active context to the current plot when added to a layout. If `TRUE`,\n#' any subsequent `ggplot` elements will be applied to this plot.\n#' @param name A string specifying the plot's name, useful for switching active\n#' contexts through the `what` argument in functions like\n#' [`quad_anno()`]/[`stack_switch()`].\n#' @export\nactive <- function(order = waiver(), use = waiver(), name = waiver()) {\n if (!is.waive(order)) order <- check_order(order)\n if (!is.waive(use)) assert_bool(use)\n if (!is.waive(name)) {\n assert_string(name,\n empty_ok = FALSE, allow_na = TRUE,\n allow_null = FALSE\n )\n }\n new_active(order = order, use = use, name = name)\n}\n\n# for internal function, we only adjust to the `use` argument\n# here, we put it in the first\nnew_active <- function(use, order = NA_integer_, name = NA_character_) {\n structure(\n list(order = order, use = use, name = name),\n class = \"ggalign_active\"\n )\n}\n\n#' @importFrom utils modifyList\nupdate_active <- function(active, default) {\n if (is.null(active)) return(default) # styler: off\n modifyList(default,\n active[!vapply(active, is.waive, logical(1L), USE.NAMES = FALSE)],\n keep.null = TRUE\n )\n}\n"], ["/ggalign/R/layout-heatmap-.R", "#' Create a heatmap\n#'\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' `heatmap_layout` is a specialized version of [`quad_discrete()`], which\n#' simplifies the creation of heatmap plots by integrating essential elements\n#' for a standard heatmap layout, ensuring that the appropriate data mapping and\n#' visualization layers are automatically applied. `ggheatmap` is an alias for\n#' `heatmap_layout`.\n#'\n#' @param data `r rd_layout_data()`. By default, it will try to inherit from\n#' parent layout. [`fortify_matrix()`] will be used to convert data to a\n#' matrix.\n#' @param ... Additional arguments passed to [`fortify_matrix()`].\n#' @inheritParams quad_layout\n#' @param filling A single string of `r oxford_or(c(\"raster\", \"tile\"))` to\n#' indicate the filling style. By default, `waiver()` is used, which means that\n#' if the input matrix has more than 20,000 cells (`nrow * ncol > 20000`),\n#' [`geom_raster()`][ggplot2::geom_raster] will be used for performance\n#' efficiency; for smaller matrices, [`geom_tile()`][ggplot2::geom_tile] will be\n#' used. To customize the filling style, set this to `NULL`.\n#'\n#' For backward compatibility, a single boolean value is acceptable: `TRUE`\n#' means `waiver()`, and `FALSE` means `NULL`.\n#'\n#' By default, the classic heatmap color scheme\n#' [`scale_fill_gradient2(low = \"blue\", high = \"red\")`][ggplot2::scale_fill_gradient2]\n#' is utilized for continuous values.\n#'\n#' You can use the options\n#' `r code_quote(sprintf(\"%s.heatmap_continuous_fill\", pkg_nm()))` or\n#' `r code_quote(sprintf(\"%s.heatmap_discrete_fill\", pkg_nm()))` to modify the\n#' default heatmap body filling color scale. See\n#' [`scale_fill_continuous()`][ggplot2::scale_fill_continuous] or\n#' [`scale_fill_discrete()`][ggplot2::scale_fill_discrete] for details on\n#' option settings.\n#'\n#' @section ggplot2 specification:\n#' The data input will be converted to a matrix using [`fortify_matrix()`], and\n#' the data in the underlying main plot will contain the following columns:\n#'\n#' - `.panel_x` and `.panel_y`: the column and row panel groups.\n#'\n#' - `.x` and `.y`: an integer index of `x` and `y` coordinates\n#'\n#' - `.discrete_x` and `.discrete_y`: a factor of the data labels (only\n#' applicable when `.row_names` and `.column_names` exists).\n#'\n#' - `.row_names` and `.column_names`: A character of the row and column names\n#' of the original matrix (only applicable when names exist).\n#'\n#' - `.row_index` and `.column_index`: the row and column index of the original\n#' matrix.\n#'\n#' - `value`: the actual matrix value.\n#'\n#' @return A `HeatmapLayout` object.\n#' @examples\n#' ggheatmap(1:10)\n#' ggheatmap(letters)\n#' ggheatmap(matrix(rnorm(81), nrow = 9L))\n#' @importFrom ggplot2 aes\n#' @export\nheatmap_layout <- function(data = NULL, mapping = aes(),\n ...,\n width = NA, height = NA, filling = waiver(),\n theme = NULL, active = NULL) {\n UseMethod(\"heatmap_layout\")\n}\n\n#' @usage NULL\n#' @export\n#' @rdname heatmap_layout\nggheatmap <- heatmap_layout\n\n#' @importFrom ggplot2 aes\n#' @importFrom rlang arg_match0\n#' @export\nheatmap_layout.default <- function(data = NULL, mapping = aes(),\n ...,\n width = NA, height = NA, filling = waiver(),\n theme = NULL, active = NULL) {\n # A single boolean value for compatible with `version <= 0.0.4`\n if (isTRUE(filling)) {\n filling <- waiver()\n } else if (isFALSE(filling)) {\n filling <- NULL\n } else if (!is.waive(filling) && !is.null(filling)) {\n filling <- arg_match0(filling, c(\"tile\", \"raster\"))\n }\n data <- data %|w|% NULL\n # we need a matrix to melted into long formated data frame\n data <- fortify_matrix(data = data, ...)\n ans <- new_quad_layout(\n name = \"ggheatmap\",\n data = data,\n mapping = mapping,\n theme = theme, active = active,\n width = width, height = height,\n class = \"HeatmapLayout\"\n )\n # add default mapping\n ans@plot <- ggadd_default(ans@plot, mapping = aes(.data$.x, .data$.y)) +\n ggplot2::labs(x = NULL, y = NULL)\n ans@filling <- filling\n ans\n}\n\n# used to create the heatmap layout\n#' @keywords internal\n#' @include layout-quad-.R\nmethods::setClass(\n \"HeatmapLayout\",\n contains = \"QuadLayout\",\n list(filling = \"ANY\") # parameters for heatmap body\n)\n"], ["/ggalign/R/ggplot-utils.R", "#' @importFrom ggplot2 .pt\nggfun <- function(fn, mode = \"any\") from_namespace(\"ggplot2\", fn, mode = mode)\n\nallow_lambda <- function(x) {\n if (rlang::is_formula(x)) rlang::as_function(x) else x\n}\n\nis.waive <- function(x) inherits(x, \"waiver\")\n\n`%|w|%` <- function(x, y) if (inherits(x, \"waiver\")) y else x\n\nsnake_class <- function(x) ggfun(\"snake_class\")(x)\n\nggadd_default <- function(plot, mapping = NULL, theme = NULL) {\n if (!is.null(mapping)) {\n plot <- plot + mapping + plot$mapping\n }\n if (!is.null(theme)) plot$theme <- theme + plot$theme\n plot\n}\n\nis_palette_unset <- function(type, aes) {\n type <- match.arg(type, c(\"discrete\", \"continuous\", \"binned\"))\n aes <- match.arg(aes, c(\"fill\", \"colour\"))\n is.null(getOption(sprintf(\"ggplot2.%s.%s\", type, aes)))\n}\n\n# A guide-box should be a `zeroGrob()` or a `gtable` object\n#' @importFrom gtable is.gtable\nmaybe_guide_box <- function(x) inherits(x, \"zeroGrob\") || is.gtable(x)\n\n######################################################\ngguse_data <- function(plot, data) {\n # ggplot use waiver() to indicate no data\n plot[\"data\"] <- list(data %||% waiver())\n plot\n}\n\nggremove_margin <- function(plot, direction) {\n if (!is.null(direction) && packageVersion(\"ggplot2\") > \"3.5.2\") {\n plot <- plot + switch_direction(\n direction,\n theme(plot.margin = margin(t = 0, r = NA, b = 0, l = NA)),\n theme(plot.margin = margin(t = NA, r = 0, b = NA, l = 0))\n )\n }\n plot\n}\n\n######################################################\ndefault_expansion <- function(x = NULL, y = NULL) {\n structure(list(x = x, y = y), class = c(\"ggalign_default_expansion\"))\n}\n\n#' @importFrom ggplot2 ggplot_add ggproto ggproto_parent\n#' @export\nggplot_add.ggalign_default_expansion <- function(object, plot, object_name,\n ...) {\n if (is.null(.subset2(object, \"x\")) && is.null(.subset2(object, \"y\"))) {\n return(plot)\n }\n ParentFacet <- plot$facet\n plot$facet <- ggproto(\n NULL,\n ParentFacet,\n init_scales = function(self, layout, x_scale = NULL, y_scale = NULL,\n params) {\n if (!is.null(x_scale) && !is.null(.subset2(object, \"x\"))) {\n x_scale$expand <- x_scale$expand %|w|% .subset2(object, \"x\")\n }\n if (!is.null(y_scale) && !is.null(.subset2(object, \"y\"))) {\n y_scale$expand <- y_scale$expand %|w|% .subset2(object, \"y\")\n }\n ggproto_parent(ParentFacet, self)$init_scales(\n layout = layout,\n x_scale = x_scale,\n y_scale = y_scale,\n params = params\n )\n }\n )\n plot\n}\n\n######################################################\nreverse_continuous_axis <- function(plot, axis) {\n if (plot$scales$has_scale(axis)) {\n # modify scale in place\n scale <- plot$scales$get_scales(axis)\n if (!scale$is_discrete()) {\n if (identical(scale$trans$name, \"identity\")) {\n scale$trans <- scales::as.transform(\"reverse\")\n } else if (identical(scale$trans$name, \"reverse\")) {\n scale$trans <- scales::as.transform(\"identity\")\n }\n }\n } else {\n plot <- plot +\n switch(axis,\n x = ggplot2::scale_x_reverse(),\n y = ggplot2::scale_y_reverse()\n )\n }\n plot\n}\n"], ["/ggalign/R/layout-chain-operator.R", "#' @keywords internal\nchain_layout_subtract <- function(object, layout, object_name) {\n UseMethod(\"chain_layout_subtract\")\n}\n\n#' @export\nchain_layout_subtract.default <- function(object, layout, object_name) {\n if (is.null(active_index <- layout@active) ||\n is_craftbox(plot <- .subset2(layout@plot_list, active_index))) {\n layout@plot_list <- lapply(layout@plot_list, function(plot) {\n if (is_craftbox(plot)) {\n chain_plot_add(plot, object, object_name, force = FALSE)\n } else {\n plot\n }\n })\n } else {\n layout@plot_list[[active_index]] <- quad_layout_subtract(\n object, plot, object_name\n )\n }\n layout\n}\n\n# for objects can inherit from layout\n#' @export\nchain_layout_subtract.ggalign_scheme <- function(object, layout, object_name) {\n if (is.null(active_index <- layout@active) ||\n is_craftbox(plot <- .subset2(layout@plot_list, active_index))) {\n layout <- update_layout_scheme(object, layout, object_name)\n } else {\n layout@plot_list[[active_index]] <- quad_layout_subtract(\n object, plot, object_name\n )\n }\n layout\n}\n\n#' @export\nchain_layout_subtract.ggalign_with_quad <- function(object, layout,\n object_name) {\n if (!is_stack_layout(layout)) {\n cli_abort(sprintf(\n \"Cannot add {.var {object_name}} to %s\",\n object_name(layout)\n ))\n }\n if (is.null(active_index <- layout@active) ||\n is_craftbox(plot <- .subset2(layout@plot_list, active_index))) {\n inner <- .subset2(object, \"object\")\n inner_name <- .subset2(object, \"object_name\")\n\n # subtract set at layout level, if it is a plot option\n # we only apply to current active layout\n if (inherits(inner, \"ggalign_scheme\")) {\n layout <- update_layout_scheme(inner, layout, inner_name)\n return(layout)\n }\n\n # otherwise, we apply the object to all plots in the stack layout\n direction <- layout@direction\n layout@plot_list <- lapply(layout@plot_list, function(plot) {\n if (is_craftbox(plot)) {\n plot <- chain_plot_add(plot, inner, inner_name, force = FALSE)\n } else if (is.waive(.subset2(object, \"position\"))) {\n # default behaviour for object wrap with `with_quad()`\n # we add the object along the stack layout\n # if means for horizontal stack, we'll add it\n # to the left and right annotation, and the main plot\n positions <- switch_direction(\n direction,\n c(\"left\", \"right\"),\n c(\"top\", \"bottom\")\n )\n for (position in positions) {\n if (!is.null(slot(plot, position))) {\n slot(plot, position) <- chain_layout_subtract(\n inner, slot(plot, position), inner_name\n )\n }\n }\n if (is.null(main <- .subset2(object, \"main\")) || main) {\n plot <- quad_body_add(inner, plot, inner_name)\n }\n } else {\n # we respect the context setting\n plot <- quad_layout_subtract(object, plot, object_name)\n }\n plot\n })\n } else {\n layout@plot_list[[active_index]] <- quad_layout_subtract(\n object, plot, object_name\n )\n }\n layout\n}\n\n##################################################################\n#' @keywords internal\nchain_layout_and_add <- function(object, layout, object_name) {\n UseMethod(\"chain_layout_and_add\")\n}\n\n#' @export\nchain_layout_and_add.ggalign_with_quad <- function(object, layout, object_name) {\n if (!is_stack_layout(layout)) {\n cli_abort(sprintf(\n \"Cannot add {.var {object_name}} to %s\",\n object_name(layout)\n ))\n }\n object <- .subset2(object, \"object\")\n object_name <- .subset2(object, \"object_name\")\n NextMethod()\n}\n\n#' @export\nchain_layout_and_add.default <- function(object, layout, object_name) {\n layout@plot_list <- lapply(layout@plot_list, function(plot) {\n if (is_craftbox(plot)) {\n plot <- chain_plot_add(plot, object, object_name, force = FALSE)\n } else {\n plot <- quad_layout_and_add(object, plot, object_name)\n }\n plot\n })\n layout\n}\n\n#' @export\nchain_layout_and_add.theme <- function(object, layout, object_name) {\n ans <- NextMethod()\n # to align with `patchwork`, we also modify the layout theme\n # when using `&` to add the theme object.\n ans@theme <- ggfun(\"add_theme\")(ans@theme, object)\n ans\n}\n"], ["/ggalign/R/alignpatch-patchwork.R", "########################################\n#' @importFrom utils modifyList getFromNamespace\n#' @export\nalignpatch.patchwork <- function(x) {\n rlang::check_installed(\"patchwork\", \"to align patchwork\")\n get_patches <- getFromNamespace(\"get_patches\", \"patchwork\")\n # patchwork will keep the class when extracting patches from it.\n # we removed the classes for patchwork, added behind patchwork\n # in this way, the last plot won't have class like `free_align`,\n # `free_border`, `free_lab`, et al. which is added for the patchwork\n sub_patchwork_cls <- which(class(x) == \"patchwork\") - 1L # nolint\n if (sub_patchwork_cls > 0L) {\n class(x) <- class(x)[-seq_len(sub_patchwork_cls)]\n }\n x <- get_patches(x)\n plots <- .subset2(x, \"plots\")\n layout <- .subset2(x, \"layout\")\n annotation <- .subset2(x, \"annotation\")\n default <- getFromNamespace(\"default_layout\", \"patchwork\")\n layout <- modifyList(default, layout[\n !vapply(layout, is.null, logical(1L), USE.NAMES = FALSE)\n ])\n if (identical(.subset2(layout, \"guides\"), \"collect\")) {\n layout$guides <- .TLBR\n } else {\n layout$guides <- NULL\n }\n alignpatch(AlignPatches(\n plots,\n layout = layout,\n titles = .subset(annotation, names(layout_title())),\n theme = .subset2(annotation, \"theme\")\n ))\n}\n\n#' @export\nalignpatch.free_plot <- function(x) {\n if (inherits(x, \"patchwork\")) {\n free_settings <- attr(x, \"patchwork_free_settings\")\n } else {\n free_settings <- attr(x, \"free_settings\")\n }\n free_settings <- split(\n names(free_settings),\n factor(free_settings, rev(unique(free_settings)))\n )\n class(x) <- vec_set_difference(class(x), \"free_plot\")\n for (type in names(free_settings)) {\n side <- paste(.subset2(free_settings, type), collapse = \"\")\n x <- switch(type,\n panel = free_align(x, side),\n label = free_lab(x, side),\n space = free_space(free_border(x, side), side),\n )\n }\n alignpatch(x)\n}\n\n######################################\n# `patch` from `patchwork`: patchwork::plot_spacer\n#' @importFrom ggplot2 ggproto\n#' @export\nalignpatch.patch <- function(x) {\n rlang::check_installed(\n \"patchwork\", sprintf(\"to align %s plot\", obj_type_friendly(x))\n )\n ggproto(NULL, PatchPatchworkPatch, plot = x)\n}\n\n#' @importFrom ggplot2 ggproto\nPatchPatchworkPatch <- ggproto(\n \"PatchPatchworkPatch\", Patch,\n # `patch` from `patchwork`: patchwork::plot_spacer\n #' @importFrom gtable gtable_add_rows gtable_add_cols\n #' @importFrom ggplot2 find_panel\n patch_gtable = function(self, theme, guides, plot = self$plot) {\n guides <- if (length(guides)) \"collect\" else \"keep\"\n ans <- patchwork::patchGrob(patch, guides = guides)\n for (border in .TLBR) {\n panel_pos <- find_panel(ans)\n if (border == \"top\") {\n h <- .subset2(panel_pos, \"t\") - 4L # above original xlab\n ans <- gtable_add_rows(ans, unit(0L, \"mm\"), pos = h)\n } else if (border == \"left\") {\n v <- .subset2(panel_pos, \"l\") - 4L # left of the ylab\n ans <- gtable_add_cols(ans, unit(0, \"mm\"), pos = v)\n } else if (border == \"bottom\") {\n h <- .subset2(panel_pos, \"b\") + 3L # below original xlab\n ans <- gtable_add_rows(ans, unit(0L, \"mm\"), pos = h)\n } else if (border == \"right\") {\n v <- .subset2(panel_pos, \"r\") + 3L # right of the ylab\n ans <- gtable_add_cols(ans, unit(0, \"mm\"), pos = v)\n }\n }\n ans\n }\n)\n\n#' @export\nalignpatch.spacer <- function(x) NULL\n\n#########################################\n# `patch` from `patchwork`: patchwork::wrap_elements\n#' @export\nalignpatch.wrapped_patch <- alignpatch.patch\n"], ["/ggalign/R/alignpatch-free-lab.R", "#' @param labs Which axis labs to be free? A string containing one or more of\n#' `r oxford_and(.tlbr)`.\n#' @return\n#' - `free_lab`: A modified version of `plot` with a `free_lab` class.\n#' @export\n#' @rdname free\nfree_lab <- function(plot, labs = \"tlbr\") {\n UseMethod(\"free_lab\")\n}\n\n#' @export\nfree_lab.ggplot <- function(plot, labs = \"tlbr\") {\n assert_position(labs)\n attr(plot, \"free_labs\") <- labs\n add_class(plot, \"free_lab\")\n}\n\n#' @export\nfree_lab.alignpatches <- free_lab.ggplot\n\n#' @export\nfree_lab.free_align <- function(plot, labs = \"tlbr\") {\n assert_position(labs)\n labs <- setdiff_position(labs, attr(plot, \"free_axes\"))\n if (!nzchar(labs)) return(plot) # styler: off\n NextMethod()\n}\n\n#' @export\nfree_lab.free_borders <- function(plot, labs = \"tlbr\") {\n assert_position(labs)\n labs <- setdiff_position(labs, attr(plot, \"free_borders\"))\n if (!nzchar(labs)) return(plot) # styler: off\n NextMethod()\n}\n\n#' @export\nfree_lab.free_lab <- function(plot, labs = \"tlbr\") {\n assert_position(labs)\n attr(plot, \"free_labs\") <- union_position(attr(plot, \"free_labs\"), labs)\n plot\n}\n\n#' @export\nfree_lab.default <- function(plot, labs = \"tlbr\") {\n cli_abort(\"Cannot use with {.obj_type_friendly {plot}}\")\n}\n\n####################################################\n#' @importFrom ggplot2 ggproto ggproto_parent\n#' @export\nalignpatch.free_lab <- function(x) {\n Parent <- NextMethod()\n ggproto(\n \"PatchFreeLab\", Parent,\n free_labs = setup_pos(attr(x, \"free_labs\")),\n collect_guides = function(self, guides, gt = self$gt) {\n ans <- ggproto_parent(Parent, self)$collect_guides(\n guides = guides, gt = gt\n )\n self$gt <- ggproto_parent(Parent, self)$free_lab(\n labs = self$free_labs, gt = self$gt\n )\n ans\n },\n free_lab = function(self, labs, gt = self$gt) {\n if (length(labs <- vec_set_difference(labs, self$free_labs))) {\n gt <- ggproto_parent(Parent, self)$free_lab(\n labs = labs, gt = gt\n )\n }\n gt\n }\n )\n}\n"], ["/ggalign/R/alignpatch-wrap.R", "#' Wrap Arbitrary Graphics to ggplot\n#'\n#' The `ggwrap()` function allows non-ggplot2 elements to be converted into a\n#' compliant representation for use with [`align_plots()`]. This is useful for\n#' adding any graphics that can be converted into a [`grob`][grid::grob] with\n#' the [`patch()`] method.\n#'\n#' @param plot Any graphic that can be converted into a [`grob`][grid::grob]\n#' using [`patch()`].\n#' @param ... Additional arguments passed to the [`patch()`] method.\n#' @param align A string specifying the area to place the plot: `\"full\"` for the\n#' full area, `\"plot\"` for the full plotting area (including the axis label), or\n#' `\"panel\"` for only the actual area where data is drawn.\n#' @param clip A single boolean value indicating whether the grob should be\n#' clipped if they expand outside their designated area.\n#' @param on_top A single boolean value indicates whether the graphic plot\n#' should be put frontmost. Note: the graphic plot will always put above the\n#' background.\n#' @param vp A [`viewport`][grid::viewport] object, you can use this to define\n#' the plot area.\n#' @return A `wrapped_plot` object that can be directly placed into\n#' [`align_plots()`].\n#' @inherit patch seealso\n#' @examples\n#' library(grid)\n#' ggwrap(rectGrob(gp = gpar(fill = \"goldenrod\")), align = \"full\") +\n#' inset(rectGrob(gp = gpar(fill = \"steelblue\")), align = \"panel\") +\n#' inset(textGrob(\"Here are some text\", gp = gpar(color = \"black\")),\n#' align = \"panel\"\n#' )\n#' p1 <- ggplot(mtcars) +\n#' geom_point(aes(mpg, disp)) +\n#' ggtitle(\"Plot 1\")\n#' align_plots(p1, ggwrap(\n#' ~ plot(mtcars$mpg, mtcars$disp),\n#' mar = c(0, 2, 0, 0), bg = NA\n#' ))\n#'\n#' @importFrom ggplot2 theme element_blank ggplot\n#' @importFrom grid is.grob\n#' @export\nggwrap <- function(plot, ..., align = \"panel\", on_top = FALSE,\n clip = TRUE, vp = NULL) {\n patch <- ggplot() +\n theme(\n plot.background = element_blank(),\n panel.background = element_blank()\n )\n inset <- make_inset(\n plot = plot, ..., align = align, on_top = on_top,\n clip = clip, vp = vp\n )\n make_wrap(patch, inset)\n}\n\nmake_wrap <- function(patch, inset) UseMethod(\"make_wrap\")\n\nmake_wrapped_plot <- function(patch, inset) {\n if (.subset2(inset, \"on_top\")) {\n patch$ggalign_wrapped_insets_above <- c(\n patch$ggalign_wrapped_insets_above, list(inset)\n )\n } else {\n patch$ggalign_wrapped_insets_under <- c(\n patch$ggalign_wrapped_insets_under, list(inset)\n )\n }\n add_class(patch, \"wrapped_plot\")\n}\n\n#' @export\nmake_wrap.ggplot <- function(patch, inset) {\n patch <- add_class(patch, \"patch_ggplot\")\n make_wrap(patch, inset)\n}\n\n#' @export\nmake_wrap.patch_ggplot <- make_wrapped_plot\n\n#' @export\nmake_wrap.alignpatches <- make_wrapped_plot\n\n#################################################\n#' @importFrom ggplot2 ggproto ggproto_parent\n#' @export\nalignpatch.wrapped_plot <- function(x) {\n Parent <- NextMethod()\n ggproto(\n \"PatchWrapped\", Parent,\n ggalign_wrapped_insets_under = x$ggalign_wrapped_insets_under,\n ggalign_wrapped_insets_above = x$ggalign_wrapped_insets_above,\n patch_gtable = function(self, theme, guides, plot = Parent$plot) {\n ans <- ggproto_parent(Parent, self)$patch_gtable(\n theme = theme, guides = guides, plot = plot\n )\n ans <- add_wrapped_insets(\n ans, self$ggalign_wrapped_insets_under, FALSE\n )\n add_wrapped_insets(ans, self$ggalign_wrapped_insets_above, TRUE)\n }\n )\n}\n\n# For wrapped plot -------------------\n#' @export\nalignpatch.grob <- function(x) alignpatch(ggwrap(x))\n\n#' @export\nalignpatch.gList <- alignpatch.grob\n\n#' @export\nalignpatch.formula <- alignpatch.grob\n\n#' @export\nalignpatch.function <- alignpatch.grob\n\n#' @export\nalignpatch.recordedplot <- alignpatch.grob\n\n#' @export\nalignpatch.trellis <- alignpatch.grob\n\n#' @export\nalignpatch.Heatmap <- function(x) alignpatch(ggwrap(x, align = \"full\"))\n\n#' @export\nalignpatch.HeatmapList <- alignpatch.Heatmap\n\n#' @export\nalignpatch.HeatmapAnnotation <- alignpatch.Heatmap\n\n#' @export\nalignpatch.pheatmap <- function(x) alignpatch(ggwrap(x, align = \"full\"))\n\n################################################## 3\nadd_wrapped_insets <- function(gt, insets, on_top) {\n if (is.null(insets)) return(gt) # styler: off\n for (i in seq_along(insets)) {\n gt <- add_wrapped_inset(gt, .subset2(insets, i), on_top, i)\n }\n gt\n}\n\n#' @importFrom gtable gtable is.gtable gtable_add_grob\nadd_wrapped_inset <- function(gt, inset, on_top, i) {\n align <- .subset2(inset, \"align\")\n clip <- .subset2(inset, \"clip\")\n layout <- .subset2(gt, \"layout\")\n grob <- .subset2(inset, \"grob\")\n if (on_top) {\n z <- Inf\n } else {\n background <- .subset2(layout, \"name\") == \"background\"\n z <- .subset2(layout, \"z\")[background] + 1L\n gt$layout$z[layout$z >= z] <- layout$z[layout$z >= z] + 1L\n }\n\n # add the grob to the gtable\n if (align == \"full\") {\n gt <- gtable_add_grob(gt,\n list(grob), 1L, 1L, nrow(gt), ncol(gt),\n clip = clip, name = sprintf(\"wrap-full-%d\", i), z = z\n )\n } else {\n panel_loc <- find_panel(gt)\n gt <- switch(align,\n plot = gtable_add_grob(gt,\n list(grob),\n .subset2(panel_loc, \"t\") - 3L,\n .subset2(panel_loc, \"l\") - 3L,\n .subset2(panel_loc, \"b\") + 3L,\n .subset2(panel_loc, \"r\") + 3L,\n clip = clip, name = sprintf(\"wrap-plot-%d\", i), z = z\n ),\n panel = gtable_add_grob(gt,\n list(grob),\n .subset2(panel_loc, \"t\"),\n .subset2(panel_loc, \"l\"),\n .subset2(panel_loc, \"b\"),\n .subset2(panel_loc, \"r\"),\n clip = clip, name = sprintf(\"wrap-panel-%d\", i), z = z\n )\n )\n }\n gt\n}\n"], ["/ggalign/R/alignpatch-free-vp.R", "#' @inheritParams grid::viewport\n#' @inheritDotParams grid::viewport -x -y -width -height\n#' @return\n#' - `free_vp`: A modified version of `plot` with a `free_vp` class.\n#' @importFrom grid viewport\n#' @export\n#' @rdname free\nfree_vp <- function(plot, x = 0.5, y = 0.5, width = NA, height = NA, ...) {\n UseMethod(\"free_vp\")\n}\n\n#' @export\nfree_vp.default <- function(plot, x = 0.5, y = 0.5,\n width = NA, height = NA, ...) {\n cli_abort(\"Cannot use with {.obj_type_friendly {plot}}\")\n}\n\n#' @export\nfree_vp.ggplot <- function(plot, x = 0.5, y = 0.5,\n width = NA, height = NA, ...) {\n attr(plot, \"vp\") <- viewport(\n x = x, y = y, width = width, height = height, ...,\n )\n add_class(plot, \"free_vp\")\n}\n\n#' @export\nfree_vp.alignpatches <- free_vp.ggplot\n\n####################################################\n#' @importFrom gtable gtable_width gtable_height\n#' @importFrom ggplot2 ggproto ggproto_parent\n#' @export\nalignpatch.free_vp <- function(x) {\n Parent <- NextMethod()\n ggproto(\n \"PatchFreeViewport\", Parent,\n vp = attr(x, \"vp\"),\n align_border = function(self, t = NULL, l = NULL, b = NULL, r = NULL,\n gt = self$gt) {\n ans <- ggproto_parent(Parent, self)$align_border(\n t = t, l = l, b = b, r = r, gt = gt\n )\n vp <- self$vp\n\n if (!any(is_null_unit(widths <- .subset2(ans, \"widths\")))) {\n horizontal_just <- TRUE\n vp$width <- sum(widths)\n } else if (!is.na(as.numeric(vp$width))) {\n # we guess the width from the gtable\n horizontal_just <- TRUE\n vp$width <- max(vp$width, sum(widths))\n } else {\n vp$width <- unit(1, \"npc\")\n horizontal_just <- FALSE\n }\n if (!any(is_null_unit(heights <- .subset2(ans, \"heights\")))) {\n vertical_just <- TRUE\n vp$height <- sum(heights)\n } else if (!is.na(as.numeric(vp$height))) {\n # we guess the height from the gtable\n vertical_just <- TRUE\n vp$height <- max(vp$height, sum(heights))\n } else {\n vp$height <- unit(1, \"npc\")\n vertical_just <- FALSE\n }\n if (horizontal_just || vertical_just) ans$vp <- vp\n ans\n }\n )\n}\n"], ["/ggalign/R/layout-chain-stack-switch.R", "#########################################################\n#' Determine the active context of stack layout\n#'\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' `stack_active` is an alias for `stack_switch()`, which sets `what = NULL` by\n#' default.\n#'\n#' @inheritParams rlang::args_dots_empty\n#' @inheritParams quad_switch\n#' @inheritParams stack_discrete\n#' @param what What should get activated for the stack layout?\n#' `r rd_chain_what()`, this is useful when the active context is a\n#' [`quad_layout()`] object, where any `align_*()` will be added to the\n#' [`quad_layout()`]. By removing the active context, we can add `align_*()`\n#' into the [`stack_layout()`].\n#' @return A `stack_switch` object which can be added to [stack_layout()].\n#' @examples\n#' stack_discrete(\"h\", matrix(1:9, nrow = 3L)) +\n#' ggheatmap() +\n#' # ggheamtap will set the active context, directing following addition\n#' # into the heatmap plot area. To remove the heatmap active context,\n#' # we can use `stack_active()` which will direct subsequent addition into\n#' # the stack\n#' stack_active() +\n#' # here we add a dendrogram to the stack.\n#' align_dendro()\n#' @export\nstack_switch <- function(sizes = NULL, what = waiver(), ...) {\n rlang::check_dots_empty()\n if (!is.waive(what)) what <- check_stack_context(what)\n if (!is.null(sizes)) sizes <- check_stack_sizes(sizes)\n structure(list(what = what, sizes = sizes), class = \"stack_switch\")\n}\n\n#' @export\n#' @rdname stack_switch\nstack_active <- function(sizes = NULL, ...) {\n rlang::check_dots_empty()\n stack_switch(sizes, what = NULL)\n}\n"], ["/ggalign/R/alignpatch-patch.R", "#' Convert Object into a Grob\n#'\n#' The `patch()` function is used by [`ggwrap()`] and [inset()] to convert\n#' objects into a [`grob`][grid::grob].\n#'\n#' @param x An object to be converted into a [`grob`][grid::grob].\n#' @param ... Additional arguments passed to specific methods.\n#' @return A [`grob`][grid::grob] object.\n#' @eval rd_collect_family(\"patch\", \"`patch` method collections\")\n#' @export\n#' @keywords internal\npatch <- function(x, ...) {\n UseMethod(\"patch\")\n}\n\n# Following methods much are copied from `cowplot` or `ggplotify`\n#' @export\npatch.default <- function(x, ...) {\n cli_abort(\"Cannot make grob from {.obj_type_friendly {x}}\")\n}\n\n#' @inherit patch title description return\n#' @inheritParams patch\n#' @param ... Not used currently.\n#' @family patch\n#' @export\npatch.grob <- function(x, ...) {\n rlang::check_dots_empty()\n x\n}\n\n#' @importFrom grid gTree\n#' @export\n#' @rdname patch.grob\npatch.gList <- function(x, ...) {\n rlang::check_dots_empty()\n # gLists need to be wrapped in a gTree\n gTree(children = x)\n}\n\n#' @importFrom ggplot2 ggplotGrob\n#' @inherit patch.grob\n#' @seealso [ggplot][ggplot2::ggplot]\n#' @family patch\n#' @export\npatch.ggplot <- function(x, ...) {\n ggplotGrob(x, ...)\n}\n\n#' @inherit patch.grob\n#' @seealso\n#' - [`patch_titles()`]\n#' - [`inset()`]\n#' - [`ggwrap()`]\n#' @family patch\n#' @export\npatch.patch_ggplot <- function(x, ...) {\n ggalignGrob(x, ...)\n}\n\n#' @inherit patch.grob\n#' @seealso [`alignpatches`][align_plots]\n#' @family patch\n#' @export\npatch.alignpatches <- function(x, ...) {\n ggalignGrob(x, ...)\n}\n\n#' @inherit patch.grob\n#' @seealso [`patchwork`][patchwork::patchworkGrob]\n#' @family patch\n#' @export\npatch.patchwork <- function(x, ...) {\n rlang::check_installed(\"patchwork\", \"to make grob from patchwork\")\n patchwork::patchworkGrob(x, ...)\n}\n\n#' @inherit patch.grob\n#' @seealso [`patch`][patchwork::patchGrob]\n#' @family patch\n#' @export\npatch.patch <- function(x, ...) {\n rlang::check_installed(\"patchwork\", \"to make grob from patch\")\n patchwork::patchGrob(x, ...)\n}\n\n#' @inherit patch.grob\n#' @param ... Graphical Parameters passed on to [par()][graphics::par].\n#' @inheritParams gridGraphics::echoGrob\n#' @seealso [`plot()`]\n#' @family patch\n#' @export\npatch.formula <- function(x, ..., device = NULL, name = NULL) {\n rlang::check_installed(\"gridGraphics\", \"to make grob from base plot\")\n gp <- graphics::par(..., no.readonly = TRUE)\n gridGraphics::echoGrob(\n function() {\n old_gp <- graphics::par(no.readonly = TRUE)\n graphics::par(gp)\n on.exit(try(graphics::par(old_gp)))\n suppressMessages(eval(x[[2]], attr(x, \".Environment\")))\n invisible(NULL)\n },\n name = name,\n device = device %||% offscreen\n )\n}\n\n#' @export\n#' @rdname patch.formula\npatch.function <- function(x, ..., device = NULL, name = NULL) {\n rlang::check_installed(\"gridGraphics\", \"to make grob from base plot\")\n gp <- graphics::par(..., no.readonly = TRUE)\n gridGraphics::echoGrob(\n function() {\n old_gp <- graphics::par(no.readonly = TRUE)\n graphics::par(gp)\n on.exit(try(graphics::par(old_gp)))\n suppressMessages(x())\n invisible(NULL)\n },\n name = name,\n device = device %||% offscreen\n )\n}\n\n#' @inherit patch.grob\n#' @inheritParams gridGraphics::echoGrob\n#' @seealso [`recordPlot()`][grDevices::recordPlot]\n#' @family patch\n#' @export\npatch.recordedplot <- function(x, ..., device = NULL) {\n rlang::check_installed(\"gridGraphics\", \"to make grob from recordedplot\")\n rlang::check_dots_empty()\n gridGraphics::echoGrob(x, device = device %||% offscreen)\n}\n\noffscreen <- function(width, height) {\n if (requireNamespace(\"ragg\", quietly = TRUE)) {\n ragg::agg_capture(width = width, height = height, units = \"in\")\n grDevices::dev.control(\"enable\")\n } else {\n grDevices::pdf(NULL, width = width, height = height)\n grDevices::dev.control(\"enable\")\n }\n}\n\n#' @inherit patch.grob\n#' @inheritDotParams grid::grid.grabExpr -expr -device\n#' @inheritParams grid::grid.grabExpr\n#' @seealso [`trellis`][lattice::trellis.object]\n#' @family patch\n#' @export\npatch.trellis <- function(x, ..., device = NULL) {\n grid::grid.grabExpr(expr = print(x), ..., device = device %||% offscreen)\n}\n\n#' @inherit patch.grob\n#' @param ... Additional arguments passed to [draw()][ComplexHeatmap::draw].\n#' @inheritParams grid::grid.grabExpr\n#' @seealso\n#' - [`Heatmap()`][ComplexHeatmap::Heatmap]\n#' - [`HeatmapAnnotation()`][ComplexHeatmap::HeatmapAnnotation]\n#' @family patch\n#' @export\npatch.Heatmap <- function(x, ..., device = NULL) {\n rlang::check_installed(\n \"ComplexHeatmap\",\n sprintf(\"to make grob from %s plot\", obj_type_friendly(x))\n )\n draw <- getExportedValue(\"ComplexHeatmap\", \"draw\")\n grid::grid.grabExpr(\n expr = draw(object = x, ...),\n device = device %||% offscreen\n )\n}\n\n#' @export\n#' @rdname patch.Heatmap\npatch.HeatmapList <- patch.Heatmap\n\n#' @export\n#' @rdname patch.Heatmap\npatch.HeatmapAnnotation <- patch.HeatmapList\n\n#' @inherit patch.grob\n#' @seealso [`pheatmap()`][pheatmap::pheatmap]\n#' @family patch\n#' @export\npatch.pheatmap <- function(x, ...) {\n rlang::check_dots_empty()\n .subset2(x, \"gtable\")\n}\n"], ["/ggalign/R/alignpatch-free-border.R", "#' @param borders Which border shouldn't be aligned? A string containing one or\n#' more of `r oxford_and(.tlbr)`.\n#' @return\n#' - `free_border`: A modified version of `plot` with a `free_border` class.\n#' @export\n#' @rdname free\nfree_border <- function(plot, borders = \"tlbr\") {\n UseMethod(\"free_border\")\n}\n\n#' @export\nfree_border.ggplot <- function(plot, borders = \"tlbr\") {\n assert_position(borders)\n attr(plot, \"free_borders\") <- borders\n add_class(plot, \"free_border\")\n}\n\n#' @export\nfree_border.alignpatches <- free_border.ggplot\n\n#' @export\nfree_border.free_align <- function(plot, borders = \"tlbr\") {\n assert_position(borders)\n borders <- setdiff_position(borders, attr(plot, \"free_axes\"))\n if (!nzchar(borders)) {\n return(plot)\n }\n NextMethod()\n}\n\n#' @export\nfree_border.free_lab <- function(plot, borders = \"tlbr\") {\n assert_position(borders)\n free_labs <- setdiff_position(attr(plot, \"free_labs\"), borders)\n if (nzchar(free_labs)) {\n attr(plot, \"free_labs\") <- free_labs\n } else {\n attr(plot, \"free_labs\") <- NULL\n plot <- remove_class(plot, \"free_lab\")\n }\n NextMethod()\n}\n\n#' @export\nfree_border.free_border <- function(plot, borders = \"tlbr\") {\n assert_position(borders)\n attr(plot, \"free_borders\") <- union_position(\n attr(plot, \"free_borders\"), borders\n )\n plot\n}\n\n#' @export\nfree_border.default <- function(plot, borders = \"tlbr\") {\n cli_abort(\"Cannot use with {.obj_type_friendly {plot}}\")\n}\n\n################################################################\n#' @importFrom ggplot2 ggproto ggproto_parent\n#' @export\nalignpatch.free_border <- function(x) {\n Parent <- NextMethod()\n ggproto(\n \"PatchFreeBorder\", Parent,\n free_borders = setup_pos(attr(x, \"free_borders\")),\n collect_guides = function(self, guides, gt = self$gt) {\n ans <- ggproto_parent(Parent, self)$collect_guides(\n guides = guides, gt = gt\n )\n self$gt <- ggproto_parent(Parent, self)$free_border(\n borders = self$free_borders, gt = self$gt\n )\n ans\n },\n align_border = function(self, t = NULL, l = NULL, b = NULL, r = NULL,\n gt = self$gt) {\n gt <- ggproto_parent(Parent, self)$align_border(\n t = t, l = l, b = b, r = r, gt = gt\n )\n ggproto_parent(Parent, self)$align_free_border(\n borders = self$free_borders,\n t = t, l = l, b = b, r = r, gt = gt\n )\n },\n free_border = function(self, borders, gt = self$gt) {\n borders <- vec_set_difference(borders, self$free_borders)\n if (length(borders)) {\n gt <- ggproto_parent(Parent, self)$free_border(\n borders = borders, gt = gt\n )\n }\n gt\n },\n align_free_border = function(self, borders,\n t = NULL, l = NULL, b = NULL, r = NULL,\n gt = self$gt) {\n borders <- vec_set_difference(borders, self$free_borders)\n if (length(borders)) {\n gt <- ggproto_parent(Parent, self)$align_free_border(\n borders = borders,\n t = t, l = l, b = b, r = r, gt = gt\n )\n }\n gt\n }\n )\n}\n"], ["/ggalign/R/scheme-theme.R", "#' Plot default theme\n#'\n#' @description\n#' `r lifecycle::badge('experimental')`\n#'\n#' `scheme_theme()` serves as the default theme and will always be overridden by\n#' any `theme()` settings applied directly to the plot. The default theme\n#' (`scheme_theme()`) is applied first, followed by any specific `theme()`\n#' settings, even if `theme()` is added before `scheme_theme()`.\n#'\n#' @inherit ggplot2::theme\n#' @param ... A [`theme()`][ggplot2::theme] object or additional element\n#' specifications not part of base ggplot2. In general, these should also be\n#' defined in the `element tree` argument. [`Splicing`][rlang::splice] a list\n#' is also supported.\n#' @examples\n#' set.seed(123)\n#' small_mat <- matrix(rnorm(56), nrow = 8)\n#' ggheatmap(small_mat) +\n#' scheme_theme(plot.background = element_rect(fill = \"red\"))\n#'\n#' # `scheme_theme()` serves as the default theme and will always be\n#' # overridden by any `theme()` settings applied directly to the plot\n#' ggheatmap(small_mat) +\n#' theme(plot.background = element_rect(fill = \"blue\")) +\n#' scheme_theme(plot.background = element_rect(fill = \"red\"))\n#'\n#' @importFrom ggplot2 theme\n#' @importFrom rlang inject\n#' @export\nscheme_theme <- rlang::new_function(\n # We utilize editor completion by listing all `theme()` arguments here.\n # By placing `...` at the beginning, we can check if the first\n # following argument is a `theme()` object rather than individual theme\n # elements.\n c(\n rlang::exprs(... = ),\n .subset(\n rlang::fn_fmls(theme),\n vec_set_difference(names(rlang::fn_fmls(theme)), \"...\")\n )\n ),\n quote({\n elements <- ggfun(\"find_args\")(..., complete = NULL, validate = NULL)\n ans <- theme(!!!elements)\n th <- NULL\n for (i in seq_len(...length())) {\n if (inherits(t <- ...elt(i), \"theme\")) {\n th <- ggfun(\"add_theme\")(th, t)\n }\n }\n new_scheme_theme(ggfun(\"add_theme\")(th, ans))\n })\n)\n\n#' @importFrom ggplot2 theme\nnew_scheme_theme <- function(th = theme()) {\n # I don't know why, if I omit the `object = th` argument, it won't work\n UseMethod(\"new_scheme_theme\", th)\n}\n\n#' @importFrom rlang inject\n#' @export\nnew_scheme_theme.theme <- function(th = theme()) {\n attrs <- attributes(th)\n attrs <- vec_slice(\n attrs, vec_set_difference(names(attrs), c(\"names\", \"class\"))\n )\n inject(new_scheme(\n name = \"scheme_theme\", th, !!!attrs,\n class = c(\"scheme_theme\", class(th))\n ))\n}\n\n#' @export\nnew_scheme_theme.scheme_theme <- function(th = theme()) th\n\n###############################################################\n#' @export\nupdate_scheme.scheme_theme <- function(new, old, object_name) {\n ggfun(\"add_theme\")(old, new, object_name)\n}\n\n#' @export\ninherit_scheme.scheme_theme <- function(scheme, pscheme) {\n pscheme + scheme\n}\n\n#' @export\nplot_add_scheme.scheme_theme <- function(plot, scheme) {\n # setup plot theme\n plot$theme <- scheme + plot$theme\n plot\n}\n"], ["/ggalign/R/alignpatch-free-space.R", "#' @param spaces Which border spaces should be removed? A string containing one\n#' or more of `r oxford_and(.tlbr)`.\n#' @return\n#' - `free_space`: A modified version of `plot` with a `free_space` class.\n#' @export\n#' @rdname free\nfree_space <- function(plot, spaces = \"tlbr\") {\n UseMethod(\"free_space\")\n}\n\n#' @export\nfree_space.default <- function(plot, spaces = \"tlbr\") {\n cli_abort(\"Cannot use with {.obj_type_friendly {plot}}\")\n}\n\n#' @export\nfree_space.ggplot <- function(plot, spaces = \"tlbr\") {\n assert_position(spaces)\n attr(plot, \"free_spaces\") <- spaces\n add_class(plot, \"free_space\")\n}\n\n#' @export\nfree_space.alignpatches <- free_space.ggplot\n\n#' @export\nfree_space.free_align <- function(plot, spaces = \"tlbr\") {\n assert_position(spaces)\n spaces <- setdiff_position(spaces, attr(plot, \"free_axes\"))\n if (!nzchar(spaces)) {\n return(plot)\n }\n NextMethod()\n}\n\n#' @export\nfree_space.free_space <- function(plot, spaces = \"tlbr\") {\n assert_position(spaces)\n attr(plot, \"free_spaces\") <- union_position(\n attr(plot, \"free_spaces\"), spaces\n )\n plot\n}\n\n##########################################################\n#' @importFrom ggplot2 ggproto ggproto_parent\n#' @importFrom grid unit\n#' @export\nalignpatch.free_space <- function(x) {\n Parent <- NextMethod()\n ggproto(\n \"PatchFreeSpace\", Parent,\n free_spaces = split_position(attr(x, \"free_spaces\")),\n get_sizes = function(self, free = NULL, gt = self$gt) {\n ggproto_parent(Parent, self)$get_sizes(\n union(free, self$free_spaces),\n gt = gt\n )\n }\n )\n}\n"], ["/ggalign/R/layout-heatmap-build.R", "#' @export\nquad_build.HeatmapLayout <- function(quad, schemes = NULL, theme = NULL,\n direction = NULL) {\n ans <- NextMethod()\n\n # add heatmap filling in the first layer --------------\n if (!is.null(filling <- quad@filling)) {\n # we always ensure the filling layer has a fill mapping\n if (is.null(.subset2(ans$plots$main$mapping, \"fill\"))) {\n mapping <- aes(.data$.x, .data$.y, fill = .data$value)\n } else {\n mapping <- aes(.data$.x, .data$.y)\n }\n if (is.waive(filling)) {\n if (nrow(quad@data) * ncol(quad@data) > 20000L) {\n cli_inform(c(\">\" = \"heatmap built with {.fn geom_raster}\"))\n filling <- \"raster\"\n } else {\n cli_inform(c(\">\" = \"heatmap built with {.fn geom_tile}\"))\n filling <- \"tile\"\n }\n }\n ans$plots$main <- ans$plots$main + layer_order(switch(filling,\n raster = ggplot2::geom_raster(mapping = mapping),\n tile = ggplot2::geom_tile(mapping = mapping)\n ))\n }\n # add class to set the default color mapping --------\n ans$plots$main <- add_class(ans$plots$main, \"ggalign_heatmap\")\n ans\n}\n\n#' @importFrom ggplot2 ggplot_build\n#' @export\nggplot_build.ggalign_heatmap <- function(plot, ...) {\n with_options(\n NextMethod(),\n ggplot2.discrete.fill = heatmap_fill(\"discrete\"),\n ggplot2.continuous.fill = heatmap_fill(\"continuous\")\n )\n}\n\nheatmap_fill <- function(type) {\n opt <- sprintf(\"%s.heatmap_%s_fill\", pkg_nm(), type)\n if (is.null(ans <- getOption(opt, default = NULL))) {\n if (type == \"continuous\") {\n ans <- function(...) {\n ggplot2::scale_fill_gradient2(low = \"blue\", high = \"red\")\n }\n } else {\n ans <- getOption(\"ggplot2.discrete.fill\")\n }\n }\n ans\n}\n"], ["/ggalign/R/alignpatch-free-guide.R", "#' @param guides A string containing one or more of\n#' `r oxford_and(c(.tlbr, \"i\"))` indicates which side of guide legends should be\n#' collected for the plot. If `NULL`, no guide legends will be collected.\n#' @return\n#' - `free_guide`: A modified version of `plot` with a `free_guide` class.\n#' @export\n#' @rdname free\nfree_guide <- function(plot, guides = \"tlbr\") {\n UseMethod(\"free_guide\")\n}\n\n#' @export\nfree_guide.ggplot <- function(plot, guides = \"tlbr\") {\n if (!is.null(guides)) assert_guides(guides)\n attr(plot, \"free_guides\") <- guides\n add_class(plot, \"free_guide\")\n}\n\n#' @export\nfree_guide.alignpatches <- free_guide.ggplot\n\n#' @export\nfree_guide.free_guide <- function(plot, guides = \"tlbr\") {\n if (is.null(guides)) {\n attr(plot, \"free_guides\") <- NULL\n } else {\n assert_guides(guides)\n if (is.null(old <- attr(plot, \"free_guides\", exact = TRUE))) {\n attr(plot, \"free_guides\") <- guides\n } else {\n attr(plot, \"free_guides\") <- union_position(old, guides)\n }\n }\n plot\n}\n\n################################################################\n#' @importFrom ggplot2 ggproto ggproto_parent\n#' @export\nalignpatch.free_guide <- function(x) {\n Parent <- NextMethod()\n if (!is.null(free_guides <- attr(x, \"free_guides\", exact = TRUE))) {\n free_guides <- setup_guides(free_guides)\n }\n ggproto(\"PatchFreeGuide\", Parent,\n set_guides = function(self, guides) free_guides\n )\n}\n"], ["/ggalign/R/tune.R", "#' Change the shape of the input object\n#'\n#' @param data An R object.\n#' @param shape Usually `NULL` or a string, specifying the new shape for the\n#' object. Refer to the detailed method for allowed values.\n#' @details\n#' In most cases, [`fortify_matrix()`] or [`fortify_data_frame()`] provide full\n#' support for transforming objects. However, some objects may require two\n#' completely different approaches to be fortified. The `tune` function acts as\n#' a helper to create a new class tailored for these objects.\n#' @eval rd_collect_family(\"tune\", \"`tune` method collections\")\n#' @export\ntune <- function(data, shape = NULL) UseMethod(\"tune\")\n\n#' @inherit tune title\n#' @description\n#' - `new_tune`: Creates a new object by wrapping it in a scalar list with\n#' the specified attributes and class.\n#' - `tune_data`: Retrieves the original input data.\n#'\n#' @param x An R object.\n#' @param ... Additional attributes passed to [`structure()`].\n#' @param class A character vector specifying the class name to be added.\n#' @export\nnew_tune <- function(x, ..., class = character()) {\n structure(list(x), ..., class = c(class, \"ggalign_tune\"))\n}\n\n#' @export\n#' @rdname new_tune\ntune_data <- function(x) .subset2(x, 1L)\n\n#' @export\nprint.ggalign_tune <- function(x, ...) {\n print(tune_data(x))\n invisible(x)\n}\n\n#' @export\nfortify_matrix.ggalign_tune <- function(data, ...) {\n cli_abort(\"No {.fn fortify_matrix} method for {.obj_type_friendly {data}}\")\n}\n\n#' @export\nfortify_data_frame.ggalign_tune <- function(data, ...) {\n cli_abort(\n \"No {.fn fortify_data_frame} method for {.obj_type_friendly {data}}\"\n )\n}\n"], ["/ggalign/R/scheme-.R", "new_schemes <- function(...) {\n default <- list(\n new_scheme_data(),\n new_scheme_align(),\n new_scheme_theme()\n )\n names(default) <- vapply(default, ggalign_scheme_name,\n character(1L),\n USE.NAMES = FALSE\n )\n for (i in seq_len(...length())) {\n scheme <- ...elt(i)\n default[[ggalign_scheme_name(scheme)]] <- scheme\n }\n default\n}\n\nnew_scheme <- function(name, data, ..., class = character()) {\n structure(data,\n `__ggalign.scheme_name__` = name, ...,\n class = c(class, \"ggalign_scheme\")\n )\n}\n\nggalign_scheme_name <- function(x) {\n attr(x, \"__ggalign.scheme_name__\", exact = TRUE)\n}\n\n#' @importFrom ggplot2 theme\ndefault_schemes <- function(data = NULL, th = theme()) {\n if (!is.waive(data)) data <- NULL\n new_schemes(\n new_scheme_data(data),\n new_scheme_theme(th)\n )\n}\n\n###############################################################\n#' Used to update global data\n#' @noRd\nupdate_scheme <- function(new, old, object_name) {\n UseMethod(\"update_scheme\", old)\n}\n\n#' @export\nupdate_scheme.default <- function(new, old, object_name) new\n\nupdate_layout_scheme <- function(object, layout, object_name) {\n name <- ggalign_scheme_name(object)\n layout@schemes[name] <- list(update_scheme(\n object, .subset2(layout@schemes, name), object_name\n ))\n layout\n}\n\n###############################################################\ninherit_scheme <- function(scheme, pscheme) {\n UseMethod(\"inherit_scheme\", pscheme)\n}\n\n# If no parent scheme, use child scheme directly\n#' @export\ninherit_scheme.NULL <- function(scheme, pscheme) scheme\n\ninherit_schemes <- function(schemes, pschemes) {\n nms <- vapply(pschemes,\n ggalign_scheme_name, character(1L),\n USE.NAMES = FALSE\n )\n ans <- lapply(nms, function(opt) {\n inherit_scheme(.subset2(schemes, opt), .subset2(pschemes, opt))\n })\n names(ans) <- nms\n ans\n}\n\n###############################################################\nplot_add_scheme <- function(plot, scheme) UseMethod(\"plot_add_scheme\", scheme)\n\n#' @export\nplot_add_scheme.NULL <- function(plot, scheme) plot\n\nplot_add_schemes <- function(plot, schemes) {\n for (i in seq_along(schemes)) {\n plot <- plot_add_scheme(plot, scheme = .subset2(schemes, i))\n }\n plot\n}\n"], ["/ggalign/R/import-standalone-purrr.R", "# Standalone file: do not edit by hand\n# Source: \n# ----------------------------------------------------------------------\n#\n# ---\n# repo: Yunuuuu/standalone\n# file: standalone-purrr.R\n# last-updated: 2024-11-13\n# license: https://unlicense.org\n# ---\n\n# This file provides a minimal shim to provide a purrr-like API on top of\n# base R functions. They are not drop-in replacements but allow a similar style\n# of programming.\n#\n# Note: these functions won't support lambda syntax.\n\n# ## Changelog\n# 2024-11-13:\n# rename `transpose()` to `list_transpose()`\n#\n# 2024-11-12:\n# First release\n#\n# nocov start\n\nmap <- function(.x, .f, ...) lapply(.x, .f, ...)\n\nwalk <- function(.x, .f, ...) {\n lapply(.x, .f, ...)\n invisible(.x)\n}\n\nmap_lgl <- function(.x, .f, ...) {\n vapply(X = .x, FUN = .f, logical(1L), ...)\n}\n\nmap_int <- function(.x, .f, ...) {\n vapply(X = .x, FUN = .f, integer(1L), ...)\n}\n\nmap_dbl <- function(.x, .f, ...) {\n vapply(X = .x, FUN = .f, double(1L), ...)\n}\n\nmap_chr <- function(.x, .f, ...) {\n vapply(X = .x, FUN = .f, character(1L), ...)\n}\n\npmap <- function(.l, .f, ...) {\n out <- .mapply(.f, .l, list(...))\n if (!is.null(nms <- names(.subset2(.l, 1L)))) names(out) <- nms\n out\n}\n\npmap_lgl <- function(.l, .f, ...) {\n .purrr_pmap_mold(.l, .f, ..., mold = logical(1L))\n}\n\npmap_int <- function(.l, .f, ...) {\n .purrr_pmap_mold(.l, .f, ..., mold = integer(1L))\n}\n\npmap_dbl <- function(.l, .f, ...) {\n .purrr_pmap_mold(.l, .f, ..., mold = double(1L))\n}\n\npmap_chr <- function(.l, .f, ...) {\n .purrr_pmap_mold(.l, .f, ..., mold = character(1L))\n}\n\n.purrr_pmap_mold <- function(.l, .f, ..., mold) {\n nms <- names(.subset2(.l, 1L))\n dots <- list(...)\n out <- vapply(seq_along(nms), function(i) {\n do.call(.f, args = c(lapply(.l, .subset2, i), dots))\n }, mold, USE.NAMES = FALSE)\n if (!is.null(nms)) names(out) <- nms\n out\n}\n\nmap2 <- function(.x, .y, .f, ...) pmap(list(.x, .y), .f, ...)\n\nmap2_lgl <- function(.x, .y, .f, ...) {\n .purrr_pmap_mold(list(.x, .y), .f, ..., mold = logical(1L))\n}\n\nmap2_int <- function(.x, .y, .f, ...) {\n .purrr_pmap_mold(list(.x, .y), .f, ..., mold = integer(1L))\n}\n\nmap2_dbl <- function(.x, .y, .f, ...) {\n .purrr_pmap_mold(list(.x, .y), .f, ..., mold = double(1L))\n}\n\nmap2_chr <- function(.x, .y, .f, ...) {\n .purrr_pmap_mold(list(.x, .y), .f, ..., mold = character(1L))\n}\n\nimap <- function(.x, .f, ...) {\n nms <- names(.x)\n if (is.null(nms)) {\n .l <- list(.x, seq_along(.x))\n } else {\n .l <- list(.x, nms)\n }\n pmap(.l, .f, ...)\n}\n\n.purrr_imap_mold <- function(.x, .f, ..., mold) {\n if (is.null(nms <- names(.x))) {\n .l <- list(.x, seq_along(.x))\n } else {\n .l <- list(.x, nms)\n }\n .purrr_pmap_mold(.l, .f, ..., mold = mold)\n}\n\nimap_lgl <- function(.l, .f, ...) {\n .purrr_imap_mold(.l, .f, ..., mold = logical(1L))\n}\n\nimap_int <- function(.l, .f, ...) {\n .purrr_imap_mold(.l, .f, ..., mold = integer(1L))\n}\n\nimap_dbl <- function(.l, .f, ...) {\n .purrr_imap_mold(.l, .f, ..., mold = double(1L))\n}\n\nimap_chr <- function(.l, .f, ...) {\n .purrr_imap_mold(.l, .f, ..., mold = character(1L))\n}\n\nlist_transpose <- function(.l) {\n if (!length(.l)) return(.l) # styler: off\n inner_names <- names(.subset2(.l, 1L))\n if (is.null(inner_names)) {\n fields <- seq_along(.subset2(.l, 1L))\n } else {\n fields <- inner_names\n names(fields) <- fields\n .l <- lapply(.l, function(x) {\n if (is.null(names(x))) names(x) <- inner_names # styler: off\n x\n })\n }\n\n # This way missing fields are subsetted as `NULL` instead of causing\n # an error\n .l <- lapply(.l, as.list)\n\n lapply(fields, function(i) lapply(.l, .subset2, i))\n}\n\n# nocov end\n"], ["/ggalign/R/utils-rd.R", "rd_layout <- function() {\n sprintf(\"%s or [`stack_layout()`] object\", rd_quad())\n}\n\nrd_quad <- function() \"[`quad_layout()`]/[`ggheatmap()`]\"\n\nrd_chain_what <- function() {\n paste(\n \"A single number or string of the plot elements in the layout.\",\n \"If `NULL`, will remove any active context\"\n )\n}\n\nrd_quad_position <- function(action) {\n sprintf(\n \"A string of %s indicates which annotation stack should be %s\",\n oxford_or(.TLBR),\n action\n )\n}\n\nrd_layout_data <- function() {\n paste(\n \"Default dataset to use for the layout. If not specified, it must be\",\n \"supplied in each plot added to the layout\"\n )\n}\n\nrd_gg_aesthetics <- function(...) {\n ans <- ggfun(\"rd_aesthetics\")(...)\n ans <- sub(\"link[=\", \"link[ggplot2:\", ans, fixed = TRUE)\n sub(\"(vignette\\\\([^)]+)\\\\)\", \"\\\\1, package = \\\"ggplot2\\\")\", ans)\n}\n"], ["/ggalign/R/craft-cross-none.R", "#' Reset layout ordering and panel group\n#'\n#' @param data The dataset to use for the layout. By default,\n#' [`fortify_matrix()`] will convert the data to a matrix. This argument\n#' allows you to change the layout data. If not specified, the original data\n#' will be used.\n#' @param ... <[dyn-dots][rlang::dyn-dots]> Additional arguments passed to\n#' [`fortify_matrix()`].\n#' @param inherit_index A boolean value indicating whether to inherit the\n#' ordering index. If `TRUE`, will match the layout ordering index with the\n#' data names.\n#' @param inherit_panel A boolean value indicating whether to inherit the\n#' panel group. If `TRUE`, will match the layout panel with the data names.\n#' @param inherit_nobs A boolean value indicating whether to inherit the\n#' number of observations (nobs). If `TRUE`, the `data` input must be\n#' compatible with the layout data.\n#' @export\ncross_none <- function(data = waiver(), ...,\n inherit_index = NULL,\n inherit_panel = NULL,\n inherit_nobs = NULL) {\n cross(CrossNone,\n data = data, data_params = list2(...), plot = NULL,\n active = new_active(use = FALSE),\n schemes = default_schemes(),\n inherit_index = inherit_index,\n inherit_panel = inherit_panel,\n inherit_nobs = inherit_nobs\n )\n}\n\n#' @importFrom ggplot2 ggproto ggproto_parent\n#' @include craft-cross-.R\nCrossNone <- ggproto(\"CrossNone\", CraftCross)\n"], ["/ggalign/R/layout-quad-operator.R", "# `subtract` operates at layout-level\n#' @keywords internal\nquad_layout_subtract <- function(object, quad, object_name) {\n UseMethod(\"quad_layout_subtract\")\n}\n\n#' @export\nquad_layout_subtract.default <- function(object, quad, object_name) {\n if (is.null(context <- quad@active)) context <- c(.TLBR, list(NULL))\n for (active in context) {\n if (is.null(active)) {\n quad <- quad_body_add(object, quad, object_name)\n } else if (!is.null(slot(quad, active))) {\n slot(quad, active) <- chain_layout_subtract(\n object, slot(quad, active), object_name\n )\n }\n }\n quad\n}\n\n# for object can set at layout level\n#' @export\nquad_layout_subtract.ggalign_scheme <- function(object, quad, object_name) {\n if (is.null(context <- quad@active)) {\n quad <- update_layout_scheme(object, quad, object_name)\n } else {\n slot(quad, context) <- update_layout_scheme(\n object, slot(quad, context), object_name\n )\n }\n quad\n}\n\n#' @export\nquad_layout_subtract.ggalign_with_quad <- function(object, quad, object_name) {\n old <- quad@active\n context <- quad_operated_context(object, old, \"-\")\n object <- .subset2(object, \"object\")\n object_name <- .subset2(object, \"object_name\")\n # `subtract` operates at layout-level\n if (is.null(context)) {\n quad@active <- context\n quad <- quad_layout_subtract(object, quad, object_name)\n } else {\n for (active in context) {\n if (is.null(active)) {\n quad <- quad_body_add(object, quad, object_name)\n } else if (!is.null(slot(quad, active))) {\n slot(quad, active) <- chain_layout_subtract(\n object, slot(quad, active), object_name\n )\n }\n }\n }\n quad@active <- old\n quad\n}\n\n###############################################################\n#' @keywords internal\nquad_layout_and_add <- function(object, quad, object_name) {\n UseMethod(\"quad_layout_and_add\")\n}\n\n#' @export\nquad_layout_and_add.default <- function(object, quad, object_name) {\n quad <- quad_body_add(object, quad, object_name)\n for (position in .TLBR) {\n stack <- slot(quad, position)\n if (is.null(stack)) next\n slot(quad, position) <- chain_layout_and_add(\n object, stack, object_name\n )\n }\n quad\n}\n\n#' @export\nquad_layout_and_add.ggalign_with_quad <- function(object, quad, object_name) {\n object <- .subset2(object, \"object\")\n object_name <- .subset2(object, \"object_name\")\n NextMethod()\n}\n\n#' @export\nquad_layout_and_add.theme <- function(object, quad, object_name) {\n ans <- NextMethod()\n # to align with `patchwork`, we also modify the layout theme\n # when using `&` to add the theme object.\n ans@theme <- ggfun(\"add_theme\")(ans@theme, object)\n ans\n}\n"], ["/ggalign/R/object-name.R", "format_object_name <- function(name, format = NULL) {\n if (is.null(format)) {\n name\n } else {\n sprintf(\"{.%s %s}\", format, name)\n }\n}\n\nobject_name <- function(object, format) UseMethod(\"object_name\")\n\n#' @export\nobject_name.StackLayout <- function(object, format = \"fn\") {\n ans <- format_object_name(object@name, format)\n if (!is.null(position <- .subset2(object@heatmap, \"position\"))) {\n ans <- sprintf(\"the %s annotation %s\", position, ans)\n } else {\n ans <- sprintf(\"the %s %s\", object@direction, ans)\n }\n ans\n}\n\n#' @export\nobject_name.CircleLayout <- function(object, format = \"fn\") {\n format_object_name(object@name, format)\n}\n\n#' @export\nobject_name.QuadLayout <- function(object, format = \"fn\") {\n format_object_name(object@name, format)\n}\n\n#' @export\nobject_name.CraftBox <- function(object, format = \"fn\") {\n object_name(object@craftsman, format)\n}\n\n#' @export\nobject_name.Craftsman <- function(object, format = \"fn\") {\n format_object_name(snake_class(object), format)\n}\n\n#' @export\nobject_name.AlignGg <- function(object, format = \"fn\") {\n format_object_name(\"ggalign\", format)\n}\n\n#' @export\nobject_name.CrossGg <- function(object, format = \"fn\") {\n format_object_name(\"ggcross\", format)\n}\n\n#' @export\nobject_name.FreeGg <- function(object, format = \"fn\") {\n format_object_name(\"ggfree\", format)\n}\n\n#' @export\nobject_name.MarkGg <- function(object, format = \"fn\") {\n format_object_name(\"ggmark\", format)\n}\n"], ["/ggalign/R/craft-align-kmeans.R", "#' Split observations by k-means clustering groups.\n#'\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' Aligns and groups observations based on k-means clustering, enabling\n#' observation splits by cluster groups.\n#'\n#' @inheritDotParams stats::kmeans -x -centers\n#' @param data A numeric matrix to be used by k-means. By default, it will\n#' inherit from the layout matrix.\n#' @inheritParams align\n#' @inheritSection align Discrete Axis Alignment\n#' @examples\n#' ggheatmap(matrix(rnorm(81), nrow = 9)) +\n#' anno_top() +\n#' align_kmeans(3L)\n#' @importFrom rlang list2\n#' @export\nalign_kmeans <- function(..., data = NULL, active = NULL) {\n assert_active(active)\n active <- update_active(active, new_active(use = FALSE))\n align(\n align = AlignKmeans,\n params = list2(...),\n active = active,\n data = data\n )\n}\n\n#' @importFrom ggplot2 ggproto\n#' @importFrom rlang inject\nAlignKmeans <- ggproto(\"AlignKmeans\", CraftAlign,\n interact_layout = function(self, layout) {\n ggproto_parent(AlignOrder2, self)$interact_layout(layout)\n },\n compute = function(self, panel, index) {\n inject(stats::kmeans(x = self$data, !!!self$params))\n },\n align = function(self, panel, index) {\n list(.subset2(self$statistics, \"cluster\"), index)\n },\n summary_align = function(self) c(FALSE, TRUE)\n)\n"], ["/ggalign/R/ggalign-package.R", "#' @keywords internal\n\"_PACKAGE\"\n\n## usethis namespace: start\n#' @import vctrs\n#' @importFrom lifecycle deprecated\n#' @importFrom rlang .data .env\n#' @importFrom cli cli_abort cli_warn cli_inform\n## usethis namespace: end\nNULL\n\n# enable usage of @name in package code\n#' @rawNamespace if (getRversion() < \"4.3.0\") importFrom(\"S7\", \"@\")\nNULL\n"], ["/ggalign/R/rasterise.R", "rasterise.QuadLayout <- function(input, ...) {\n input@plot <- ggrastr::rasterise(input = input@plot, ...)\n for (position in .TLBR) {\n stack <- slot(input, position)\n if (is.null(stack)) next\n slot(input, position) <- ggrastr::rasterise(input = stack, ...)\n }\n input\n}\n\nrasterise.ChainLayout <- function(input, ...) {\n input@plot_list <- lapply(input@plot_list, ggrastr::rasterise, ...)\n input\n}\n\nrasterise.CraftBox <- function(input, ...) {\n if (!is.null(plot <- input@plot)) {\n input@plot <- ggrastr::rasterise(input = plot, ...)\n }\n input\n}\n\n##########################################################\n#' @export\nraster_magick0.QuadLayout <- function(x, ...) {\n x@plot <- raster_magick0(x = x@plot, ...)\n for (position in .TLBR) {\n stack <- slot(x, position)\n if (is.null(stack)) next\n slot(x, position) <- raster_magick0(x = stack, ...)\n }\n x\n}\n\n#' @export\nraster_magick0.ChainLayout <- function(x, ...) {\n x@plot_list <- lapply(x@plot_list, raster_magick0, ...)\n x\n}\n\n\n#' @export\nraster_magick0.CraftBox <- function(x, ...) {\n if (!is.null(plot <- input@plot)) {\n input@plot <- raster_magick0(x = plot, ...)\n }\n input\n}\n"], ["/ggalign/R/zzz.R", "#' @importFrom S7 methods_register\n.onLoad <- function(libname, pkgname) {\n # register ggplot2 theme elements\n theme_elements()\n\n # register method for\n s3_register(\"ggrastr::rasterise\", \"CraftBox\")\n s3_register(\"ggrastr::rasterise\", \"QuadLayout\")\n s3_register(\"ggrastr::rasterise\", \"ChainLayout\")\n\n methods_register()\n invisible()\n}\n"]], "task_instance_info": {"created_time": "2025-08-21 01:14:33", "created_task_model": "DeepSeek-R1", "function_skeleton": "function(data, arg = caller_arg(data),\n call = caller_call()) {}", "code_description": "This code segment functions to: Validate input data against allowed types and handle functional conversions while generating appropriate error messages for non-compliant cases."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```r\n[TASK_BEGIN]\ncheck_scheme_data <- function(data, arg = caller_arg(data),\n call = caller_call()) {\n if (!inherits(data, \"scheme_data\")) {\n cli_abort(\n \"{.arg {arg}} must be created with {.fn scheme_data}\",\n call = call\n )\n }\n data\n}\n[TASK_END]\n```", "inference_time": "2025-08-21 01-14-58"}, "editdistance_info": {"edit_distance": 44.7059, "calculate_time": "2025-08-21 01:14:58", "true_code_clean": "function(data, arg = caller_arg(data),\n call = caller_call()) {\n if (!is.waive(data) && !is.null(data) &&\n !is.function(data <- allow_lambda(data))) {\n cli_abort(paste(\n \"{.arg {arg}} must be a function,\",\n \"{.code NULL} or {.fn waiver}\"\n ), call = call)\n }\n data\n}", "predict_code_clean": "check_scheme_data <- function(data, arg = caller_arg(data),\n call = caller_call()) {\n if (!inherits(data, \"scheme_data\")) {\n cli_abort(\n \"{.arg {arg}} must be created with {.fn scheme_data}\",\n call = call\n )\n }\n data\n}"}} {"repo_name": "ggalign", "file_name": "/ggalign/R/craft-align-group.R", "inference_info": {"prefix_code": "#' Group and align observations based on a group vector\n#'\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' Splits observations into groups, with slice ordering based on group levels.\n#'\n#' @param group A character define the groups of the observations.\n#' @inheritParams align\n#' @examples\n#' set.seed(1L)\n#' small_mat <- matrix(rnorm(81), nrow = 9)\n#' ggheatmap(small_mat) +\n#' anno_top() +\n#' align_group(sample(letters[1:4], ncol(small_mat), replace = TRUE))\n#' @export\nalign_group <- function(group, active = NULL) {\n assert_active(active)\n if (vec_size(group) == 0L) {\n cli_abort(\"{.arg group} cannot be empty\")\n }\n active <- update_active(active, new_active(use = FALSE))\n align(\n align = AlignGroup,\n group = group,\n active = active,\n check.param = TRUE\n )\n}\n\n#' @importFrom ggplot2 ggproto\nAlignGroup <- ggproto(\"AlignGroup\", CraftAlign,\n interact_layout = ", "suffix_code": ",\n align = function(self, panel, index) list(self$group, index),\n summary_align = function(self) c(FALSE, TRUE)\n)\n", "middle_code": "function(self, layout) {\n layout <- ggproto_parent(CraftAlign, self)$interact_layout(layout)\n if (is.null(layout_nobs <- .subset2(layout@design, \"nobs\"))) {\n layout@design[\"nobs\"] <- list(vec_size(self$group))\n } else {\n assert_mismatch_nobs(\n self, layout_nobs, vec_size(self$group),\n arg = \"group\"\n )\n }\n layout\n }", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "r", "sub_task_type": null}, "context_code": [["/ggalign/R/craft-align-order.R", "#' Order observations based on weights\n#'\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' Ordering observations based on summary weights or a specified ordering\n#' character or integer index.\n#'\n#' @param weights A summary function which accepts a data and returns the\n#' weights for each observations. Alternatively, you can provide an ordering\n#' index as either an integer or a character. Since characters have been\n#' designated as character indices, if you wish to specify a function name as a\n#' string, you must enclose it with [`I()`].\n#' @param ... <[dyn-dots][rlang::dyn-dots]> Additional arguments passed to\n#' function provided in `weights` argument.\n#' @param reverse A boolean value. Should the sort order be in reverse?\n#' @param strict A boolean value indicates whether the order should be strict.\n#' If previous groups has been established, and strict is `FALSE`, this will\n#' reorder the observations in each group.\n#' @param data A `matrix`, `data frame`, or atomic vector used as the input for\n#' the `weights` function. Alternatively, you can specify a `function`\n#' (including purrr-like lambda syntax) that will be applied to the layout\n#' matrix, transforming it as necessary for weight calculations. By default, it\n#' will inherit from the layout matrix.\n#' @inheritParams align\n#' @inheritSection align Discrete Axis Alignment\n#' @examples\n#' ggheatmap(matrix(rnorm(81), nrow = 9)) +\n#' anno_left() +\n#' align_order(I(\"rowMeans\"))\n#' @importFrom ggplot2 waiver\n#' @importFrom rlang list2\n#' @export\nalign_order <- function(weights = rowMeans, ...,\n reverse = FALSE, strict = TRUE, data = NULL,\n active = NULL) {\n if (is.numeric(weights) ||\n (is.character(weights) && !inherits(weights, \"AsIs\"))) {\n # vec_duplicate_any is slight faster than `anyDuplicated`\n if (vec_any_missing(weights) || vec_duplicate_any(weights)) {\n cli_abort(paste(\n \"{.arg weights} must be an ordering numeric or character\",\n \"without missing value or ties\"\n ))\n } else if (is.numeric(weights)) {\n weights <- vec_cast(weights, integer())\n }\n if (vec_size(weights) == 0L) {\n cli_abort(\"{.arg weights} cannot be empty\")\n }\n if (!is.null(data)) {\n cli_warn(c(\n \"{.arg data} won't be used\",\n i = \"{.arg weights} is not a {.cls function}\"\n ))\n }\n } else {\n weights <- rlang::as_function(weights)\n data <- data %||% waiver()\n }\n assert_bool(strict)\n assert_bool(reverse)\n assert_active(active)\n active <- update_active(active, new_active(use = FALSE))\n align(\n align = AlignOrder,\n weights = weights,\n params = list2(...),\n reverse = reverse,\n strict = strict,\n active = active,\n data = data\n )\n}\n\n#' @importFrom ggplot2 ggproto\n#' @importFrom rlang inject is_atomic\nAlignOrder <- ggproto(\"AlignOrder\", CraftAlign,\n interact_layout = function(self, layout) {\n if (is.function(self$weights)) {\n layout <- ggproto_parent(AlignOrder2, self)$interact_layout(layout)\n } else {\n layout <- ggproto_parent(CraftAlign, self)$interact_layout(layout)\n if (is.null(layout_nobs <- .subset2(layout@design, \"nobs\"))) {\n layout@design[\"nobs\"] <- list(vec_size(self$weights))\n } else {\n assert_mismatch_nobs(\n self, layout_nobs, vec_size(self$weights),\n arg = \"weights\"\n )\n }\n self$labels <- vec_names(layout@data)\n }\n layout\n },\n compute = function(self, panel, index) {\n if (is.function(self$weights)) {\n ans <- inject(self$weights(self$data, !!!self$params))\n if (!is_atomic(ans)) {\n cli_abort(\n \"{.arg weights} must return an atomic weights\",\n call = self$call\n )\n }\n assert_mismatch_nobs(\n self, vec_size(ans), vec_size(ans),\n arg = \"weights\"\n )\n ans\n }\n },\n align = function(self, panel, index) {\n if (is.function(self$weights)) {\n index <- order(self$statistics)\n } else {\n index <- vec_as_location(\n self$weights,\n n = vec_size(self$weights),\n names = self$labels,\n missing = \"error\",\n call = self$call\n )\n }\n if (self$reverse) index <- rev(index)\n assert_reorder(self, panel, index, self$strict)\n list(panel, index)\n },\n summary_align = function(self) c(TRUE, FALSE)\n)\n"], ["/ggalign/R/ggmark.R", "#' Add a plot to annotate selected observations\n#'\n#' @param mark A [`mark_draw()`] object to define how to draw the links. Like\n#' [`mark_line()`], [`mark_tetragon()`]. Note the names of the pair links will\n#' be used to define the panel names so must be unique.\n#' @inheritParams ggalign\n#' @param group1,group2 A single boolean value indicating whether to use the\n#' panel group information from the layout as the paired groups. By default,\n#' if no specific observations are selected in `mark`, `ggmark()` will\n#' automatically connect all observations and group them according to the\n#' layout's defined groups.\n#' @param obs_size A single numeric value that indicates the size of a single\n#' observation, ranging from `(0, 1]`.\n#' @section ggplot2 specification:\n#' `ggmark` initializes a ggplot object. The underlying data is created using\n#' [`fortify_data_frame()`]. Please refer to it for more details.\n#'\n#' In addition, the following columns will be added to the data frame:\n#'\n#' - `.panel`: the panel for the aligned axis. It means `x-axis` for vertical\n#' stack layout (including top and bottom annotation), `y-axis` for\n#' horizontal stack layout (including left and right annotation).\n#'\n#' - `.names` ([`vec_names()`][vctrs::vec_names]) and `.index`\n#' ([`vec_size()`][vctrs::vec_size()]/[`NROW()`]): a character names (only\n#' applicable when names exists) and an integer of index of the original\n#' data.\n#'\n#' - `.hand`: A factor with levels `c(\"left\", \"right\")` for horizontal stack\n#' layouts, or `c(\"top\", \"bottom\")` for vertical stack layouts, indicating\n#' the position of the linked observations.\n#'\n#' @examples\n#' set.seed(123)\n#' small_mat <- matrix(rnorm(56), nrow = 7)\n#' rownames(small_mat) <- paste0(\"row\", seq_len(nrow(small_mat)))\n#' colnames(small_mat) <- paste0(\"column\", seq_len(ncol(small_mat)))\n#'\n#' # mark_line\n#' ggheatmap(small_mat) +\n#' theme(axis.text.x = element_text(hjust = 0, angle = -60)) +\n#' anno_right() +\n#' align_kmeans(3L) +\n#' ggmark(mark_line(I(1:3) ~ NULL)) +\n#' geom_boxplot(aes(.names, value)) +\n#' theme(plot.margin = margin(l = 0.1, t = 0.1, unit = \"npc\"))\n#'\n#' # mark_tetragon\n#' ggheatmap(small_mat) +\n#' theme(axis.text.x = element_text(hjust = 0, angle = -60)) +\n#' anno_right() +\n#' align_kmeans(3L) +\n#' ggmark(mark_tetragon(I(1:3) ~ NULL)) +\n#' geom_boxplot(aes(.names, value)) +\n#' theme(plot.margin = margin(l = 0.1, t = 0.1, unit = \"npc\"))\n#' @importFrom rlang list2\n#' @export\nggmark <- function(mark, data = waiver(), mapping = aes(), ...,\n group1 = NULL, group2 = NULL,\n obs_size = 1, size = NULL, active = NULL) {\n if (!inherits(mark, \"ggalign_mark_draw\")) {\n cli_abort(\"{.arg mark} must be a {.fn mark_draw} object\")\n }\n assert_obs_size(obs_size)\n assert_active(active)\n active <- update_active(active, new_active(use = TRUE))\n assert_bool(group1, allow_null = TRUE)\n assert_bool(group2, allow_null = TRUE)\n new_craftbox(\n MarkGg,\n # fields added to `MarkGg`\n input_data = allow_lambda(data), # used by AlignGg\n params = list2(...), # used by AlignGg\n mark = mark, # used by MarkGg\n group1 = group1, group2 = group2,\n obs_size = obs_size,\n\n # slot\n plot = ggplot(mapping = mapping),\n size = size,\n schemes = default_schemes(data, th = theme_panel_border()),\n active = active\n )\n}\n\n#' @importFrom ggplot2 ggproto ggplot margin element_rect\nMarkGg <- ggproto(\"MarkGg\", Craftsman,\n free_facet = TRUE,\n free_limits = TRUE,\n interact_layout = function(self, layout) {\n layout_name <- self$layout_name\n if (!self$in_linear) { # only used for linear coordinate\n cli_abort(c(\n sprintf(\n \"Cannot add %s to %s\",\n object_name(self), layout_name\n ),\n i = sprintf(\n \"%s can only be used in linear layout\",\n object_name(self)\n )\n ))\n }\n if (is_layout_continuous(layout)) { # only used for discrete variable\n # ggmark special for discrete variables\n cli_abort(c(\n sprintf(\"Cannot add %s to %s\", object_name(self), layout_name),\n i = sprintf(\"%s cannot align discrete variables\", layout_name)\n ))\n }\n ans <- ggproto_parent(AlignGg, self)$interact_layout(layout)\n self$labels0 <- self$labels # CrossMark uses `labels0`\n ans\n },\n build_plot = function(self, plot, design, extra_design = NULL,\n previous_design = NULL) {\n if (is.null(.subset2(design, \"nobs\"))) {\n cli_abort(sprintf(\n \"you must initialize %s before drawing %s\",\n self$layout_name, object_name(self)\n ), call = self$call)\n }\n mark <- self$mark\n\n # parse links --------------------------------------------\n links <- .subset2(mark, \"links\")\n group1 <- self$group1\n group2 <- self$group2\n position <- self$position\n if (is_empty(links) && is.null(group1) && is.null(group2)) {\n # guess group1 and group2 from position\n if (is.null(position)) { # a normal stack layout\n group1 <- TRUE\n } else if (any(position == c(\"top\", \"left\"))) {\n group2 <- TRUE\n } else {\n group1 <- TRUE\n }\n }\n full_data <- split(\n seq_len(.subset2(design, \"nobs\")),\n .subset2(design, \"panel\")\n )\n if (isTRUE(group1) && isTRUE(group2)) {\n extra_links <- mapply(function(l1, l2) {\n new_pair_link(I(l1), I(l2))\n }, full_data, full_data, SIMPLIFY = FALSE)\n } else if (isTRUE(group1)) {\n extra_links <- lapply(full_data, function(l) {\n new_pair_link(hand1 = I(l))\n })\n } else if (isTRUE(group2)) {\n extra_links <- lapply(full_data, function(l) {\n new_pair_link(hand2 = I(l))\n })\n } else {\n extra_links <- NULL\n }\n\n # unlock the object\n self$unlock()\n self$mark$links <- vec_c(extra_links, links)\n on.exit(self$mark <- mark, add = TRUE) # restore the original `mark`\n on.exit(self$lock(), add = TRUE)\n\n # setup the plot\n plot <- ggproto_parent(CrossMark, self)$build_plot(\n plot,\n design,\n extra_design,\n previous_design %||% design\n )\n plot_data <- plot$data\n\n # prepare data for the plot ------------------------------\n if (!is.null(data <- self$data)) {\n plot_data <- inner_join(plot_data, data, by = \".index\")\n }\n gguse_data(plot, ggalign_data_restore(plot_data, data))\n },\n finish_plot = function(self, plot, schemes, theme) {\n ggproto_parent(CrossMark, self)$finish_plot(plot, schemes, theme)\n },\n summary = function(self, plot) {\n header <- ggproto_parent(Craftsman, self)$summary(plot)\n c(header, \" Add plot to annotate observations\")\n }\n)\n"], ["/ggalign/R/craft-align-order2.R", "#' Reorders layout observations based on specific statistics.\n#'\n#' @details\n#' `r lifecycle::badge('experimental')`\n#'\n#' The `align_order2()` function differs from `align_order()` in that the\n#' `weights` argument in `align_order()` must return atomic weights for each\n#' observation. In contrast, the `stat` argument in `align_order2()` can\n#' return more complex structures, such as [hclust][stats::hclust] or\n#' [dendrogram][stats::as.dendrogram], among others.\n#'\n#' Typically, you can achieve the functionality of `align_order2()` using\n#' `align_order()` by manually extracting the ordering information from\n#' the statistic.\n#'\n#' @param stat A statistical function which accepts a data and returns the\n#' statistic, which we'll call [`order2()`] to extract the ordering information.\n#' @param ... <[dyn-dots][rlang::dyn-dots]> Additional arguments passed to\n#' function provided in `stat` argument.\n#' @param data A `matrix`, `data frame`, or atomic vector used as the input for\n#' the `stat` function. Alternatively, you can specify a `function` (including\n#' purrr-like lambda syntax) that will be applied to the layout matrix,\n#' transforming it as necessary for statistic calculations. By default, it will\n#' inherit from the layout matrix.\n#' @inheritParams align_order\n#' @inheritSection align Discrete Axis Alignment\n#' @examples\n#' ggheatmap(matrix(rnorm(81), nrow = 9)) +\n#' anno_left() +\n#' align_order2(hclust2)\n#' @seealso [order2()]\n#' @importFrom ggplot2 waiver\n#' @importFrom rlang list2\n#' @export\nalign_order2 <- function(stat, ..., reverse = FALSE,\n strict = TRUE, data = NULL,\n active = NULL) {\n stat <- rlang::as_function(stat)\n assert_bool(strict)\n assert_bool(reverse)\n assert_active(active)\n active <- update_active(active, new_active(use = FALSE))\n align(\n align = AlignOrder2,\n stat = stat,\n params = list2(...),\n reverse = reverse,\n strict = strict,\n active = active,\n data = data\n )\n}\n\n#' @importFrom ggplot2 ggproto\n#' @importFrom rlang inject\nAlignOrder2 <- ggproto(\"AlignOrder2\", CraftAlign,\n interact_layout = function(self, layout) {\n layout <- ggproto_parent(CraftAlign, self)$interact_layout(layout)\n layout_data <- layout@data\n if (is.null(input_data <- self$input_data) ||\n is.waive(input_data)) { # inherit from the layout\n if (is.null(data <- layout_data)) {\n cli_abort(c(\n sprintf(\n \"you must provide {.arg data} in %s\",\n object_name(self)\n ),\n i = sprintf(\"no data was found in %s\", self$layout_name)\n ))\n }\n } else if (is.function(input_data)) {\n if (is.null(layout_data)) {\n cli_abort(c(\n sprintf(\n \"{.arg data} in %s cannot be a function\",\n object_name(self)\n ),\n i = sprintf(\"no data was found in %s\", self$layout_name)\n ))\n }\n data <- input_data(layout_data)\n } else {\n data <- input_data\n }\n\n design <- layout@design\n layout_nobs <- .subset2(design, \"nobs\")\n\n # we always regard rows as the observations\n if (is.null(layout_nobs)) {\n layout_nobs <- vec_size(data)\n if (layout_nobs == 0L) {\n cli_abort(\"{.arg data} cannot be empty\", call = self$call)\n }\n design[\"nobs\"] <- list(layout_nobs)\n layout@design <- design\n } else if (vec_size(data) != layout_nobs) {\n cli_abort(sprintf(\n \"%s (nobs: %d) is not compatible with the %s (nobs: %d)\",\n object_name, vec_size(data), layout_name, layout_nobs\n ))\n }\n\n # save the labels\n self$labels <- vec_names(data) %||% vec_names(layout_data)\n self$data <- ggalign_data_restore(data, layout_data)\n layout\n },\n compute = function(self, panel, index) {\n inject(self$stat(self$data, !!!self$params))\n },\n align = function(self, panel, index) {\n index <- vec_cast(\n order2(self$statistics), integer(),\n x_arg = \"stat\", call = self$call\n )\n assert_mismatch_nobs(\n self, vec_size(self$data), vec_size(index),\n arg = \"stat\"\n )\n if (self$reverse) index <- rev(index)\n assert_reorder(self, panel, index, self$strict)\n list(panel, index)\n },\n summary_align = function(self) c(TRUE, FALSE)\n)\n\n#' Ordering Permutation\n#'\n#' `order2` returns a permutation which rearranges its first argument into\n#' ascending order.\n#' @param x Any objects can be extracting ordering.\n#' @return An integer vector unless any of the inputs has `2^31` or more\n#' elements, when it is a double vector.\n#' @examples\n#' order2(hclust2(matrix(rnorm(100L), nrow = 10L)))\n#' @export\norder2 <- function(x) UseMethod(\"order2\")\n\n#' @export\n#' @rdname order2\norder2.hclust <- function(x) x$order\n\n#' @importFrom stats order.dendrogram\n#' @export\n#' @rdname order2\norder2.dendrogram <- function(x) order.dendrogram(x)\n\n#' @export\n#' @rdname order2\norder2.ser_permutation_vector <- function(x) {\n rlang::check_installed(\n \"seriation\", \"to extract order from `ser_permutation_vector`\"\n )\n getExportedValue(\"seriation\", \"get_order\")(x)\n}\n\n#' @export\n#' @rdname order2\norder2.ser_permutation <- function(x) {\n rlang::check_installed(\n \"seriation\", \"to extract order from `ser_permutation`\"\n )\n getExportedValue(\"seriation\", \"get_order\")(x)\n}\n\n#' @export\n#' @rdname order2\norder2.phylo <- function(x) {\n second <- x$edge[, 2L, drop = TRUE]\n second[second <= length(x$tip.label)]\n}\n"], ["/ggalign/R/craft-align-hclust.R", "#' Reorder or Group observations based on hierarchical clustering\n#'\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' This function aligns observations within the layout according to a\n#' hierarchical clustering tree, enabling reordering or grouping of elements\n#' based on clustering results.\n#'\n#' @param data A matrix-like object. By default, it inherits from the layout\n#' `matrix`.\n#' @inheritParams align\n#' @inheritParams hclust2\n#' @param reorder_dendrogram A single boolean value indicating whether to\n#' reorder the dendrogram based on the means. Alternatively, you can provide a\n#' custom function that accepts an [`hclust`][stats::hclust] object and the data\n#' used to generate the tree, returning either an [`hclust`][stats::hclust] or\n#' [`dendrogram`][stats::as.dendrogram] object. Default is `FALSE`.\n#' @param reorder_group A single boolean value, indicates whether we should do\n#' Hierarchical Clustering between groups, only used when previous groups have\n#' been established. Default: `FALSE`.\n#' @param k An integer scalar indicates the desired number of groups.\n#' @param h A numeric scalar indicates heights where the tree should be cut.\n#' @param cutree A function used to cut the [`hclust`][stats::hclust] tree. It\n#' should accept four arguments: the [`hclust`][stats::hclust] tree object,\n#' `distance` (only applicable when `method` is a string or a function for\n#' performing hierarchical clustering), `k` (the number of clusters), and `h`\n#' (the height at which to cut the tree). By default,\n#' [`cutree()`][stats::cutree()] is used.\n#' @inheritSection align Discrete Axis Alignment\n#' @seealso [`hclust2()`]\n#' @examples\n#' # align_hclust won't add a dendrogram\n#' ggheatmap(matrix(rnorm(81), nrow = 9)) +\n#' anno_top() +\n#' align_hclust(k = 3L)\n#' @export\nalign_hclust <- function(distance = \"euclidean\",\n method = \"complete\",\n use_missing = \"pairwise.complete.obs\",\n reorder_dendrogram = FALSE,\n reorder_group = FALSE,\n k = NULL, h = NULL, cutree = NULL,\n data = NULL, active = NULL) {\n assert_active(active)\n active <- update_active(active, new_active(use = FALSE))\n .align_hclust(\n align = AlignHclust,\n distance = distance,\n method = method,\n use_missing = use_missing,\n reorder_dendrogram = reorder_dendrogram,\n reorder_group = reorder_group,\n k = k, h = h, cutree = cutree, data = data, active = active\n )\n}\n\n.align_hclust <- function(align, ..., plot = NULL,\n distance = \"euclidean\",\n method = \"complete\",\n use_missing = \"pairwise.complete.obs\",\n reorder_dendrogram = FALSE,\n reorder_group = FALSE,\n k = NULL, h = NULL, cutree = NULL,\n data = NULL, schemes = NULL, active = NULL,\n call = caller_call()) {\n reorder_dendrogram <- allow_lambda(reorder_dendrogram)\n if (!rlang::is_bool(reorder_dendrogram) &&\n !is.null(reorder_dendrogram) &&\n !is.function(reorder_dendrogram)) {\n cli_abort(\n \"{.arg reorder_dendrogram} must be a single boolean value or a function\",\n call = call\n )\n }\n assert_number_whole(k, allow_null = TRUE, call = call)\n assert_number_decimal(h, allow_null = TRUE, call = call)\n assert_bool(reorder_group, call = call)\n cutree <- allow_lambda(cutree)\n assert_(cutree, is.function, \"a function\", allow_null = TRUE, call = call)\n if (inherits(method, \"hclust\")) {\n if (vec_size(.subset2(method, \"order\")) == 0L) {\n cli_abort(\"{.cls hclust} defined in {.arg method} cannot be empty\",\n call = call\n )\n }\n } else if (inherits(method, \"dendrogram\")) {\n if (stats::nobs(method) == 0L) {\n cli_abort(\n \"{.cls dendrogram} defined in {.arg method} cannot be empty\",\n call = call\n )\n }\n }\n\n if (isTRUE(reorder_dendrogram)) {\n reorder_dendrogram <- function(tree, data) {\n if (!inherits(tree, \"dendrogram\")) {\n tree <- stats::as.dendrogram(tree)\n }\n reorder(x = tree, wts = rowMeans(data), agglo.FUN = mean)\n }\n } else if (is.function(reorder_dendrogram)) {\n user_reorder <- reorder_dendrogram\n reorder_dendrogram <- function(tree, data) {\n # we ensure, what we input for user is a `hclust` object.\n if (!inherits(tree, \"hclust\")) tree <- stats::as.hclust(tree)\n ans <- user_reorder(tree, data)\n if (!inherits(ans, \"hclust\") &&\n !inherits(ans, \"dendrogram\")) {\n cli_abort(\n \"{.fn reorder_dendrogram} must return a {.cls hclust} or {.cls dendrogram} object\",\n call = call\n )\n }\n ans\n }\n }\n\n align(\n align = align,\n distance = distance, method = method,\n use_missing = use_missing,\n reorder_dendrogram = reorder_dendrogram,\n reorder_group = reorder_group,\n k = k, h = h, cutree = cutree,\n active = active,\n ..., # additional fields to be added, used by align_dendro\n schemes = schemes %||% default_schemes(),\n data = data,\n plot = plot,\n call = call\n )\n}\n\n#' @importFrom ggplot2 ggproto aes\nAlignHclust <- ggproto(\"AlignHclust\", CraftAlign,\n interact_layout = function(self, layout) {\n if (inherits(self$method, \"hclust\") ||\n inherits(self$method, \"dendrogram\")) {\n layout <- ggproto_parent(CraftAlign, self)$interact_layout(layout)\n if (inherits(self$method, \"hclust\")) {\n nobs <- vec_size(.subset2(self$method, \"order\"))\n } else {\n nobs <- stats::nobs(self$method)\n }\n\n if (is.null(layout_nobs <- .subset2(layout@design, \"nobs\"))) {\n layout@design[\"nobs\"] <- list(nobs)\n } else {\n assert_mismatch_nobs(self, layout_nobs, nobs, arg = \"method\")\n }\n } else {\n layout <- ggproto_parent(AlignOrder2, self)$interact_layout(layout)\n }\n\n # initialize the internal parameters\n self$multiple_tree <- FALSE\n self$height <- NULL\n self$panel <- NULL\n layout\n },\n compute = function(self, panel, index) {\n if (!is.null(self$data) && vec_size(self$data) < 2L) {\n cli_abort(c(\n \"Cannot do Hierarchical Clustering\",\n i = \"must have >= 2 observations to cluster\"\n ), call = self$call)\n }\n\n # if the old panel exist, we do sub-clustering\n if (!is.null(panel) && is.null(self$k) && is.null(self$h) &&\n is.null(self$cutree)) {\n # in this way, we prevent sub-clustering\n if (inherits(self$method, \"hclust\") ||\n inherits(self$method, \"dendrogram\")) {\n cli_abort(\n \"{.arg method} cannot be a {.cls hclust} or {.cls dendrogram} when previous layout panel groups exist\",\n call = self$call\n )\n }\n children <- vector(\"list\", nlevels(panel))\n names(children) <- levels(panel)\n labels <- vec_names(self$data)\n\n # we do clustering within each group ---------------\n for (g in levels(panel)) {\n idx <- which(panel == g)\n gdata <- vec_slice(self$data, idx)\n if (vec_size(gdata) == 1L) {\n children[[g]] <- tree_one_node(idx, .subset(labels, idx))\n } else {\n child <- stats::as.dendrogram(hclust2(\n gdata,\n distance = self$distance,\n method = self$method,\n use_missing = self$use_missing\n ))\n # we restore the actual index of the original matrix\n child <- stats::dendrapply(child, function(x) {\n if (stats::is.leaf(x)) {\n ans <- .subset(idx, x)\n attributes(ans) <- attributes(x)\n ans\n } else {\n x\n }\n })\n if (is.function(self$reorder_dendrogram)) {\n child <- self$reorder_dendrogram(child, gdata)\n }\n children[[g]] <- child\n }\n }\n return(children) # can be a list of `dendrogram` or `hclust` or mix\n }\n hclust2(self$data, self$distance, self$method, self$use_missing)\n },\n #' @importFrom stats order.dendrogram\n align = function(self, panel, index) {\n statistics <- self$statistics\n if (!is.null(panel) && is.null(self$k) && is.null(self$h) &&\n is.null(self$cutree)) {\n # reordering the dendrogram ------------------------\n if (nlevels(panel) > 1L && self$reorder_group) {\n parent_levels <- levels(panel)\n parent_data <- t(sapply(parent_levels, function(g) {\n colMeans(vec_slice(self$data, panel == g), na.rm = TRUE)\n }))\n rownames(parent_data) <- parent_levels\n parent <- hclust2(\n parent_data,\n distance = self$distance,\n method = self$method,\n use_missing = self$use_missing\n )\n # reorder parent based on the parent tree\n if (is.function(self$reorder_dendrogram)) {\n parent <- self$reorder_dendrogram(parent, parent_data)\n }\n # we always ensure the parent is a dendrogram\n # since we'll call `merge_dendrogram()` which requires a\n # dendrogram\n parent <- stats::as.dendrogram(parent)\n panel <- factor(panel, parent_levels[order.dendrogram(parent)])\n # we don't cutree, so we won't draw the height line\n # self$draw_params$height <- attr(ans, \"cutoff_height\")\n } else {\n parent <- NULL\n }\n\n # merge children tree ------------------------------\n if (nlevels(panel) == 1L) {\n statistics <- .subset2(statistics, 1L)\n } else if (isTRUE(self$merge_dendro)) {\n # we have a function named merge_dendrogram(), so we use\n # `merge_dendro` as the argument name\n # `merge_dendrogram` will follow the order of the parent\n statistics <- lapply(statistics, stats::as.dendrogram)\n statistics <- merge_dendrogram(parent, statistics)\n } else {\n # if no parent tree, and we havn't merged the tree\n # we must manually reorder the dendrogram\n if (!is.null(parent)) {\n statistics <- .subset(statistics, levels(panel))\n }\n self$multiple_tree <- TRUE\n }\n } else {\n # hclust2() will attach the distance used\n distance <- attr(statistics, \"distance\")\n if (is.function(self$reorder_dendrogram)) {\n statistics <- self$reorder_dendrogram(statistics, self$data)\n }\n if (!is.null(self$k) || !is.null(self$h) || !is.null(self$cutree)) {\n if (is.null(cutree <- self$cutree)) {\n cutree <- function(tree, dist, k, h) {\n if (!is.null(k)) {\n stats::cutree(tree, k = k)\n } else {\n stats::cutree(tree, h = h)\n }\n }\n }\n # we need `hclust` object to cutree\n statistics <- stats::as.hclust(statistics)\n panel <- cutree(statistics, distance, self$k, self$h)\n # For `cutree`, we always respect the height user specified\n # For user defined function, we always calculate\n # height from the number of `panels`\n if (isTRUE(self$plot_cut_height)) {\n self$height <- self$h %||% cutree_k_to_h(\n statistics, vec_unique_count(panel)\n )\n }\n }\n }\n # save the modified `statistics`\n self$statistics <- statistics\n if (self$multiple_tree) {\n index <- unlist(lapply(statistics, order2), FALSE, FALSE)\n } else {\n index <- order2(statistics)\n }\n # reorder panel factor levels to following the dendrogram order\n if (!is.null(panel)) {\n panel <- factor(panel, unique(panel[index]))\n # save panel information, in case of user change it\n self$panel <- panel\n }\n list(panel, index)\n },\n summary_align = function(self, ...) {\n c(TRUE, !is.null(self$k) || !is.null(self$h) || !is.null(self$cutree))\n }\n)\n\n#' Generate Tree Structures with Hierarchical Clustering\n#'\n#' @param matrix A numeric matrix, or data frame.\n#' @param distance A string of distance measure to be used. This must be one of\n#' `\"euclidean\"`, `\"maximum\"`, `\"manhattan\"`, `\"canberra\"`, `\"binary\"` or\n#' `\"minkowski\"`. Correlation coefficient can be also used, including\n#' `\"pearson\"`, `\"spearman\"` or `\"kendall\"`. In this way, `1 - cor` will be used\n#' as the distance. In addition, you can also provide a [`dist`][stats::dist]\n#' object directly or a function return a [`dist`][stats::dist] object. Use\n#' `NULL`, if you don't want to calculate the distance.\n#' @param method A string of the agglomeration method to be used. This should be\n#' (an unambiguous abbreviation of) one of `\"ward.D\"`, `\"ward.D2\"`, `\"single\"`,\n#' `\"complete\"`, `\"average\"` (= UPGMA), `\"mcquitty\"` (= WPGMA), `\"median\"` (=\n#' WPGMC) or `\"centroid\"` (= UPGMC). You can also provide a function which\n#' accepts the calculated distance (or the input matrix if `distance` is `NULL`)\n#' and returns a [`hclust`][stats::hclust] object. Alternative, you can supply\n#' an object which can be coerced to [`hclust`][stats::hclust].\n#' @param use_missing An optional character string giving a method for computing\n#' covariances in the presence of missing values. This must be (an abbreviation\n#' of) one of the strings `\"everything\"`, `\"all.obs\"`, `\"complete.obs\"`,\n#' `\"na.or.complete\"`, or `\"pairwise.complete.obs\"`. Only used when `distance`\n#' is a correlation coefficient string.\n#' @seealso\n#' - [cor()][stats::cor]\n#' - [dist()][stats::dist]\n#' - [hclust()][stats::hclust]\n#' @examples\n#' hclust2(dist(USArrests), method = \"ward.D\")\n#' @return A [hclust][stats::hclust] object.\n#' @importFrom rlang is_string try_fetch\n#' @export\nhclust2 <- function(matrix, distance = \"euclidean\", method = \"complete\",\n use_missing = \"pairwise.complete.obs\") {\n method <- allow_lambda(method)\n if (!is_string(method) && !is.function(method)) {\n ans <- try_fetch(\n stats::as.hclust(method),\n error = function(cnd) {\n cli_abort(paste(\n \"{.arg method} can only be a {.cls string},\",\n \"{.cls function} or an object which can be coerced to\",\n \"{.cls hclust}.\"\n ), parent = cnd)\n }\n )\n return(ans)\n }\n if (is.null(distance)) {\n d <- matrix\n } else {\n d <- make_dist(matrix, distance, use_missing)\n }\n if (is_string(method)) {\n ans <- stats::hclust(d, method = method)\n } else if (is.function(method)) {\n ans <- method(d)\n ans <- try_fetch(\n stats::as.hclust(ans),\n error = function(cnd) {\n cli_abort(paste(\n \"{.arg method} must return an object which\",\n \"can be coerced to {.cls hclust}\"\n ), parent = cnd)\n }\n )\n }\n if (!is.null(distance)) attr(ans, \"distance\") <- d\n ans\n}\n\n#' @importFrom rlang arg_match0\nmake_dist <- function(matrix, distance, use_missing,\n arg = caller_arg(distance), call = caller_call()) {\n distance <- allow_lambda(distance)\n if (is_string(distance)) {\n distance <- arg_match0(distance, c(\n \"euclidean\", \"maximum\", \"manhattan\", \"canberra\",\n \"binary\", \"minkowski\", \"pearson\", \"spearman\", \"kendall\"\n ), arg_nm = arg, error_call = call)\n d <- switch(distance,\n euclidean = ,\n maximum = ,\n manhattan = ,\n canberra = ,\n binary = ,\n minkowski = stats::dist(matrix, method = distance),\n pearson = ,\n spearman = ,\n kendall = stats::as.dist(\n 1 - stats::cor(t(matrix), use = use_missing, method = distance)\n ),\n cli_abort(\"Unsupported {.arg {arg}} specified\", call = call)\n )\n } else if (is.function(distance)) {\n if (!inherits(d <- distance(matrix), \"dist\")) {\n cli_abort(\n \"{.arg {arg}} must return a {.cls dist} object\",\n call = call\n )\n }\n } else if (inherits(distance, \"dist\")) {\n d <- distance\n } else {\n cli_abort(paste(\n \"{.arg {arg}} can only be a {.cls string}, {.cls dist}\",\n \"object, or a {.cls function} return {.cls dist}\"\n ), call = call)\n }\n d\n}\n\ncutree_k_to_h <- function(tree, k) {\n if (is.null(n1 <- nrow(tree$merge)) || n1 < 1) {\n cli_abort(\"invalid {.arg tree} ({.field merge} component)\")\n }\n n <- n1 + 1\n if (is.unsorted(tree$height)) {\n cli_abort(\n \"the 'height' component of 'tree' is not sorted (increasingly)\"\n )\n }\n mean(tree$height[c(n - k, n - k + 1L)])\n}\n"], ["/ggalign/R/ggalign.R", "#' Add ggplot by Aligning discrete or continuous variable\n#'\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' `ggalign()` is similar to `ggplot` in that it initializes a `ggplot` data and\n#' `mapping`. `ggalign()` allowing you to provide data in various formats,\n#' including matrices, data frames, or simple vectors. By default, it will\n#' inherit from the layout. If a function, it will apply with the layout matrix.\n#' `ggalign()` focuses on integrating plots into a layout by aligning the axes.\n#'\n#' @param data The following options can be used:\n#' - `NULL`: No data is set.\n#' - [`waiver()`][ggplot2::waiver]: Inherits the data from the layout matrix.\n#' - A `function` (including purrr-like lambda syntax): Applied to the layout\n#' matrix to transform the data before use. To transform the final plot\n#' data, please use [`scheme_data()`].\n#' - A `matrix`, `data.frame`, or atomic vector.\n#' @inheritParams ggplot2::ggplot\n#' @param ... <[dyn-dots][rlang::dyn-dots]> Additional arguments passed to\n#' [`fortify_data_frame()`].\n#' @param size The relative size of the plot, can be specified as a\n#' [`unit()`][grid::unit]. Note that for [`circle_layout()`], all size values\n#' will be interpreted as relative sizes, as this layout type adjusts based on\n#' the available space in the circular arrangement.\n#' @param no_axes `r lifecycle::badge('experimental')` Logical; if `TRUE`,\n#' removes axes elements for the alignment axis using [`theme_no_axes()`]. By\n#' default, will use the option-\n#' `r code_quote(sprintf(\"%s.align_no_axes\", pkg_nm()))`.\n#' @param active A [`active()`] object that defines the context settings when\n#' added to a layout.\n#' @section ggplot2 specification:\n#' `ggalign` initializes a ggplot object. The underlying data is created using\n#' [`fortify_data_frame()`]. Please refer to it for more details.\n#'\n#' When aligning discrete variables, `ggalign()` always applies a default\n#' mapping for the axis of the data index in the layout. Specifically:\n#'\n#' - `aes(y = .data$.y)` is used for the horizontal `stack_layout()` (including\n#' left and right annotations).\n#' - `aes(x = .data$.x)` is used for the vertical `stack_layout()` (including\n#' top and bottom annotations) and `circle_layout()`.\n#'\n#' The following columns will be added to the data frame to align discrete\n#' variables:\n#'\n#' - `.panel`: The panel for the aligned axis. Refers to the `x-axis` for\n#' vertical `stack_layout()` (including top and bottom annotations), and the\n#' `y-axis` for horizontal `stack_layout()` (including left and right\n#' annotations).\n#'\n#' - `.names` ([`vec_names()`][vctrs::vec_names]) and `.index`\n#' ([`vec_size()`][vctrs::vec_size()]/[`NROW()`]): Character names (if\n#' available) and the integer index of the original data.\n#'\n#' - `.x`/`.y` and `.discrete_x`/`.discrete_y`: Integer indices for `x`/`y`\n#' coordinates, and a factor of the data labels (only applicable when names\n#' exist).\n#'\n#' It is recommended to use `.x`/`.y`, or `.discrete_x`/`.discrete_y` as the\n#' `x`/`y` mapping.\n#'\n#' If the data inherits from [`quad_layout()`]/[`ggheatmap()`], additional\n#' columns will be added:\n#'\n#' - `.extra_panel`: Provides the panel information for the column (left or\n#' right annotation) or row (top or bottom annotation).\n#' - `.extra_index`: The index information for the column (left or right\n#' annotation) or row (top or bottom annotation).\n#'\n#' @inheritSection align Discrete Axis Alignment\n#' @examples\n#' ggheatmap(matrix(rnorm(81), nrow = 9)) +\n#' anno_top() +\n#' ggalign() +\n#' geom_point(aes(y = value))\n#'\n#' ggheatmap(matrix(rnorm(81), nrow = 9)) +\n#' anno_top(size = 0.5) +\n#' align_dendro(k = 3L) +\n#' ggalign(data = NULL, size = 0.2) +\n#' geom_tile(aes(y = 1L, fill = .panel))\n#'\n#' @importFrom ggplot2 ggplot aes\n#' @importFrom rlang list2\n#' @export\nggalign <- function(data = waiver(), mapping = aes(), ..., size = NULL,\n no_axes = NULL, active = NULL) {\n if (inherits(data, \"uneval\")) {\n cli_abort(c(\n \"{.arg data} cannot be {.obj_type_friendly {data}}\",\n \"i\" = \"Have you misspelled the {.arg data} argument in {.fn ggalign}\"\n ))\n }\n no_axes <- no_axes %||%\n getOption(sprintf(\"%s.align_no_axes\", pkg_nm()), default = TRUE)\n assert_active(active)\n active <- update_active(active, new_active(use = TRUE))\n new_craftbox(\n AlignGg,\n input_data = allow_lambda(data),\n data_params = list2(...),\n plot = ggplot(mapping = mapping),\n size = size,\n schemes = default_schemes(data, th = theme_no_strip()),\n no_axes = no_axes, active = active\n )\n}\n\n#' @importFrom rlang inject\n#' @importFrom ggplot2 ggproto ggplot\nAlignGg <- ggproto(\"AlignGg\", Craftsman,\n interact_layout = function(self, layout) {\n layout_name <- self$layout_name\n input_data <- self$input_data\n object_name <- object_name(self)\n layout_data <- layout@data\n\n # inherit data from the layout\n if (is.function(input_data)) {\n if (is.null(layout_data)) {\n cli_abort(c(\n sprintf(\n \"{.arg data} in %s cannot be a function\",\n object_name\n ),\n i = sprintf(\"no data was found in %s\", layout_name)\n ))\n }\n data <- input_data(layout_data)\n } else if (is.waive(input_data)) {\n data <- layout_data %|w|% NULL\n # for data inherit from the layout, and the layout data is from\n # the quad-layout, we'll integrate the `extra_design`\n self$use_extra_design <- is_stack_layout(layout) &&\n isTRUE(layout@heatmap$quad_matrix)\n } else {\n data <- input_data\n }\n plot_data <- inject(\n fortify_data_frame(data, !!!self$data_params, call = self$call)\n )\n\n # for discrete design, # we need ensure the nobs is the same\n if (is_discrete_design(design <- layout@design)) {\n if (!is.null(data)) {\n if (is.null(layout_nobs <- design$nobs)) {\n layout_nobs <- NROW(data)\n if (layout_nobs == 0L) {\n cli_abort(\"{.arg data} cannot be empty\",\n call = self$call\n )\n }\n } else if (NROW(data) != layout_nobs) {\n cli_abort(sprintf(\n \"%s (nobs: %d) is not compatible with the %s (nobs: %d)\",\n object_name, NROW(data), layout_name, layout_nobs\n ))\n }\n design[\"nobs\"] <- list(layout_nobs)\n\n # we always add `.index` to align the observations\n # For matrix-like object\n if (!is.data.frame(data) &&\n vec_is(dim(data), integer(), size = 2L)) {\n plot_data$.index <- vec_rep(seq_len(NROW(data)), NCOL(data))\n } else {\n plot_data$.index <- seq_len(NROW(data))\n }\n layout@design <- design\n self$labels <- vec_names(data) %||% vec_names(layout_data)\n # always remove names, we'll add it in `build_plot()`\n plot_data$.names <- NULL\n } else {\n self$labels <- vec_names(layout_data)\n }\n self$add_mapping <- TRUE\n }\n self$data <- ggalign_data_restore(plot_data, layout_data)\n layout\n },\n setup_plot = function(self, plot) {\n direction <- self$direction\n ggadd_default(\n plot,\n mapping = if (isTRUE(self$add_mapping)) {\n switch_direction(\n direction,\n aes(y = .data$.y),\n aes(x = .data$.x)\n )\n },\n theme = if (is.null(self$data)) {\n # remove the title and text of axis vertically with the layout\n theme_no_axes(switch_direction(direction, \"x\", \"y\"))\n }\n ) + switch_direction(\n direction,\n ggplot2::labs(y = NULL),\n ggplot2::labs(x = NULL)\n )\n },\n\n #' @importFrom stats reorder\n build_plot = function(self, plot, design, extra_design = NULL,\n previous_design = NULL) {\n data <- self$data\n\n # if inherit from the parent layout\n if (isTRUE(self$use_extra_design) &&\n is_discrete_design(extra_design) &&\n !is.null(.subset2(extra_design, \"nobs\"))) {\n # if the data is inherit from the `quad_layout()`\n # the data must be a matrix\n extra_plot_data <- data_frame0(\n .extra_panel = .subset2(extra_design, \"panel\"),\n .extra_index = .subset2(extra_design, \"index\")\n )\n } else {\n extra_plot_data <- NULL\n }\n\n if (is_continuous_design(design)) {\n if (!is.null(data) && !is.null(extra_plot_data)) {\n data <- full_join(data, extra_plot_data,\n by.x = \".column_index\", by.y = \".extra_index\"\n )\n }\n return(gguse_data(plot, data))\n } else if (is.null(.subset2(design, \"nobs\"))) {\n cli_abort(c(\n sprintf(\n \"you must initialize %s before drawing %s\",\n self$layout_name, object_name(self)\n ),\n i = \"Or you should use {.fn ggfree}\"\n ), call = self$call)\n }\n direction <- self$direction\n axis <- to_coord_axis(direction)\n panel <- .subset2(design, \"panel\")\n index <- .subset2(design, \"index\")\n coord_name <- paste0(\".\", axis)\n plot_data <- data_frame0(\n .panel = panel,\n .index = index,\n # `data_frame0` will omit `NULL`\n .names = .subset(self$labels, index)\n )\n plot_data[[coord_name]] <- seq_along(index)\n if (!is.null(.subset2(plot_data, \".names\"))) {\n plot_data[[paste0(\".discrete_\", axis)]] <- reorder(\n .subset2(plot_data, \".names\"),\n .subset2(plot_data, coord_name),\n order = FALSE\n )\n }\n\n if (!is.null(extra_plot_data)) {\n plot_data <- cross_join(plot_data, extra_plot_data)\n if (!is.null(data)) {\n plot_data <- full_join(data, plot_data,\n by.x = c(\".column_index\", \".index\"),\n by.y = c(\".extra_index\", \".index\")\n )\n }\n } else if (!is.null(data)) {\n plot_data <- full_join(data, plot_data, by = \".index\")\n }\n gguse_data(plot, ggalign_data_restore(plot_data, data))\n },\n\n # let Craftsman to add schemes and theme acoordingly\n finish_plot = function(self, plot, schemes, theme) {\n direction <- self$direction\n # remove axis titles, text, ticks used for alignment\n if (isTRUE(self$no_axes)) {\n schemes$scheme_theme <- .subset2(schemes, \"scheme_theme\") +\n theme_no_axes(switch_direction(direction, \"y\", \"x\"))\n }\n plot <- plot_add_schemes(plot, schemes)\n if (is_horizontal(direction)) {\n theme <- theme(\n panel.spacing.y = calc_element(\"panel.spacing.y\", theme)\n )\n } else {\n theme <- theme(\n panel.spacing.x = calc_element(\"panel.spacing.x\", theme)\n )\n }\n plot <- plot + theme\n ggremove_margin(plot, direction) + theme_recycle()\n },\n summary = function(self, plot) {\n header <- ggproto_parent(Craftsman, self)$summary(plot)\n c(header, \" Add plot by Aligning discrete or continuous variable\")\n }\n)\n\n#' Create ggplot object with layout panel data\n#'\n#' @description\n#' `r lifecycle::badge(\"deprecated\")`\n#'\n#' This function was deprecated because we realised that it's a special case of\n#' the [`ggalign()`] function. Please use `ggalign(data = NULL)` instead.\n#' @export\n#' @keywords internal\nalign_panel <- function(...) {\n lifecycle::deprecate_stop(\"0.0.5\", \"align_panel()\", \"ggalign(data = NULL)\")\n}\n\n#' @export\n#' @rdname align_panel\nggpanel <- function(...) {\n lifecycle::deprecate_stop(\"0.0.5\", \"ggpanel()\", \"ggalign(data = NULL)\")\n}\n"], ["/ggalign/R/craft-align-kmeans.R", "#' Split observations by k-means clustering groups.\n#'\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' Aligns and groups observations based on k-means clustering, enabling\n#' observation splits by cluster groups.\n#'\n#' @inheritDotParams stats::kmeans -x -centers\n#' @param data A numeric matrix to be used by k-means. By default, it will\n#' inherit from the layout matrix.\n#' @inheritParams align\n#' @inheritSection align Discrete Axis Alignment\n#' @examples\n#' ggheatmap(matrix(rnorm(81), nrow = 9)) +\n#' anno_top() +\n#' align_kmeans(3L)\n#' @importFrom rlang list2\n#' @export\nalign_kmeans <- function(..., data = NULL, active = NULL) {\n assert_active(active)\n active <- update_active(active, new_active(use = FALSE))\n align(\n align = AlignKmeans,\n params = list2(...),\n active = active,\n data = data\n )\n}\n\n#' @importFrom ggplot2 ggproto\n#' @importFrom rlang inject\nAlignKmeans <- ggproto(\"AlignKmeans\", CraftAlign,\n interact_layout = function(self, layout) {\n ggproto_parent(AlignOrder2, self)$interact_layout(layout)\n },\n compute = function(self, panel, index) {\n inject(stats::kmeans(x = self$data, !!!self$params))\n },\n align = function(self, panel, index) {\n list(.subset2(self$statistics, \"cluster\"), index)\n },\n summary_align = function(self) c(FALSE, TRUE)\n)\n"], ["/ggalign/R/craft-align-.R", "#' Create a New `CraftBox` Object with `CraftAlign` craftsman\n#'\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' An `CraftAlign` object interacts with the `Layout` object to reorder or split\n#' observations and, in some cases, add plot components to the `Layout`.\n#'\n#' @param align An `CraftAlign` object.\n#' @param ... Additional fields passed to the `align` object.\n#' @param plot A ggplot object.\n#' @inheritParams ggalign\n#' @param schemes Options for `schemes`:\n#' - `NULL`: Used when `align` do not add a plot.\n#' - [`waiver()`][ggplot2::waiver]: Try to infer `schemes` based on `data`.\n#' @param call The `call` used to construct the `align` object, for\n#' reporting messages.\n#'\n#' @section Discrete Axis Alignment:\n#' It is important to note that we consider rows as observations, meaning\n#' `vec_size(data)`/`NROW(data)` must match the number of observations along the\n#' axis used for alignment (x-axis for a vertical stack layout, y-axis for a\n#' horizontal stack layout).\n#'\n#' @return A new `CraftBox` object.\n#' @examples\n#' align_dendro()\n#' @importFrom rlang caller_call current_call\n#' @importFrom ggplot2 ggproto\n#' @export\n#' @keywords internal\nalign <- function(align, data = NULL, ..., plot = NULL,\n size = NULL, schemes = NULL, no_axes = NULL,\n active = NULL, call = caller_call()) {\n if (override_call(call)) {\n call <- current_call()\n }\n\n # check arguments ---------------------------------------------\n data <- allow_lambda(data)\n no_axes <- no_axes %||%\n getOption(sprintf(\"%s.align_no_axes\", pkg_nm()), default = TRUE)\n schemes <- schemes %|w|% default_schemes(data)\n\n new_craftbox(\n craftsman = align,\n\n # additional field for `align` object\n no_axes = no_axes,\n ...,\n\n # Following fields will be initialzed when added into the layout\n # and will be saved and accessed across the plot rendering process\n direction = NULL,\n position = NULL,\n data = NULL, # Used to save the modified `input_data`\n statistics = NULL, # `$compute` method\n labels = NULL, # the original `vec_names()` of the `input_data`\n\n # the input data\n input_data = data,\n\n # object slots\n plot = plot,\n active = active,\n size = size,\n schemes = schemes,\n\n # call\n call = call\n )\n}\n\n#' @details\n#' Each of the `Align*` objects is just a [`ggproto()`][ggplot2::ggproto]\n#' object, descended from the top-level `CraftAlign`, and each implements\n#' various methods and fields.\n#'\n#' To create a new type of `Align*` object, you typically will want to\n#' override one or more of the following:\n#' - `setup_params`: Prepare parameter or check parameters used by this plot.\n#' - `setup_data`: Prepare data used by this plot.\n#' - `compute`: A method used to compute statistics.\n#' - `align`: A method used to group observations into panel or reorder\n#' observations.\n#' - `draw`: A method used to draw the plot. Must return a `ggplot` object.\n#' @importFrom ggplot2 ggproto\n#' @export\n#' @format NULL\n#' @usage NULL\n#' @rdname align\n#' @include craftbox-.R\nCraftAlign <- ggproto(\"CraftAlign\", Craftsman,\n interact_layout = function(self, layout) {\n # check plot is compatible with the layout\n if (is_layout_continuous(layout)) {\n layout_name <- self$layout_name\n # `CraftAlign` object is special for discrete variables\n cli_abort(c(\n sprintf(\"Cannot add %s to %s\", object_name(self), layout_name),\n i = sprintf(\"%s cannot align discrete variables\", layout_name)\n ))\n }\n layout\n },\n setup_design = function(self, design) {\n old_panel <- .subset2(design, \"panel\")\n old_index <- .subset2(design, \"index\")\n # prepare the data -------------------------------\n # compute statistics ---------------------------------\n self$statistics <- self$compute(panel = old_panel, index = old_index)\n\n # make the new layout -------------------------------\n panel_and_index <- self$align(panel = old_panel, index = old_index)\n\n # check panel\n layout_name <- self$layout_name\n nobs <- .subset2(design, \"nobs\")\n new_panel <- .subset2(panel_and_index, 1L)\n if (!is.null(new_panel)) {\n if (!is.atomic(new_panel)) {\n cli_abort(c(\n sprintf(\n \"invalid layout panels defined by %s\",\n object_name(self)\n ),\n i = \"layout panels must be an atomic vector\"\n ))\n } else if (anyNA(new_panel)) {\n cli_abort(sprintf(\n \"layout panels defined by %s contain `NA`\",\n object_name(self)\n ))\n } else if (is.null(nobs)) {\n # we have defined panel, but don't define the `nobs`\n cli_abort(sprintf(\n \"%s defined the panels but not define {.field nobs}\", object_name(self)\n ))\n } else if (length(new_panel) != nobs) {\n # we have defined panel, but don't define the `nobs`\n cli_abort(sprintf(\n \"layout panels defined by %s (nobs: %d) is not compatible with the nobs: %d\",\n object_name(self), length(new_panel), nobs\n ))\n } else if (!is.null(old_panel) && !(new_panel %nest% old_panel)) {\n cli_abort(sprintf(\n \"%s disrupt the previously established panel groups of %s\",\n object_name(self), layout_name\n ))\n }\n } else if (!is.null(old_panel)) {\n # push developer to reset the panel in the layout\n cli_abort(c(\n sprintf(\"invalid %s\", object_name(self)),\n i = sprintf(\n \"%s reset the {.field panel}, but don't change the {.field panel} of the layout\", object_name(self)\n )\n ))\n }\n panel <- new_panel\n if (!is.null(panel) && !is.factor(panel)) panel <- factor(panel)\n\n # check index\n new_index <- .subset2(panel_and_index, 2L)\n if (!is.null(new_index)) {\n if (!is.integer(new_index)) {\n cli_abort(c(\n sprintf(\n \"invalid layout ordering index defined by %s\", object_name(self)\n ),\n i = \"layout ordering index must be an integer\"\n ))\n } else if (anyNA(new_index)) {\n cli_abort(sprintf(\n \"layout ordering index defined by %s contain `NA`\",\n object_name(self)\n ))\n } else if (is.null(nobs)) {\n # we have defined panel, but don't define the `nobs`\n cli_abort(sprintf(\n \"%s defined the ordering index but not define nobs\", object_name(self)\n ))\n } else if (length(new_index) != nobs) {\n # we have defined index, but don't define the `nobs`\n cli_abort(sprintf(\n \"layout ordering index defined by %s (nobs: %d) is not compatible with the nobs (%d)\",\n object_name(self), length(new_index), nobs\n ))\n }\n } else if (!is.null(old_index)) {\n # push developer to reset the `index` in the layout\n cli_abort(c(\n sprintf(\"invalid %s\", object_name(self)),\n i = sprintf(\n \"%s reset the {.field index}, but don't change the {.field index} of the layout\",\n object_name(self)\n )\n ))\n }\n index <- new_index\n\n # we always make the index following the panel\n if (!is.null(panel) && !is.null(index)) {\n index <- reorder_index(panel, index)\n }\n\n # we always prevent from reordering twice.\n if (!is.null(old_index) && !all(old_index == index)) {\n cli_abort(sprintf(\n \"%s disrupt the previously established ordering index of %s\",\n object_name(self), layout_name\n ))\n }\n discrete_design(panel, index, nobs)\n },\n\n # Following fields should be defined for the new `CraftAlign` object.\n # argument name in these function doesn't matter.\n compute = function(self, panel, index) NULL,\n\n # Group heamap row/column and reorder, Must return a list of 2:\n # - the first one should be the groups for heatmap row/column, the factor\n # levels will determine the panel order, so it should always follow the\n # index if you don't want the panel levels break the index. See\n # `AlignDendro` for example.\n # - the second one should be the heatmap row/column order index, and will\n # determine the order in each grouped panel.\n #\n # See `$setup_design()` method for details\n # There will have following situations (the input is old index and old\n # panel):\n #\n # 1. old index is NULL and old panel is NULL, there is nothing wrong to\n # define any new index or panel\n # 2. old index is `NULL` and old panel is not `NULL`, in this way, new\n # index must follow the old panel.\n #\n # For new `CraftAlign` object, which can do clustering, we must\n # abort, if it can not do sub-clustering, if it can do sub-clustering, we\n # should know if we want to change the order between the groups (panel\n # levels).\n #\n # Please check `AlignGroup` object and `CraftAlign` object\n # For dendrogram, it can do sub-clustering within each group, it also\n # allows reordering between groups (it provide `reorder_group` argument),\n # so the new panel levels may be not the same with old panel\n #\n # For `CraftAlign` object reordering the heatmap rows/columns.\n # usually we provide a `strict` argument, to allow reorder heatmap within\n # group only. See `AlignOrder2`.\n #\n # 3. old index is not `NULL`, no matter whether old panel is `NULL` or not,\n # in this way, we should always ensure the new index won't change the old\n # index, this will be checked in `$setup_design()` method.\n align = function(self, panel, index) list(panel, index),\n\n # let Craftsman to add schemes and theme acoordingly\n finish_plot = function(self, plot, schemes, theme) {\n ggproto_parent(AlignGg, self)$finish_plot(plot, schemes, theme)\n },\n summary = function(self, plot) {\n header <- ggproto_parent(Craftsman, self)$summary(plot)\n oo <- self$summary_align()\n nms <- c(\"plot\", \"reorder\", \"split\")\n content <- c(\n if (is.null(plot)) \"no\" else \"yes\",\n if (isTRUE(oo[1L])) \"yes\" else \"no\",\n if (isTRUE(oo[2L])) \"yes\" else \"no\"\n )\n nms <- format(nms, justify = \"right\")\n content <- format(content, justify = \"left\")\n content <- paste0(\" \", nms, \": \", content)\n c(header, content)\n },\n\n # Summary the action of `Align`\n #\n # @return A logical vector of length 2, indicating:\n # - Whether the object reorders the observations.\n # - Whether the object splits the observations into groups.\n # @keywords internal\n summary_align = function(self) c(FALSE, FALSE)\n)\n"], ["/ggalign/R/craft-align-phylo.R", "#' Plot Phylogenetics tree\n#'\n#' @param phylo A [`phylo`][ape::as.phylo] object.\n#' @param ... <[dyn-dots][rlang::dyn-dots]> Additional arguments passed to\n#' [`geom_segment()`][ggplot2::geom_segment].\n#' @param ladderize A single string of `r oxford_or(c(\"left\", \"right\"))`,\n#' indicating whether to ladderize the tree. Ladderizing arranges the tree so\n#' that the smallest clade is positioned on the `\"right\"` or the `\"left\"`. By\n#' default, `NULL` means the tree will not be ladderized.\n#' @inheritParams fortify_data_frame.phylo\n#' @inheritParams ggalign\n#' @export\nalign_phylo <- function(phylo, ..., ladderize = NULL, type = \"rectangle\",\n center = FALSE, tree_type = NULL,\n no_axes = NULL, active = NULL,\n size = NULL) {\n if (!is.null(ladderize)) {\n ladderize <- arg_match0(ladderize, c(\"left\", \"right\"))\n rlang::check_installed(\"ape\", \"to ladderize phylogenetics tree\")\n }\n assert_s3_class(phylo, \"phylo\")\n assert_active(active)\n active <- update_active(active, new_active(use = TRUE))\n align(\n align = AlignPhylo,\n phylo = phylo,\n ladderize = ladderize,\n no_axes = no_axes,\n plot = ggplot() +\n ggplot2::geom_segment(\n mapping = aes(\n x = .data$x, y = .data$y,\n xend = .data$xend, yend = .data$yend\n ),\n ...,\n stat = \"identity\",\n data = function(data) ggalign_attr(data, \"edge\")\n ),\n data_params = list(type = type, center = center, tree_type = tree_type),\n active = active,\n size = size\n )\n}\n\nAlignPhylo <- ggproto(\"AlignPhylo\", CraftAlign,\n interact_layout = function(self, layout) {\n layout <- ggproto_parent(CraftAlign, self)$interact_layout(layout)\n\n # we keep the names from the layout data for usage\n tip_labels <- self$phylo$tip.label\n if (is.null(tip_labels)) {\n cli_abort(\n \"{.arg phylo} must have tip labels to match the layout data\",\n call = self$call\n )\n } else if (vec_duplicate_any(tip_labels)) {\n cli_abort(\n \"{.arg phylo} cannot have duplicated tip labels\",\n call = self$call\n )\n }\n\n # we ensure the layout data has names to match the phylo tree\n if (is.null(layout_labels <- vec_names(layout@data))) {\n cli_abort(c(\n sprintf(\n \"Cannot add %s to %s\", object_name(self),\n self$layout_name\n ),\n i = sprintf(\n \"%s has no labels (rownames) to match {.arg phylo}\",\n self$layout_name\n )\n ))\n } else if (vec_duplicate_any(layout_labels)) {\n cli_abort(c(\n sprintf(\n \"Cannot add %s to %s\", object_name(self),\n self$layout_name\n ),\n i = sprintf(\"%s has duplicated labels\", self$layout_name)\n ))\n }\n assert_mismatch_nobs(\n self, .subset2(layout@design, \"nobs\"), vec_size(tip_labels),\n arg = \"phylo\"\n )\n\n # we keep the names from the layout data for usage\n self$labels <- layout_labels\n layout\n },\n compute = function(self, panel, index) {\n phylo <- self$phylo\n # R CMD check won't give error even we don't add `ape` to the dependency\n if (!is.null(self$ladderize)) {\n phylo <- ape::ladderize(phylo,\n right = identical(self$ladderize, \"right\")\n )\n }\n inject(fortify_data_frame.phylo(\n data = phylo, !!!self$data_params,\n data_arg = \"phylo\", call = self$call\n ))\n },\n align = function(self, panel, index) {\n data <- self$statistics\n tip <- vec_slice(data, .subset2(data, \"tip\"))\n ordered <- .subset2(tip, \"label\")[order(.subset2(tip, \"x\"))]\n index <- match(ordered, self$labels)\n if (!is.null(panel) && nlevels(panel) > 1L &&\n !all(index == reorder_index(panel, index))) {\n layout_name <- self$layout_name\n object_name <- object_name(self)\n cli_abort(c(\n sprintf(\"Cannot add %s to %s\", object_name, layout_name),\n i = sprintf(\n \"Group of %s will disrupt the ordering index of %s\", layout_name, object_name\n )\n ), call = self$call)\n }\n list(panel, index)\n },\n setup_plot = function(self, plot) {\n ggadd_default(plot, aes(x = .data$x, y = .data$y)) + switch_direction(\n self$direction,\n ggplot2::labs(x = \"timing\"),\n ggplot2::labs(y = \"timing\")\n )\n },\n build_plot = function(self, plot, design, extra_design = NULL,\n previous_design = NULL) {\n if (!is.null(panel <- .subset2(design, \"panel\")) &&\n nlevels(panel) > 1L) {\n layout_name <- self$layout_name\n object_name <- object_name(self)\n cli_abort(c(\n sprintf(\"Cannot add %s to %s\", object_name, layout_name),\n i = sprintf(\"%s cannot span multiple panels\", object_name)\n ))\n }\n\n data <- self$statistics\n edge <- ggalign_attr(data, \"edge\")\n node <- data\n node$.panel <- unique(panel)\n edge$.panel <- unique(panel)\n\n # add names\n if (!is.null(node$label)) {\n node$.names <- node$label\n }\n if (!is.null(edge$label)) {\n edge$.names <- edge$label\n }\n if (is_horizontal(self$direction)) {\n edge <- rename(\n edge,\n c(x = \"y\", xend = \"yend\", y = \"x\", yend = \"xend\")\n )\n node <- rename(node, c(x = \"y\", y = \"x\"))\n }\n plot <- gguse_data(plot, ggalign_data_set(node, edge = edge))\n position <- self$position\n if (!self$in_linear || # for circular layout\n # for top annotation, reverse y-axis\n (!is.null(position) && position == \"top\")) {\n plot <- reverse_continuous_axis(plot, \"y\")\n } else if (!is.null(position) && position == \"right\") {\n # for right annotation, reverse x-axis\n plot <- reverse_continuous_axis(plot, \"x\")\n }\n\n # always turn off clip, this is what dendrogram dependends on\n old_coord <- plot$coordinates\n if (!identical(old_coord$clip, \"off\")) {\n # to prevent from changing the input of user.\n plot$coordinates <- ggproto(NULL, old_coord, clip = \"off\")\n }\n plot\n },\n summary_align = function(self) c(TRUE, FALSE)\n)\n\n#' Build a matrix from `phylo` object\n#'\n#' @description This method allows a [`phylo`][ape::as.phylo] object to be\n#' directly input into `stack_discrete()` or `circle_discrete()`. This makes it\n#' possible to add [`align_phylo()`] to the stack independently, as\n#' [`align_phylo()`] requires the layout to have labels.\n#' @inheritParams rlang::args_dots_empty\n#' @param data A [`phylo`][ape::as.phylo] object.\n#' @inheritParams fortify_matrix\n#' @return A one-column matrix where the tip labels are the values, and the row\n#' names will also be the tip labels.\n#' @family fortify_matrix\n#' @export\nfortify_matrix.phylo <- function(data, ..., data_arg = caller_arg(data),\n call = NULL) {\n call <- call %||% current_call()\n rlang::check_dots_empty(call = call)\n if (is.null(labels <- data$tip.label)) {\n cli_abort(\n \"{.arg {data_arg}} must have tip labels to match the layout data\",\n call = call\n )\n }\n as.matrix(vec_set_names(labels, labels))\n}\n\n#' @inherit fortify_data_frame.default title description\n#' @inheritParams rlang::args_dots_empty\n#' @inheritParams fortify_data_frame.dendrogram\n#' @param tree_type A single string, one of\n#' `r oxford_or(c(\"phylogram\", \"cladogram\"))`, indicating the type of tree.\n#' - `phylogram`: Represents a phylogenetic tree where branch lengths indicate\n#' evolutionary distance or time.\n#' - `cladogram`: Represents a tree where branch lengths are not used, or the\n#' branches do not reflect evolutionary time.\n#'\n#' Usually, you don't need to modify this.\n#'\n#' @param tip_pos The x-coordinates of the tip. Must be the same length\n#' of the number of tips in `tree`.\n#' @return A `data frame` with the node coordinates:\n#' - `.index`: the original index in the tree for the the tip/node.\n#' - `label`: the tip/node label text.\n#' - `x` and `y`: x-axis and y-axis coordinates for the tip/node.\n#' - `tip`: A logical value indicates whether current node is a tip.\n#' @section ggalign attributes:\n#' `edge`: A `data frame` for edge coordinates:\n#'\n#' - `x` and `y`: x-axis and y-axis coordinates for the start node of the edge.\n#' - `xend` and `yend`: the x-axis and y-axis coordinates of the terminal node\n#' for edge.\n#' @family fortify_data_frame\n#' @export\nfortify_data_frame.phylo <- function(data, ..., type = \"rectangle\",\n center = FALSE,\n tree_type = NULL, tip_pos = NULL,\n data_arg = NULL, call = NULL) {\n call <- call %||% current_call()\n data_arg <- data_arg %||% \"data\"\n rlang::check_dots_empty(call = call)\n type <- arg_match0(type, c(\"rectangle\", \"triangle\"))\n rectangle <- type == \"rectangle\"\n edge <- data$edge\n edge_lengths <- data$edge.length\n if (!is.null(tree_type)) {\n tree_type <- arg_match0(tree_type,\n c(\"phylogram\", \"cladogram\"),\n error_call = call\n )\n if (tree_type == \"phylogram\" && is.null(edge_lengths)) {\n cli_warn(c(\n \"Cannot use {.code tree_type = 'phylogram'}\",\n \"No branch length found in {.arg {data_arg}}\"\n ))\n tree_type <- \"cladogram\"\n }\n }\n if (identical(tree_type, \"cladogram\")) {\n edge_lengths <- NULL\n }\n parent <- edge[, 1L, drop = TRUE]\n child <- edge[, 2L, drop = TRUE]\n tip_labels <- data$tip.label\n node_labels <- data$node.label\n N <- length(tip_labels)\n if (is.null(tip_pos)) {\n tip_pos <- seq_len(N)\n } else if (length(tip_pos) != N) {\n cli_abort(\n \"{.arg tip_pos} must have the same length as the number of tips in {.arg {data_arg}}\",\n call = call\n )\n }\n i <- 0L # tip index\n phylo_data <- function(index, level, timing) {\n if (any(select <- parent == index)) {\n # recursively for each child\n data <- list(index = child[select])\n # if we have edge length, timing should be available\n if (!is.null(edge_lengths)) {\n data <- c(data, list(timing = timing + edge_lengths[select]))\n }\n data <- list_transpose(.mapply(\n function(index, timing = NULL) {\n phylo_data(index, level = level + 1L, timing = timing)\n },\n data, NULL\n ))\n\n # integrate the data for each child\n node <- vec_rbind(!!!.subset2(data, \"node\"))\n edge <- vec_rbind(!!!.subset2(data, \"edge\"))\n\n # all coordinate for direct children nodes -------------\n direct_leaves_x <- unlist(\n .subset2(data, \"x\"),\n recursive = FALSE, use.names = FALSE\n )\n direct_leaves_y <- unlist(\n .subset2(data, \"y\"),\n recursive = FALSE, use.names = FALSE\n )\n\n # prepare node data ------------------------------------\n # all x coordinate for children nodes ------------------\n # used if center is `TRUE`, we'll calculate the center position\n # among all children nodes\n leaves <- vec_slice(node, .subset2(node, \"tip\")) # all leaves\n\n # x coordinate for current node: the midpoint\n if (center) {\n x <- sum(range(.subset2(leaves, \"x\"))) / 2L\n } else {\n x <- sum(range(direct_leaves_x)) / 2L\n }\n\n # y coordinate for current node\n if (is.null(edge_lengths) && is.null(timing)) {\n y <- min(direct_leaves_y) * level / (level + 1L)\n } else {\n y <- timing\n }\n\n # there is no node data for the root\n node <- vec_rbind(data_frame0(\n .index = index,\n label = node_labels[index - N],\n x = x, y = y, tip = FALSE\n ), node)\n\n # if it's the `rectangle`\n if (rectangle) {\n # vertical lines\n vertical_lines <- data_frame0(\n x = direct_leaves_x,\n xend = direct_leaves_x,\n y = y,\n yend = direct_leaves_y\n )\n added_edge <- vec_rbind(\n vertical_lines,\n # horizontal line\n data_frame0(\n x = x,\n xend = direct_leaves_x,\n y = y,\n yend = y\n )\n )\n } else {\n added_edge <- data_frame0(\n x = x,\n xend = direct_leaves_x,\n y = y,\n yend = direct_leaves_y\n )\n }\n if (is.null(edge)) {\n edge <- added_edge\n } else {\n edge <- vec_rbind(added_edge, edge)\n }\n list(node = node, edge = edge, x = x, y = y)\n } else if (any(select <- child == index)) { # for the tip\n i <<- i + 1L\n x <- tip_pos[i]\n if (is.null(edge_lengths)) {\n y <- 1L\n } else {\n y <- timing\n }\n\n list(\n node = data_frame0(\n .index = index,\n label = tip_labels[index],\n x = x,\n y = y,\n tip = TRUE\n ),\n edge = NULL,\n x = x, y = y\n )\n } else {\n cli_abort(\"Invalid {.cls phylo} provided in {.arg {data_arg}}\",\n call = call\n )\n }\n }\n\n # from ape::is.rooted, this should be the most ancester\n ans <- phylo_data(N + 1L, 0L, timing = 0)\n ggalign_data_set(.subset2(ans, \"node\"), edge = .subset2(ans, \"edge\"))\n}\n"], ["/ggalign/R/craft-cross-mark.R", "#' Add a plot to annotate observations\n#'\n#' @inheritParams cross_none\n#' @inheritParams ggmark\n#'\n#' @section ggplot2 Specification:\n#' The `cross_mark` function initializes a `ggplot` object. The underlying data\n#' contains following columns:\n#'\n#' - `.panel`: the panel for the aligned axis. It means `x-axis` for vertical\n#' stack layout (including top and bottom annotation), `y-axis` for\n#' horizontal stack layout (including left and right annotation).\n#'\n#' - `.names` ([`vec_names()`][vctrs::vec_names]) and `.index`\n#' ([`vec_size()`][vctrs::vec_size()]/[`NROW()`]): a character names (only\n#' applicable when names exists) and an integer of index of the original\n#' data.\n#'\n#' - `.hand`: A factor with levels `c(\"left\", \"right\")` for horizontal stack\n#' layouts, or `c(\"top\", \"bottom\")` for vertical stack layouts, indicating\n#' the position of the linked observations.\n#'\n#' You can use [`scheme_data()`] to modify the internal data if needed.\n#'\n#' @export\ncross_mark <- function(mark, data = waiver(), ...,\n obs_size = 1, inherit_index = NULL, inherit_panel = NULL,\n inherit_nobs = NULL,\n size = NULL, active = NULL) {\n if (!inherits(mark, \"ggalign_mark_draw\")) {\n cli_abort(\"{.arg mark} must be a {.fn mark_draw} object\")\n }\n assert_obs_size(obs_size)\n assert_active(active)\n active <- update_active(active, new_active(use = TRUE))\n cross(CrossMark,\n data = data, data_params = list2(...),\n mark = mark, obs_size = obs_size,\n plot = ggplot(), size = size,\n schemes = default_schemes(th = theme_panel_border()),\n active = active,\n inherit_nobs = inherit_nobs,\n inherit_panel = inherit_panel,\n inherit_index = inherit_index\n )\n}\n\n#' @importFrom ggplot2 ggproto ggproto_parent\n#' @include craft-cross-.R\nCrossMark <- ggproto(\"CrossMark\", CraftCross,\n interact_layout = function(self, layout) {\n if (!self$in_linear) { # only used for linear coordinate\n cli_abort(c(\n sprintf(\n \"Cannot add %s to %s\",\n object_name(self), layout_name\n ),\n i = sprintf(\n \"%s can only be used in linear layout\",\n object_name(self)\n )\n ))\n }\n ggproto_parent(CraftCross, self)$interact_layout(layout)\n },\n build_plot = function(self, plot, design, extra_design = NULL,\n previous_design = NULL) {\n if (is.null(.subset2(previous_design, \"nobs\"))) {\n cli_abort(\n sprintf(\n \"layout {.field nobs} for %s before %s is not initialized \",\n self$layout_name, object_name(self)\n )\n )\n }\n if (is.null(.subset2(design, \"nobs\"))) {\n cli_abort(\n sprintf(\n \"layout {.field nobs} for %s after %s is not initialized \",\n self$layout_name, object_name(self)\n )\n )\n }\n direction <- self$direction\n\n # parse links --------------------------------------------\n mark <- self$mark\n design1 <- previous_design\n design2 <- design\n full_data1 <- split(\n seq_len(.subset2(design1, \"nobs\")),\n .subset2(design1, \"panel\")\n )\n full_data2 <- split(\n seq_len(.subset2(design2, \"nobs\")),\n .subset2(design2, \"panel\")\n )\n link_index <- make_links_data(\n .subset2(mark, \"links\"),\n design1 = design1, design2 = design2,\n labels1 = self$labels0, labels2 = self$labels\n )\n if (vec_duplicate_any(nms <- names(link_index))) { # nolint\n cli_abort(\n c(\n \"panel names must be unique in {.arg mark}\",\n i = \"duplicated names: {.val {nms[vec_duplicate_detect(nms)]}}\"\n ),\n call = self$call\n )\n }\n data_index <- lapply(link_index, function(link) {\n if (is.null(link)) {\n return(NULL)\n }\n hand1 <- .subset2(link, \"hand1\")\n hand2 <- .subset2(link, \"hand2\")\n list(\n hand1 = .subset2(design1, \"index\")[hand1],\n hand2 = .subset2(design2, \"index\")[hand2]\n )\n })\n\n # prepare data for the plot\n plot_data <- lapply(data_index, function(index) {\n if (is.null(index)) {\n return(NULL)\n }\n hand1 <- .subset2(index, \"hand1\")\n hand2 <- .subset2(index, \"hand2\")\n hand <- switch_direction(\n direction,\n c(\"left\", \"right\"),\n c(\"top\", \"bottom\")\n )\n data_frame0(\n .hand = vec_rep_each(hand, c(length(hand1), length(hand2))),\n .names = vec_c(self$labels0[hand1], self$labels[hand2]),\n .index = vec_c(hand1, hand2)\n )\n })\n plot_data <- vec_rbind(!!!plot_data, .names_to = \".panel\")\n plot_data$.panel <- factor(plot_data$.panel, names(data_index))\n plot_data$.hand <- factor(plot_data$.hand, switch_direction(\n direction, c(\"left\", \"right\"), c(\"bottom\", \"top\")\n ))\n\n # prepare data for the plot ------------------------------\n plot <- gguse_data(plot, plot_data)\n\n # set up facets\n if (nlevels(plot_data$.panel) > 1L) {\n if (inherits(plot$facet, \"FacetGrid\")) {\n facet <- switch_direction(\n direction,\n ggplot2::facet_grid(\n rows = ggplot2::vars(.data$.panel),\n scales = \"free_y\", space = \"free\",\n drop = FALSE, as.table = FALSE\n ),\n ggplot2::facet_grid(\n cols = ggplot2::vars(.data$.panel),\n scales = \"free_x\", space = \"free\",\n drop = FALSE, as.table = FALSE\n )\n )\n } else {\n facet <- switch_direction(\n direction,\n ggplot2::facet_wrap(\n facets = ggplot2::vars(.data$.panel),\n ncol = 1L, as.table = FALSE\n ),\n ggplot2::facet_wrap(\n facets = ggplot2::vars(.data$.panel),\n nrow = 1L, as.table = FALSE\n )\n )\n }\n } else {\n facet <- facet_stack(direction, object_name(self))\n }\n # `free_row` and `free_column` have nothing with `facet_stack`\n # it's safe to use it directly\n plot <- ggmelt_facet(plot, facet, free_row = TRUE, free_column = TRUE)\n plot$ggalign_link_data <- list(\n full_data1 = full_data1,\n full_data2 = full_data2,\n link_index = link_index,\n data_index = data_index,\n direction = direction,\n draw = .subset2(mark, \"draw\"),\n obs_size = self$obs_size\n )\n add_class(plot, \"ggalign_mark_plot\", \"patch_ggplot\")\n },\n finish_plot = function(self, plot, schemes, theme) {\n plot <- plot_add_schemes(plot, schemes)\n\n # save spacing for usage\n spacing <- calc_element(\n switch_direction(\n self$direction,\n \"panel.spacing.y\",\n \"panel.spacing.x\"\n ),\n theme\n ) %||% unit(0, \"mm\")\n\n # save spacing for usage\n plot$ggalign_link_data$spacing1 <-\n plot$ggalign_link_data$spacing2 <- spacing\n\n plot + theme_recycle()\n },\n summary = function(self, plot) {\n header <- ggproto_parent(CraftCross, self)$summary(plot)\n c(header, \" Add plot to annotate observations\")\n }\n)\n\nmark_use_facet <- function(plot, facet) {\n\n}\n"], ["/ggalign/R/ggfree.R", "#' Add ggplot to layout without alignment\n#'\n#' @description\n#' `r lifecycle::badge('experimental')`\n#'\n#' The `ggfree()` function allows you to incorporate a ggplot object into your\n#' layout. Unlike `ggalign()`, which aligns every axis value precisely,\n#' `ggfree()` focuses on integrating plots into the layout without enforcing\n#' strict axis alignment.\n#'\n#' @inheritParams ggalign\n#'\n#' @section ggplot2 specification:\n#' `ggalign` initializes a ggplot object. The underlying data is created using\n#' [`fortify_data_frame()`]. Please refer to this method for more details.\n#'\n#' When used in `quad_layout()`/`ggheatmap()`, if the data is inherited from the\n#' `quad_layout()` and the other direction aligns discrete variables, following\n#' columns will be added:\n#'\n#' - `.extra_panel`: Provides the panel information for the column (left or\n#' right annotation) or row (top or bottom annotation).\n#' - `.extra_index`: The index information for the column (left or right\n#' annotation) or row (top or bottom annotation).\n#'\n#' @examples\n#' ggheatmap(matrix(rnorm(56), nrow = 7)) +\n#' anno_top() +\n#' align_dendro() +\n#' ggfree(mtcars, aes(wt, mpg)) +\n#' geom_point()\n#' @export\nggfree <- function(data = waiver(), ..., size = NULL, active = NULL) {\n UseMethod(\"ggfree\", data)\n}\n\n#' @inheritParams ggplot2::ggplot\n#' @importFrom ggplot2 ggplot\n#' @export\n#' @rdname ggfree\nggfree.default <- function(data = waiver(), mapping = aes(), ...,\n size = NULL, active = NULL) {\n data <- fortify_data_frame(data = data, ...)\n new_free_gg(\n plot = ggplot(data = NULL, mapping = mapping),\n data = data,\n size = size,\n active = active\n )\n}\n\n#' @export\nggfree.uneval <- function(data = waiver(), ...) {\n cli_abort(c(\n \"{.arg data} cannot be {.obj_type_friendly {data}}\",\n \"i\" = \"Have you misspelled the {.arg data} argument in {.fn ggalign}\"\n ))\n}\n\n#' @export\nggfree.ggplot <- function(data = waiver(), ..., size = NULL, active = NULL) {\n rlang::check_dots_empty()\n plot <- data\n # In ggplot2, `waiver()` was regard to no data\n data <- plot$data %|w|% NULL\n plot <- gguse_data(plot, waiver())\n new_free_gg(plot, data, size = size, active = active)\n}\n\nnew_free_gg <- function(plot, data, size, active,\n call = caller_call()) {\n assert_active(active, allow_null = TRUE, call = call)\n active <- update_active(active, new_active(use = TRUE))\n new_craftbox(\n FreeGg,\n # new field for FreeGg\n input_data = data,\n # slots for the plot\n plot = plot,\n size = size,\n active = active,\n schemes = default_schemes(data),\n call = call\n )\n}\n\n#' @importFrom ggplot2 ggproto\nFreeGg <- ggproto(\"FreeGg\", Craftsman,\n free_facet = TRUE,\n free_limits = TRUE,\n interact_layout = function(self, layout) {\n layout_data <- layout@data\n if (is.waive(input_data <- self$input_data)) { # inherit from the layout\n data <- layout_data\n self$labels <- vec_names(layout_data)\n\n # for data inherit from the layout, and the design is for discrete\n # variable, we'll integrate the design into the plot data\n self$use_design <- is_stack_layout(layout)\n\n # if the layout data is from the quad-layout, we use the discrete\n # `design`\n self$use_extra_design <- is_stack_layout(layout) &&\n isTRUE(layout@heatmap$quad_matrix)\n } else if (is.function(input_data)) {\n if (is.null(layout_data)) {\n cli_abort(c(\n sprintf(\n \"{.arg data} in %s cannot be a function\",\n object_name(self)\n ),\n i = sprintf(\"no data was found in %s\", self$layout_name)\n ))\n }\n data <- input_data(layout_data)\n } else {\n data <- input_data\n }\n self$data <- ggalign_data_restore(\n fortify_data_frame(data, call = self$call), layout_data\n )\n layout\n },\n build_plot = function(self, plot, design, extra_design = NULL,\n previous_design = NULL) {\n if (is.function(data <- self$data)) {\n data <- NULL\n }\n if (is.null(data)) {\n return(gguse_data(plot, data))\n }\n if (isTRUE(self$use_extra_design) &&\n is_discrete_design(extra_design) &&\n !is.null(.subset2(extra_design, \"nobs\"))) {\n extra_plot_data <- data_frame0(\n .extra_panel = .subset2(extra_design, \"panel\"),\n .extra_index = .subset2(extra_design, \"index\")\n )\n } else {\n extra_plot_data <- NULL\n }\n\n # if inherit from the parent layout\n if (isTRUE(self$use_design) &&\n is_discrete_design(design) &&\n !is.null(.subset2(design, \"nobs\"))) {\n plot_data <- data_frame0(\n .panel = .subset2(design, \"panel\"),\n .index = .subset2(design, \"index\"),\n .names = .subset(self$labels, .subset2(design, \"index\"))\n )\n if (!is.null(extra_plot_data)) {\n plot_data <- cross_join(plot_data, extra_plot_data)\n data <- full_join(data, plot_data,\n by.x = c(\".column_index\", \".row_index\"),\n by.y = c(\".extra_index\", \".index\")\n )\n } else {\n data <- full_join(data, plot_data,\n by.x = \".row_index\", by.y = \".index\"\n )\n }\n } else if (!is.null(extra_plot_data)) {\n data <- full_join(data, extra_plot_data,\n by.x = \".column_index\", by.y = \".extra_index\"\n )\n }\n gguse_data(plot, data)\n },\n summary = function(self, plot) {\n header <- ggproto_parent(Craftsman, self)$summary(plot)\n c(header, \" Add plot without alignment\")\n }\n)\n"], ["/ggalign/R/craft-cross-link.R", "#' Add a plot to connect selected observations\n#'\n#' @param link A [`link_draw()`] object that defines how to draw the links,\n#' such as [`link_line()`].\n#' @param on_top A boolean value indicating whether to draw the link on top of\n#' the plot panel (`TRUE`) or below (`FALSE`).\n#' @inheritParams cross_none\n#' @inheritParams ggmark\n#'\n#' @section ggplot2 Specification:\n#' The `cross_link` function initializes a `ggplot` object but does not\n#' initialize any data. Using [`scheme_data()`] to change the internal data if\n#' needed.\n#'\n#' @export\ncross_link <- function(link, data = waiver(), ...,\n on_top = TRUE, obs_size = 1,\n inherit_index = NULL, inherit_panel = NULL,\n inherit_nobs = NULL,\n size = NULL, active = NULL) {\n if (!inherits(link, \"ggalign_link_draw\")) {\n cli_abort(\"{.arg link} must be a {.fn link_draw} object\")\n }\n assert_obs_size(obs_size)\n assert_active(active)\n active <- update_active(active, new_active(use = TRUE))\n cross(CrossLink,\n data = data, data_params = list2(...),\n link = link, obs_size = obs_size,\n plot = ggplot(), size = size,\n schemes = default_schemes(),\n active = active,\n on_top = on_top,\n inherit_nobs = inherit_nobs,\n inherit_panel = inherit_panel,\n inherit_index = inherit_index\n )\n}\n\n#' @importFrom ggplot2 ggproto ggproto_parent\n#' @importFrom grid gTree\n#' @include craft-cross-.R\nCrossLink <- ggproto(\"CrossLink\", CraftCross,\n interact_layout = function(self, layout) {\n if (!self$in_linear) { # only used for linear coordinate\n cli_abort(c(\n sprintf(\n \"Cannot add %s to %s\",\n object_name(self), layout_name\n ),\n i = sprintf(\n \"%s can only be used in linear layout\",\n object_name(self)\n )\n ))\n }\n ggproto_parent(CraftCross, self)$interact_layout(layout)\n },\n build_plot = function(self, plot, design, extra_design = NULL,\n previous_design = NULL) {\n if (is.null(.subset2(previous_design, \"nobs\"))) {\n cli_abort(\n sprintf(\n \"layout {.field nobs} for %s before %s is not initialized \",\n self$layout_name, object_name(self)\n )\n )\n }\n if (is.null(.subset2(design, \"nobs\"))) {\n cli_abort(\n sprintf(\n \"layout {.field nobs} for %s after %s is not initialized \",\n self$layout_name, object_name(self)\n )\n )\n }\n\n direction <- self$direction\n position <- self$position\n\n # parse links --------------------------------------------\n link <- self$link\n design1 <- previous_design\n design2 <- design\n full_data1 <- split(\n seq_len(.subset2(design1, \"nobs\")),\n .subset2(design1, \"panel\")\n )\n full_data2 <- split(\n seq_len(.subset2(design2, \"nobs\")),\n .subset2(design2, \"panel\")\n )\n links <- .subset2(link, \"links\")\n # set default links for link_line()\n if (is_empty(links) &&\n inherits(link, \"ggalign_link_line\") &&\n identical(.subset2(design1, \"nobs\"), .subset2(design2, \"nobs\"))) {\n links <- lapply(seq_len(.subset2(design1, \"nobs\")), function(i) {\n rlang::new_formula(i, i)\n })\n links <- pair_links(!!!links)\n }\n link_index <- make_links_data(\n links,\n design1 = design1, design2 = design2,\n labels1 = self$labels0, labels2 = self$labels\n )\n data_index <- lapply(link_index, function(index) {\n if (is.null(index)) {\n return(NULL)\n }\n hand1 <- .subset2(index, \"hand1\")\n hand2 <- .subset2(index, \"hand2\")\n list(\n hand1 = .subset2(design1, \"index\")[hand1],\n hand2 = .subset2(design2, \"index\")[hand2]\n )\n })\n plot$ggalign_link_data <- list(\n full_data1 = full_data1,\n full_data2 = full_data2,\n link_index = link_index,\n data_index = data_index,\n direction = direction,\n draw = .subset2(link, \"draw\"),\n obs_size = self$obs_size\n )\n plot\n },\n finish_plot = function(self, plot, schemes, theme) {\n plot <- plot_add_schemes(plot, schemes)\n\n # save spacing for usage\n spacing <- calc_element(\n switch_direction(\n self$direction,\n \"panel.spacing.y\",\n \"panel.spacing.x\"\n ),\n theme\n ) %||% unit(0, \"mm\")\n\n # setup the grob\n grob <- inject(gTree(\n !!!plot$ggalign_link_data,\n spacing1 = spacing,\n spacing2 = spacing,\n cl = \"ggalignLinkTree\"\n ))\n plot$ggalign_link_data <- NULL\n\n # insert the grob\n plot <- plot + inset(grob, on_top = self$on_top)\n ggremove_margin(plot, self$direction) + theme_recycle()\n },\n summary = function(self, plot) {\n header <- ggproto_parent(CraftCross, self)$summary(plot)\n c(header, \" Add plot to connect selected observations\")\n }\n)\n"], ["/ggalign/R/craft-cross-.R", "cross <- function(cross = NULL, data = waiver(),\n data_params = list(), ...,\n inherit_index = NULL,\n inherit_panel = NULL,\n inherit_nobs = NULL,\n plot = NULL, active = NULL, size = NULL, schemes = NULL,\n data_arg = caller_arg(data),\n call = caller_call()) {\n if (override_call(call)) {\n call <- current_call()\n }\n new_craftbox(\n craftsman = cross %||% CraftCross,\n data = allow_lambda(data), data_params = data_params,\n ...,\n inherit_nobs = inherit_nobs,\n inherit_panel = inherit_panel,\n inherit_index = inherit_index,\n plot = plot, active = active, size = size, schemes = schemes,\n data_arg = data_arg, call = call\n )\n}\n\n#' @importFrom ggplot2 ggproto ggproto_parent\n#' @include craftbox-.R\nCraftCross <- ggproto(\n \"CraftCross\", Craftsman,\n free_facet = TRUE,\n free_limits = TRUE,\n data_params = NULL,\n inherit_nobs = NULL,\n inherit_panel = NULL,\n inherit_index = NULL,\n interact_layout = function(self, layout) {\n # 1. check layout is `*_cross()`\n # 2. add `cross_points`\n # 3. add `odesign`\n # 4. define `labels`, we'll rename the `labels` to `labels0`\n layout <- ggproto_parent(CrossGg, self)$interact_layout(layout)\n\n # will define `labels0`\n self$labels0 <- self$labels\n\n # check the previous (between two `break_points`) define has been\n # initialized\n if (length(layout@break_points) &&\n is.null(.subset2(layout@design, \"nobs\"))) {\n cli_abort(sprintf(\n \"layout {.field nobs} for %s must be initialized before adding %s\",\n self$layout_name, object_name(self)\n ))\n }\n\n # setup data\n layout_data <- layout@data\n design <- layout@design\n\n if (is.waive(input_data <- self$data)) { # inherit from the layout\n data <- layout_data\n # `data` is NULL, `inherit_nobs` can be `TRUE` or `FALSE`, we by\n # default regard `inherit_nobs` as `TRUE`\n if (is.null(data) && isFALSE(self$inherit_nobs)) {\n design[\"nobs\"] <- list(NULL)\n }\n\n # `data` is not `NULL`, the `nobs` will always be the same with\n # previous design, nothing to do\n } else {\n if (is.function(input_data)) {\n if (is.null(layout_data)) {\n cli_abort(c(\n sprintf(\n \"{.arg data} in %s cannot be a function\",\n object_name(self)\n ),\n i = sprintf(\"no data was found in %s\", self$layout_name)\n ))\n }\n data <- input_data(layout_data)\n } else {\n data <- input_data\n }\n data <- inject(\n fortify_matrix(\n data, !!!self$data_params,\n data_arg = self$data_arg,\n call = self$call\n )\n ) %|w|% NULL\n if (isTRUE(self$inherit_nobs)) { # we require inherit nobs\n # we check if the data match original data dimention\n if (!is.null(data) &&\n !is.null(.subset2(design, \"nobs\")) &&\n NROW(data) != .subset2(design, \"nobs\")) {\n cli_abort(c(\n sprintf(\n \"%s (nobs: %d) is not compatible with the %s (nobs: %d)\",\n object_name(self), NROW(data), layout_name, layout_nobs\n ),\n i = \"try to set {.code inherit_nobs = FALSE}\"\n ))\n }\n } else { # for `FALSE` and `NULL`\n if (is.null(data)) {\n design[\"nobs\"] <- list(NULL)\n } else {\n if (NROW(data) == 0L) {\n cli_abort(\"{.arg data} cannot be empty\",\n call = self$call\n )\n }\n design[\"nobs\"] <- list(NROW(data))\n }\n }\n }\n\n # we keep the names from the layout data for usage\n self$labels <- vec_names(data)\n\n # determine if we should inherit panel\n # by default, `inherit_panel = FALSE`\n if (isTRUE(self$inherit_panel)) {\n if (is.null(self$labels0)) {\n cli_abort(c(\n \"Cannot inherit panel from the layout\",\n i = \"No labels found in the layout data\"\n ))\n }\n if (is.null(self$labels)) {\n cli_abort(c(\n \"Cannot inherit panel from the layout\",\n i = \"No labels found in the current {.arg data}\"\n ))\n }\n if (!all(self$labels %in% self$labels0)) {\n cli_abort(c(\n \"Cannot inherit panel from the layout\",\n i = \"Some labels in the current data are not found in the previous layout data\"\n ))\n }\n if (!is.null(panel <- .subset2(design, \"panel\"))) {\n design[\"panel\"] <- list(\n droplevels(panel[match(self$labels, self$labels0)])\n )\n }\n } else {\n design[\"panel\"] <- list(NULL)\n }\n\n # determine if we should inherit panel\n # by default, `inherit_index = FALSE`\n if (isTRUE(self$inherit_index)) {\n if (is.null(self$labels0)) {\n cli_abort(c(\n \"Cannot inherit ordering index from the layout\",\n i = \"No labels found in the previous layout data\"\n ))\n }\n\n if (is.null(self$labels)) {\n cli_abort(c(\n \"Cannot inherit ordering index from the layout\",\n i = \"No labels found in the current {.arg data}\"\n ))\n }\n\n if (!all(self$labels %in% self$labels0)) {\n cli_abort(c(\n \"Cannot inherit ordering index from the layout\",\n i = \"Some labels in the current data are not found in the previous layout data\"\n ))\n }\n\n if (!is.null(index <- .subset2(design, \"index\"))) {\n new_index <- order(match(\n self$labels,\n vec_slice(self$labels0, index)\n ))\n\n # we always make the index following the panel\n if (!is.null(panel <- .subset2(design, \"panel\"))) {\n new_index <- reorder_index(panel, new_index)\n }\n design[\"index\"] <- list(new_index)\n }\n } else {\n design[\"index\"] <- list(NULL)\n }\n\n # reset layout data\n layout@data <- data # don't restore the attribute\n\n # update the design\n layout@design <- design\n\n # udpate break_points\n layout@break_points <- c(layout@break_points, length(layout@plot_list))\n layout\n }\n)\n"], ["/ggalign/R/layout-align.R", "#' Set Expansion for the Layout\n#'\n#' @description\n#' To align axes, it is important to keep the expansion consistent across all\n#' plots in the layout. You can add a `layout_expand` object to the layout. For\n#' the `quad_layout()` function, you must specify `x` and `y` arguments. For\n#' other layouts, you can pass the expansion values using `...` directly.\n#'\n#' @param ... A list of range expansion constants, used to add padding around\n#' the data to ensure they are placed some distance away from the axes. Use the\n#' convenience function [`expansion()`][ggplot2::expansion()] to generate the\n#' values.\n#' @param x,y Same as `...`, but specifically for `quad_layout()`.\n#'\n#' @importFrom rlang list2\n#' @keywords internal\nlayout_expand <- function(..., x = waiver(), y = waiver()) {\n if (...length() > 0L && (!is.waive(x) || !is.waive(y))) {\n cli_abort(\n \"Cannot mix the usage of {.arg ...} with {.arg x}/{.arg y} argument\"\n )\n }\n if (...length() > 0L) {\n ans <- list2(...)\n names(ans) <- NULL\n } else {\n ans <- list(x = x, y = y)\n }\n structure(ans, class = \"ggalign_layout_expand\")\n}\n\n#' Set continuous limits for the layout\n#'\n#' @description\n#' To align continuous axes, it is important to keep the limits consistent\n#' across all plots in the layout. You can set the limits by passing a function\n#' directly to the `limits` or `xlim`/`ylim` argument, using `...` only.\n#' Alternatively, you can add a `continuous_limits()` object to the layout. For\n#' the `quad_layout()` function, you must specify `x`/`y` arguments. For other\n#' layouts, you should pass the limits using `...` directly.\n#'\n#' @param ... A list of two numeric values, specifying the left/lower limit and\n#' the right/upper limit of the scale.\n#' @inheritParams layout_expand\n#' @importFrom rlang list2\n#' @export\ncontinuous_limits <- function(..., x = waiver(), y = waiver()) {\n if (...length() > 0L && (!is.waive(x) || !is.waive(y))) {\n cli_abort(\n \"Cannot mix the usage of {.arg ...} with {.arg x}/{.arg y} argument\"\n )\n }\n if (...length() > 0L) {\n ans <- list2(...)\n names(ans) <- NULL\n } else {\n ans <- list(x = x, y = y)\n }\n structure(ans, class = c(\"continuous_limits\", \"layout_design\"))\n}\n\n# layout params are used to align the observations\ndiscrete_design <- function(panel = NULL, index = NULL, nobs = NULL) {\n structure(\n list(panel = panel, index = index, nobs = nobs),\n class = c(\"discrete_design\", \"layout_design\")\n )\n}\n\n################################################################\nis_continuous_design <- function(x) {\n is.null(x) || inherits(x, \"continuous_limits\")\n}\n\nis_discrete_design <- function(x) inherits(x, \"discrete_design\")\n\n#' Layout can align ordinal variable or continuous variable\n#'\n#' @param x A `LayoutProto` object.\n#' @noRd\nis_layout_discrete <- function(x, ...) UseMethod(\"is_layout_discrete\")\n\nis_layout_continuous <- function(x, ...) UseMethod(\"is_layout_continuous\")\n\n################################################################\n# Initialize the index and panel\n# Reorder the panel based the ordering index and\nsetup_design <- function(design) {\n # for continuous axis, do noting special\n if (is_continuous_design(design)) return(design) # styler: off\n # if `nobs` is not initialized, it means no `Align` object exist\n # it's not necessary to initialize the `panel` and `index`\n # this is for `stack_layout` which may have no data\n if (is.null(nobs <- .subset2(design, \"nobs\"))) {\n return(design)\n }\n panel <- .subset2(design, \"panel\") %||% factor(rep_len(1L, nobs))\n index <- .subset2(design, \"index\") %||% reorder_index(panel)\n discrete_design(panel[index], index, nobs)\n}\n\nreorder_index <- function(panel, index = NULL) {\n index <- index %||% seq_along(panel)\n unlist(split(index, panel[index]), recursive = FALSE, use.names = FALSE)\n}\n\n############################################################\n#' @keywords internal\nupdate_design <- function(layout, ..., design, object_name) {\n UseMethod(\"update_design\")\n}\n\n#' @importFrom methods slot slot<-\n#' @export\nupdate_design.QuadLayout <- function(layout, ..., direction, design,\n object_name) {\n slot(layout, direction) <- design\n if (is_horizontal(direction)) {\n if (!is.null(left <- layout@left)) {\n layout@left <- update_design(left,\n design = design, object_name = object_name\n )\n }\n if (!is.null(right <- layout@right)) {\n layout@right <- update_design(right,\n design = design, object_name = object_name,\n from_head = TRUE\n )\n }\n } else {\n if (!is.null(top <- layout@top)) {\n layout@top <- update_design(top,\n design = design, object_name = object_name\n )\n }\n if (!is.null(bottom <- layout@bottom)) {\n layout@bottom <- update_design(bottom,\n design = design, object_name = object_name,\n from_head = TRUE\n )\n }\n }\n layout\n}\n\n#' @importFrom methods slot slot<-\n#' @export\nupdate_design.StackLayout <- function(layout, ..., design, object_name) {\n layout@design <- design\n layout@plot_list <- lapply(layout@plot_list, function(plot) {\n if (is_craftbox(plot)) return(plot) # styler: off\n update_design(plot,\n direction = layout@direction,\n design = design\n )\n })\n layout\n}\n\n#' @export\nupdate_design.CircleLayout <- update_design.StackLayout\n\n#' @importFrom methods slot slot<-\n#' @export\nupdate_design.StackCross <- function(layout, ..., design, object_name,\n from_head = FALSE) {\n # `design` must be a discrete_design()\n design_list <- c(layout@odesign, list(layout@design))\n\n # for cross_points, the updating will span it, but only update the panel\n # information\n cross_points <- layout@cross_points\n\n # the break_points set breaks, updating won't span the break points\n break_points <- layout@break_points\n\n plot_list <- layout@plot_list\n n <- length(plot_list)\n points <- c(cross_points, n)\n point_index <- seq_along(points)\n if (!from_head) point_index <- rev(point_index)\n for (i in point_index) {\n cross_point <- .subset(points, i)\n\n # we first update the design in the updated tail\n # it means the first design when `from_head` is `TRUE`\n # the last design when `from_head` is `FALSE`\n if ((from_head && i == 1L) || (!from_head && cross_point == n)) {\n new_design <- design\n } else if (!from_head && any(cross_point == break_points)) {\n break\n } else {\n # for design not in updated tail, we'll only update `panel` and\n # `nobs`, we check the new panel doesn't break the original index\n new_nobs <- .subset2(design, \"nobs\")\n new_panel <- .subset2(design, \"panel\")\n new_design <- .subset2(design_list, i)\n # we check the new panel don't disrupt the ordering index\n if (!is.null(new_panel) &&\n !is.null(old_index <- .subset2(new_design, \"index\"))) {\n # we always prevent from reordering twice.\n new_index <- reorder_index(new_panel, old_index)\n if (!all(old_index == new_index)) {\n cli_abort(sprintf(\n \"%s disrupt the previously established ordering index of %s (%d)\",\n object_name, object_name(layout), i\n ))\n }\n new_design[\"index\"] <- list(new_index)\n }\n new_design[\"nobs\"] <- list(new_nobs)\n new_design[\"panel\"] <- list(new_panel)\n }\n design_list[i] <- list(new_design)\n\n # we then update the design for each plot\n if (i == 1L) {\n subset <- seq_len(cross_point)\n } else {\n subset <- (.subset(points, i - 1L) + 1L):cross_point\n }\n\n layout@plot_list[subset] <- lapply(\n plot_list[subset], function(plot) {\n if (is_craftbox(plot)) {\n return(plot)\n }\n update_design(plot,\n direction = layout@direction,\n design = new_design\n )\n }\n )\n if (from_head && any(cross_point == break_points)) break\n }\n layout@odesign <- vec_slice(design_list, seq_len(length(design_list) - 1L))\n layout@design <- design_list[[length(design_list)]]\n layout\n}\n\n############################################################\nmelt_discrete_design <- function(old, new, old_name, new_name,\n call = caller_call()) {\n old_nobs <- .subset2(old, \"nobs\")\n new_nobs <- .subset2(new, \"nobs\")\n if (is.null(new_nobs)) { # no `nobs` provided\n nobs <- old_nobs\n } else if (is.null(old_nobs)) {\n nobs <- new_nobs\n } else if (!identical(new_nobs, old_nobs)) {\n cli_abort(sprintf(\n \"%s (nobs: %d) is not compatible with the %s (nobs: %d)\",\n new_name, new_nobs, old_name, old_nobs\n ), call = call)\n } else {\n nobs <- new_nobs\n }\n\n # check panel\n old_panel <- .subset2(old, \"panel\")\n new_panel <- .subset2(new, \"panel\")\n\n if (is.null(new_panel)) { # no panel provided\n panel <- old_panel\n } else if (!is.null(old_panel) && !(new_panel %nest% old_panel)) {\n cli_abort(sprintf(\n \"%s disrupt the previously established panel groups of %s\",\n new_name, old_name\n ), call = call)\n } else {\n panel <- new_panel\n }\n\n # check index\n old_index <- .subset2(old, \"index\")\n new_index <- .subset2(new, \"index\")\n if (is.null(new_index)) {\n index <- old_index\n } else {\n index <- new_index\n }\n\n # we always make the index following the panel\n if (!is.null(panel) && !is.null(index)) {\n index <- reorder_index(panel, index)\n }\n\n # we always prevent from reordering twice.\n if (!is.null(old_index) && !all(old_index == index)) {\n cli_abort(sprintf(\n \"%s disrupt the previously established ordering index of %s\",\n new_name, old_name\n ), call = call)\n }\n discrete_design(panel, index, nobs)\n}\n\n#######################################################################\n# ggplot2 add default scales in `compute_aesthetics` process\n# then ggplot2 transform all scales\n# layout:\n# in ggplot_build\n# - `setup`:\n# - call `facet$setup_params`\n# - attach `plot_env`\n# - call `facet$setup_data`\n# - call `facet$compute_layout`\n# - call `coord$setup_layout`\n# - call `facet$map_data`\n# - `train_position`: (run twice)\n# - call `facet$init_scales`\n# - call `facet$train_scales`\n# - `setup_panel_params`\n# - call `coord$modify_scales`: we align scales here, since this step\n# scales have been trained\n# - call `coord$setup_panel_params`: `view_scales_from_scale()`\n# - `map_position`\n# - `setup_panel_guides`\n# - call `coord$setup_panel_guides`\n# - call `coord$train_panel_guides`\n# in ggplot_gtable\n# - `layout$render`:\n# - call `facet$draw_back`\n# - call `facet$draw_front`\n# - call `coord$draw_panel` for each panel\n# - call `facet$draw_panels`: only once\n# - call `facet$init_gtable`:\n# - call `facet$attach_axes`:\n# - call `coord$render_axis_h`:\n# - call `guide$draw`:\n# - call `coord$render_axis_v`:\n# - call `guide$draw`:\n# - call `facet$attach_strips`:\n\n#' Set `limits`, `breaks`, `labels` for each panel\n#'\n#' @param x,y design for the layout.\n#' @keywords internal\n#' @noRd\nggalign_design <- function(x = NULL, y = NULL,\n xlabels = NULL, ylabels = NULL,\n xlim = TRUE, ylim = TRUE) {\n structure(\n list(\n x = x, y = y,\n xlabels = xlabels, ylabels = ylabels,\n xlim = xlim, ylim = ylim\n ),\n class = \"ggalign_design\"\n )\n}\n\nsetup_discrete_limits <- function(axis, design, n_panels) {\n panel <- .subset2(design, \"panel\")\n index <- .subset2(design, \"index\")\n if (n_panels == 1L) {\n list(range(index) + c(-0.5, 0.5))\n } else {\n # For y-axis, ggplot arrange panel from top to bottom,\n # we always choose to reverse the panel order\n if (axis == \"y\") panel <- fct_rev(panel)\n lapply(split(seq_along(index), panel), function(plot_index) {\n range(plot_index) + c(-0.5, 0.5)\n })\n }\n}\n\n#' @importFrom ggplot2 ggplot_add ggproto ggproto_parent\n#' @export\nggplot_add.ggalign_design <- function(object, plot, object_name, ...) {\n x_design <- .subset2(object, \"x\")\n y_design <- .subset2(object, \"y\")\n if (is.null(x_design) && is.null(y_design)) {\n return(plot)\n }\n ParentCoord <- plot$coordinates\n plot$coordinates <- ggproto(\n NULL, ParentCoord,\n num_of_panels = NULL,\n panel_counter = NULL,\n n_row_panels = NULL, # should be the number of panels in y\n n_column_panels = NULL, # should be the number of panels in x\n setup_layout = function(self, layout, params) {\n # we always initialize the number of panels and a panel counter\n self$num_of_panels <- vec_unique_count(.subset2(layout, \"PANEL\"))\n self$panel_counter <- 0L\n self$n_column_panels <- vec_unique_count(.subset2(layout, \"COL\"))\n self$n_row_panels <- vec_unique_count(.subset2(layout, \"ROW\"))\n if (.subset2(object, \"xlim\") && !is.null(x_design)) {\n if (is_discrete_design(x_design)) {\n self$xlim_list <- setup_discrete_limits(\n \"x\", x_design, self$n_column_panels\n )\n } else {\n self$xlim_list <- x_design\n }\n }\n if (.subset2(object, \"ylim\") && !is.null(y_design)) {\n if (is_discrete_design(y_design)) {\n self$ylim_list <- setup_discrete_limits(\n \"y\", y_design, self$n_row_panels\n )\n } else {\n self$ylim_list <- y_design\n }\n }\n # call the parent method\n ggproto_parent(ParentCoord, self)$setup_layout(layout, params)\n },\n # take the tricks to modify scales in place\n modify_scales = function(self, scales_x, scales_y) {\n # for each scale, we set the `breaks` and `labels`\n if (is_discrete_design(x_design)) {\n align_discrete_scales(\n \"x\", scales_x, x_design,\n labels = .subset2(object, \"xlabels\"),\n n_panels = self$n_column_panels,\n circle_layout = inherits(ParentCoord, \"CoordRadial\")\n )\n }\n if (is_discrete_design(y_design)) {\n align_discrete_scales(\n \"y\", scales_y, y_design,\n labels = .subset2(object, \"ylabels\"),\n n_panels = self$n_row_panels,\n circle_layout = inherits(ParentCoord, \"CoordRadial\")\n )\n }\n ggproto_parent(ParentCoord, self)$modify_scales(scales_x, scales_y)\n },\n setup_panel_params = function(self, scale_x, scale_y, params = list()) {\n # `setup_panel_params()` will utilize the `limits`\n # set limits here to ensure each plot will have the same limits\n cur_panel <- self$panel_counter + 1L\n if (!is.null(self$xlim_list)) {\n xlim <- .subset2(\n self$xlim_list,\n recycle_whole(cur_panel, self$n_column_panels)\n )\n if (is_discrete_design(x_design) && scale_x$is_discrete() &&\n !is.null(scale_x$range$range)) {\n # for discrete scale, the limits starts from zero in each\n # panel\n xlim <- xlim - (min(xlim) - 0.5)\n }\n if (inherits(self, \"CoordRadial\")) {\n self$limits$theta <- xlim\n } else {\n self$limits$x <- xlim\n }\n }\n if (!is.null(self$ylim_list)) {\n ylim <- .subset2(\n self$ylim_list,\n recycle_each(cur_panel, self$n_column_panels)\n )\n if (is_discrete_design(y_design) && scale_y$is_discrete() &&\n !is.null(scale_y$range$range)) {\n # for discrete scale, the limits starts from zero in each\n # panel\n ylim <- ylim - (min(ylim) - 0.5)\n }\n if (inherits(self, \"CoordRadial\")) {\n self$limits$r <- ylim\n } else {\n self$limits$y <- ylim\n }\n }\n self$panel_counter <- cur_panel\n ggproto_parent(ParentCoord, self)$setup_panel_params(\n scale_x = scale_x, scale_y = scale_y, params = params\n )\n }\n )\n plot\n}\n\nalign_discrete_scales <- function(axis, scales, design, labels, n_panels,\n circle_layout) {\n panel <- .subset2(design, \"panel\")\n index <- .subset2(design, \"index\")\n\n if (n_panels == 1L) {\n panel <- factor(vec_rep(1L, length(index)))\n } else {\n # For y-axis, ggplot arrange panel from top to bottom,\n # we always choose to reverse the panel order\n if (axis == \"y\") panel <- fct_rev(panel)\n }\n if (is.null(labels)) {\n data_labels <- NULL\n } else {\n data_labels <- split(labels, panel)\n }\n data_index <- split(index, panel)\n plot_index <- split(seq_along(index), panel)\n default_expand <- ggplot2::expansion()\n for (i in seq_along(scales)) {\n scale <- .subset2(scales, i)\n # we always use the discrete scale to determine labels and breaks\n # https://github.com/tidyverse/ggplot2/blob/7fb4c382f9ea332844d469663a8047355a88dd7a/R/scale-.R#L927\n # setup breaks and labels --------------------\n if (is.null(data_labels) &&\n is.waive(scale$labels) &&\n is.waive(scale$breaks)) {\n # special case for data have no labels\n # By default we also remove the breaks\n scale$breaks <- NULL\n scale$labels <- NULL\n } else {\n dindex <- .subset2(data_index, i)\n pindex <- .subset2(plot_index, i)\n labels <- .subset2(data_labels, i)\n scale$breaks <- get_discrete_breaks(scale, pindex, dindex, labels)\n scale$labels <- get_discrete_labels(\n scale, scale$breaks, pindex, dindex, labels\n )\n }\n\n # by default we elways remove any expansion\n # we don't allow the set of expansion for discrete variables\n # otherwise, ggmark and `cross_mark` won't work properly\n if (!circle_layout) scale$expand <- default_expand\n\n # for continuous scale, we don't allow the trans\n # if (!scale$is_discrete() && !identical(scale$trans$name, \"identity\")) {\n # cli_warn(sprintf(\n # \"{.arg trans} must be {.field identity} in {.code %s}\",\n # deparse(scale$call)\n # ))\n # scale$trans <- scales::as.transform(\"identity\")\n # }\n }\n}\n\n#' @importFrom rlang is_empty\nget_discrete_breaks <- function(scale, pindex, dindex, labels) {\n if (scale$is_empty()) return(numeric()) # styler: off\n breaks <- scale$breaks\n if (identical(breaks, NA)) {\n cli_abort(c(\n \"Invalid {.arg breaks} specification.\",\n i = \"Use {.code NULL}, not {.code NA}.\"\n ), call = scale$call)\n }\n if (is.null(breaks)) {\n return(NULL)\n }\n if (is.waive(breaks)) {\n if (scale$is_discrete() &&\n !is.null(labels) &&\n !is.null(scale$range$range) &&\n all(scale$range$range %in% labels)) {\n ans <- labels\n } else {\n ans <- pindex\n }\n } else {\n if (is.null(labels)) {\n limits <- dindex\n } else {\n limits <- labels\n }\n if (is.function(breaks)) {\n breaks <- breaks(limits)\n }\n\n if (is.factor(breaks) || is.character(breaks)) {\n # we interpreted the character breaks as the names of the original\n # matrix data.\n pos <- match(\n as.character(limits),\n vec_cast(breaks, character(),\n x_arg = \"breaks\", call = scale$call\n )\n )\n } else {\n # By default, we interpreted the breaks as the data index\n # If wrapped with `I()`, we interpreted it as the plot index\n if (inherits(breaks, \"AsIs\")) { # plot index\n pos <- match(pindex, vec_cast(breaks, integer(),\n x_arg = \"breaks\", call = scale$call\n ))\n } else { # data index\n pos <- match(dindex, vec_cast(breaks, integer(),\n x_arg = \"breaks\", call = scale$call\n ))\n }\n }\n index <- which(!is.na(pos))\n if (is_empty(index)) {\n return(NULL)\n }\n pos <- pos[index]\n if (scale$is_discrete() &&\n !is.null(labels) &&\n !is.null(scale$range$range) &&\n all(scale$range$range %in% labels)) {\n ans <- structure(labels[index], index = index, pos = pos)\n } else {\n ans <- structure(pindex[index], index = index, pos = pos)\n }\n }\n ans\n}\n\n#' @importFrom rlang is_empty\nget_discrete_labels <- function(scale, breaks, pindex, dindex, labels) {\n scale_labels <- scale$labels\n if (is_empty(breaks) || is.null(scale_labels)) { # if no breaks, no labels\n return(NULL)\n }\n\n if (identical(scale_labels, NA)) {\n cli_abort(c(\n \"Invalid {.arg labels} specification.\",\n i = \"Use {.code NULL}, not {.code NA}.\"\n ), call = scale$call)\n }\n\n # Need to ensure that if breaks were dropped\n if (!is.null(index <- attr(breaks, \"index\"))) {\n dindex <- dindex[index]\n labels <- labels[index]\n }\n\n # if layout have no names, use the data index directly\n # re-defined the breaks, the plot use the coordinates index\n # we interpreted user input as the data index\n if (is.null(labels)) {\n user_breaks <- dindex\n } else {\n user_breaks <- labels\n }\n if (is.waive(scale_labels)) { # By default, use the breaks\n user_breaks\n } else if (is.function(scale_labels)) {\n scale_labels(user_breaks)\n } else if (!is.null(names(scale_labels))) {\n # If labels have names, use them to match with breaks\n map <- match(as.character(user_breaks), names(scale_labels))\n user_breaks[map] <- scale_labels[!is.na(map)]\n user_breaks\n } else {\n # Need to ensure that if breaks were dropped, corresponding labels\n # are too\n if (is.null(pos <- attr(breaks, \"pos\"))) {\n if (inherits(scale_labels, \"AsIs\")) { # already in the plot index\n # we sort the `pos` so labels ordering won't be changed\n scale_labels <- scale_labels[pindex]\n } else { # in the data index\n scale_labels <- scale_labels[dindex]\n }\n } else {\n if (inherits(scale_labels, \"AsIs\")) { # already in the plot index\n # we sort the `pos` so labels ordering won't be changed\n scale_labels <- scale_labels[sort(pos)]\n } else { # in the data index\n scale_labels <- scale_labels[pos]\n }\n }\n scale_labels\n }\n}\n\n######################################################\n# this will remove the old coordinate,\n# so always run firstly\ngguse_linear_coord <- function(plot, layout_name) {\n coord <- plot$coordinates\n if (!inherits(coord, \"CoordTrans\") && !coord$is_linear()) {\n cli_warn(c(\n sprintf(\n \"{.fn %s} is not supported in %s\",\n snake_class(coord), layout_name\n ),\n i = \"Will use {.fn coord_cartesian} instead\"\n ))\n plot$coordinates <- ggplot2::coord_cartesian()\n }\n plot\n}\n\ngguse_circle_coord <- function(plot, coord, ..., layout_name) {\n if (inherits(plot_coord <- plot$coordinates, \"CoordRadial\")) {\n out <- ggproto(\n NULL, plot_coord,\n theta = coord$theta,\n r = coord$r,\n arc = coord$arc,\n direction = coord$direction,\n r_axis_inside = coord$r_axis_inside,\n expand = coord$expand,\n ...,\n setup_panel_params = circle_panel_params\n )\n } else {\n if (!isTRUE(plot$coordinates$default)) {\n cli_warn(c(\n sprintf(\n \"{.fn %s} is not supported in %s\",\n snake_class(plot_coord), layout_name\n ),\n i = sprintf(\"Will use {.fn %s} instead\", snake_class(coord))\n ))\n }\n if (!inherits(coord, \"CoordCircle\")) {\n out <- ggproto(NULL, coord, ...,\n setup_panel_params = circle_panel_params\n )\n } else {\n out <- ggproto(NULL, coord, ...)\n }\n }\n out\n}\n\n######################################################\n#' @importFrom ggplot2 ggproto\nggfacet_modify <- function(plot, ...) {\n ParentFacet <- plot$facet\n plot$facet <- ggproto(NULL, ParentFacet, ...)\n plot\n}\n\ngguse_facet <- function(plot, facet) {\n plot$facet <- facet\n plot\n}\n\nggmelt_facet <- function(plot, facet, ...) {\n gguse_facet(plot, melt_facet(facet, plot$facet, ...))\n}\n\n#' @param use A template facet object which will be used.\n#' @param facet User provided facet object.\n#' @noRd\nmelt_facet <- function(use, facet, ...) UseMethod(\"melt_facet\")\n\n#' @export\nmelt_facet.NULL <- function(use, facet, ...) {\n facet\n}\n\n#' @importFrom ggplot2 ggproto\n#' @export\nmelt_facet.FacetGrid <- function(use, facet, ...,\n free_row = FALSE,\n free_column = FALSE) {\n if (inherits(facet, \"FacetGrid\")) {\n # re-dispatch parameters\n params <- facet$params\n if (length(use$params$rows) || !free_row) {\n params$rows <- use$params$rows\n }\n if (length(use$params$cols) || !free_column) {\n params$cols <- use$params$cols\n }\n if (!free_row) { # Don't allow user change the rows\n params$free$y <- use$params$free$y\n params$space_free$y <- use$params$space_free$y\n }\n if (!free_column) { # Don't allow user change the cols\n params$free$x <- use$params$free$x\n params$space_free$x <- use$params$space_free$x\n }\n\n params$drop <- use$params$drop\n params$as.table <- use$params$as.table\n\n # if the use is free, it must be free\n ggproto(NULL, facet, params = params)\n } else {\n use\n }\n}\n\n#' @importFrom ggplot2 ggproto\n#' @export\nmelt_facet.FacetWrap <- function(use, facet, ...) {\n if (inherits(facet, \"FacetWrap\")) {\n # re-dispatch parameters\n params <- facet$params\n\n # we always fix the grid rows and cols\n params$facets <- use$params$facets\n params$nrow <- use$params$nrow\n params$ncol <- use$params$ncol\n params$drop <- use$params$drop\n params$as.table <- use$params$as.table\n ggproto(NULL, facet, params = params)\n } else {\n use\n }\n}\n\n#' @export\nmelt_facet.FacetNull <- function(use, facet, ...) {\n if (inherits(facet, \"FacetNull\")) {\n facet\n } else {\n use\n }\n}\n\n#' @export\nmelt_facet.FacetStack <- function(use, facet, ...) {\n if (inherits(facet, \"FacetGrid\")) {\n params <- facet$params\n if (is_horizontal(.subset2(use, \"direction\"))) {\n # for horizontal stack, we cannot facet by rows\n if (!is.null(params$rows)) {\n cli_warn(sprintf(\n \"Cannot facet by rows in %s\",\n .subset2(use, \"object_name\")\n ))\n params$rows <- NULL\n }\n } else if (!is.null(params$cols)) {\n # for vertical stack, we cannot facet by cols\n cli_warn(sprintf(\n \"Cannot facet by cols in %s\",\n .subset2(use, \"object_name\")\n ))\n params$cols <- NULL\n }\n ggproto(NULL, facet, params = params)\n } else if (inherits(facet, \"FacetWrap\")) {\n params <- facet$params\n if (is_horizontal(.subset2(use, \"direction\"))) {\n # for horizontal stack, we cannot facet by rows\n if (is.null(params$nrow)) {\n params$nrow <- 1L\n } else if (params$nrow > 1L) {\n cli_warn(sprintf(\n \"Cannot wrap facet by rows in %s\",\n .subset2(use, \"object_name\")\n ))\n params$nrow <- 1L\n }\n } else if (!is.null(params$cols)) {\n # for vertical stack, we cannot facet by cols\n if (is.null(params$ncol)) {\n params$ncol <- 1L\n } else if (params$ncol > 1L) {\n cli_warn(sprintf(\n \"Cannot wrap facet by cols in %s\",\n .subset2(use, \"object_name\")\n ))\n params$ncol <- 1L\n }\n }\n } else if (inherits(facet, \"FacetNull\")) {\n facet\n } else {\n ggplot2::facet_null()\n }\n}\n\nfacet_stack <- function(direction, object_name) {\n structure(\n list(direction = direction, object_name = object_name),\n class = \"FacetStack\"\n )\n}\n\n#' @export\nmelt_facet.FacetQuad <- function(use, facet, ...,\n free_row = FALSE,\n free_column = FALSE) {\n if (inherits(facet, \"FacetGrid\")) {\n if (free_row || free_column) {\n params <- facet$params\n if (!free_row && !is.null(params$rows)) {\n cli_warn(sprintf(\n \"Cannot facet by rows in %s\",\n .subset2(use, \"layout_name\")\n ))\n params$rows <- NULL\n # for horizontal stack, we cannot facet by rows\n }\n if (!free_column && !is.null(params$cols)) {\n cli_warn(sprintf(\n \"Cannot facet by cols in %s\",\n .subset2(use, \"layout_name\")\n ))\n params$cols <- NULL\n }\n ggproto(NULL, facet, params = params)\n } else {\n ggplot2::facet_null()\n }\n } else if (inherits(facet, \"FacetNull\")) {\n facet\n } else {\n ggplot2::facet_null()\n }\n}\n\nfacet_quad <- function(layout_name) {\n structure(list(layout_name = layout_name), class = \"FacetQuad\")\n}\n"], ["/ggalign/R/ggcross.R", "#' Connect two layout crosswise\n#'\n#' @description\n#' `ggcross` resets the layout ordering index of a [`stack_cross()`]. This\n#' allows you to add other `align_*` objects to define a new layout ordering\n#' index. Any objects added after `ggcross` will use this updated layout\n#' ordering index. This feature is particularly useful for creating `tanglegram`\n#' visualizations. `ggcross()` is an alias of `ggcross()`.\n#'\n#' @inheritParams ggalign\n#' @section ggplot2 specification:\n#' `ggcross()` initializes a ggplot `data` and `mapping`.\n#'\n#' `ggcross()` always applies a default mapping for the axis of the data index\n#' in the layout. This mapping is `aes(y = .data$.y)` for horizontal stack\n#' layout (including left and right annotation) and `aes(x = .data$.x)` for\n#' vertical stack layout (including top and bottom annotation).\n#'\n#' The data in the underlying `ggplot` object will contain following columns:\n#'\n#' - `.panel`: The panel for the aligned axis. Refers to the `x-axis` for\n#' vertical `stack_layout()` (including top and bottom annotations), and the\n#' `y-axis` for horizontal `stack_layout()` (including left and right\n#' annotations).\n#'\n#' - `.names` ([`vec_names()`][vctrs::vec_names]) and `.index`\n#' ([`vec_size()`][vctrs::vec_size()]/[`NROW()`]): Character names (if\n#' available) and the integer index of the original data.\n#'\n#' - `.hand`: a factor indicates the index groups.\n#'\n#' - `.x`/`.y` and `.discrete_x`/`.discrete_y`: Integer indices for `x`/`y`\n#' coordinates, and a factor of the data labels (only applicable when names\n#' exist).\n#'\n#' It is recommended to use `.x`/`.y`, or `.discrete_x`/`.discrete_y` as the\n#' `x`/`y` mapping.\n#'\n#' @importFrom ggplot2 ggplot aes\n#' @export\nggcross <- function(mapping = aes(), size = NULL,\n no_axes = NULL, active = NULL) {\n active <- update_active(active, new_active(use = TRUE))\n no_axes <- no_axes %||%\n getOption(sprintf(\"%s.align_no_axes\", pkg_nm()), default = TRUE)\n cross(\n CrossGg,\n plot = ggplot(mapping = mapping),\n schemes = default_schemes(th = theme_no_strip()),\n size = size, no_axes = no_axes, active = active\n )\n}\n\n#' @importFrom ggplot2 ggproto\nCrossGg <- ggproto(\"CrossGg\", \n CraftCross,\n interact_layout = function(self, layout) {\n if (!is_cross_layout(layout)) {\n cli_abort(c(\n sprintf(\n \"Cannot add %s to %s\",\n object_name(self), self$layout_name\n ),\n i = sprintf(\n \"%s can only be used in {.fn stack_cross}\",\n object_name(self)\n )\n ))\n }\n\n # udpate cross_points\n layout@cross_points <- c(layout@cross_points, length(layout@plot_list))\n\n # update old design list\n layout@odesign <- c(layout@odesign, list(layout@design))\n\n # we keep the names from the layout data for usage\n self$labels <- vec_names(layout@data)\n layout\n },\n setup_design = function(self, design) {\n design[\"index\"] <- list(NULL) # always reset the index\n design\n },\n setup_plot = function(self, plot) {\n ggadd_default(plot, mapping = switch_direction(\n self$direction, aes(y = .data$.y), aes(x = .data$.x)\n ))\n },\n #' @importFrom stats reorder\n build_plot = function(self, plot, design, extra_design = NULL,\n previous_design = NULL) {\n if (is.null(.subset2(design, \"nobs\"))) {\n cli_abort(sprintf(\n \"you must initialize %s before drawing %s\",\n self$layout_name, object_name(self)\n ), call = self$call)\n }\n direction <- self$direction\n index <- vec_c(\n .subset2(previous_design, \"index\"),\n .subset2(design, \"index\")\n )\n data <- data_frame0(\n .panel = vec_c(\n .subset2(previous_design, \"panel\"),\n .subset2(design, \"panel\")\n ),\n .index = index,\n # ggcross() only reset ordering index, labels should be the same\n .names = .subset(self$labels, index),\n .hand = if (is_horizontal(direction)) {\n factor(\n vec_rep_each(\n c(\"left\", \"right\"),\n c(\n .subset2(previous_design, \"nobs\"),\n .subset2(design, \"nobs\")\n )\n ),\n c(\"left\", \"right\")\n )\n } else {\n factor(\n vec_rep_each(\n c(\"top\", \"bottom\"),\n c(\n .subset2(previous_design, \"nobs\"),\n .subset2(design, \"nobs\")\n )\n ),\n c(\"bottom\", \"top\")\n )\n }\n )\n axis <- to_coord_axis(direction)\n coord_name <- paste0(\".\", axis)\n data[[coord_name]] <- vec_c(\n seq_len(.subset2(previous_design, \"nobs\")),\n seq_len(.subset2(design, \"nobs\"))\n )\n if (!is.null(.subset2(data, \".names\"))) {\n data[[paste0(\".discrete_\", axis)]] <- reorder(\n .subset2(data, \".names\"),\n .subset2(data, coord_name),\n order = FALSE\n )\n }\n plot <- gguse_data(plot, data)\n plot + switch_direction(\n direction,\n default_expansion(x = expansion()),\n default_expansion(y = expansion())\n )\n },\n finish_plot = function(self, plot, schemes, theme) {\n direction <- self$direction\n # remove axis titles, text, ticks used for alignment\n if (isTRUE(self$no_axes)) {\n schemes$scheme_theme <- .subset2(schemes, \"scheme_theme\") +\n theme_no_axes(switch_direction(direction, \"y\", \"x\"))\n }\n plot <- plot_add_schemes(plot, schemes)\n if (is_horizontal(direction)) {\n theme <- theme(\n panel.spacing.y = calc_element(\"panel.spacing.y\", theme)\n )\n } else {\n theme <- theme(\n panel.spacing.x = calc_element(\"panel.spacing.x\", theme)\n )\n }\n plot <- plot + theme\n ggremove_margin(plot, direction) + theme_recycle()\n },\n summary = function(self, plot) {\n header <- ggproto_parent(Craftsman, self)$summary(plot)\n c(header, \" Reset the ordering index and Add plot\")\n }\n)\n"], ["/ggalign/R/craft-align-dendrogram.R", "#' Plot dendrogram tree\n#'\n#' @param ... <[dyn-dots][rlang::dyn-dots]> Additional arguments passed to\n#' [`geom_segment()`][ggplot2::geom_segment].\n#' @param plot_dendrogram A boolean value indicates whether plot the dendrogram\n#' tree.\n#' @param plot_cut_height A boolean value indicates whether plot the cut height.\n#' @section ggplot2 specification:\n#' `align_dendro` initializes a ggplot `data` and `mapping`.\n#'\n#' The internal `ggplot` object will always use a default mapping of\n#' `aes(x = .data$x, y = .data$y)`.\n#'\n#' The default ggplot data is the `node` coordinates with `edge` data attached\n#' in [`ggalign`][ggalign_attr()] attribute, in addition, a\n#' [`geom_segment`][ggplot2::geom_segment] layer with a data frame of the `edge`\n#' coordinates will be added when `plot_dendrogram = TRUE`.\n#'\n#' See [`fortify_data_frame.dendrogram()`] for details.\n#' @param merge_dendrogram A single boolean value, indicates whether we should\n#' merge multiple dendrograms, only used when previous groups have been\n#' established. Default: `FALSE`.\n#' @inheritParams align_hclust\n#' @inheritParams fortify_data_frame.dendrogram\n#' @inheritParams ggalign\n#' @inheritSection align Discrete Axis Alignment\n#' @examples\n#' # align_dendro will always add a plot area\n#' ggheatmap(matrix(rnorm(81), nrow = 9)) +\n#' anno_top() +\n#' align_dendro()\n#' ggheatmap(matrix(rnorm(81), nrow = 9)) +\n#' anno_top() +\n#' align_dendro(k = 3L)\n#'\n#' @importFrom ggplot2 aes\n#' @importFrom rlang list2\n#' @export\nalign_dendro <- function(mapping = aes(), ...,\n distance = \"euclidean\",\n method = \"complete\",\n use_missing = \"pairwise.complete.obs\",\n reorder_dendrogram = FALSE,\n merge_dendrogram = FALSE,\n reorder_group = FALSE,\n k = NULL, h = NULL, cutree = NULL,\n plot_dendrogram = TRUE,\n plot_cut_height = NULL, root = NULL,\n center = FALSE, type = \"rectangle\",\n size = NULL, data = NULL,\n no_axes = NULL, active = NULL) {\n assert_bool(plot_cut_height, allow_null = TRUE)\n assert_bool(merge_dendrogram)\n\n # setup the default value for `plot_cut_height`\n plot_cut_height <- plot_cut_height %||% (\n # we by default don't draw the height of the user-provided cutree\n # since function like `dynamicTreeCut` will merge tree\n (!is.null(k) || !is.null(h)) && is.null(cutree)\n )\n plot <- ggplot(mapping = mapping)\n if (plot_dendrogram) {\n plot <- plot + ggplot2::geom_segment(\n mapping = aes(\n x = .data$x, y = .data$y,\n xend = .data$xend, yend = .data$yend\n ),\n ...,\n stat = \"identity\",\n data = function(data) ggalign_attr(data, \"edge\")\n )\n }\n assert_active(active)\n active <- update_active(active, new_active(use = TRUE))\n .align_hclust(\n align = AlignDendro,\n distance = distance,\n method = method,\n use_missing = use_missing,\n merge_dendro = merge_dendrogram,\n plot_cut_height = plot_cut_height,\n type = type, root = root, center = center,\n reorder_dendrogram = reorder_dendrogram,\n reorder_group = reorder_group,\n schemes = default_schemes(th = theme_no_strip()),\n k = k, h = h, cutree = cutree, data = data, active = active,\n size = size, no_axes = no_axes, plot = plot\n )\n}\n\n#' @importFrom ggplot2 aes ggplot\n#' @importFrom rlang inject\n#' @include craft-align-hclust.R\nAlignDendro <- ggproto(\"AlignDendro\", AlignHclust,\n setup_plot = function(self, plot) {\n ggadd_default(plot, aes(x = .data$x, y = .data$y)) + switch_direction(\n self$direction,\n ggplot2::labs(x = \"height\"),\n ggplot2::labs(y = \"height\")\n )\n },\n build_plot = function(self, plot, design, extra_design = NULL,\n previous_design = NULL) {\n plot_cut_height <- self$plot_cut_height\n center <- self$center\n type <- self$type\n root <- self$root\n panel <- .subset2(design, \"panel\")\n index <- .subset2(design, \"index\")\n\n statistics <- .subset2(self, \"statistics\")\n direction <- self$direction\n priority <- switch_direction(direction, \"left\", \"right\")\n dendrogram_panel <- self$panel[index]\n if (!is.null(dendrogram_panel) &&\n # we allow to change the panel level name, but we prevent\n # from changing the underlying factor level (the underlying\n # ordering)\n !all(as.integer(dendrogram_panel) == as.integer(panel))) {\n cli_abort(\"you cannot do sub-splitting in dendrogram groups\")\n }\n\n if (self$multiple_tree) {\n branches <- levels(panel)\n data <- vector(\"list\", length(statistics))\n start <- 0L\n for (i in seq_along(data)) {\n tree <- .subset2(statistics, i)\n n <- stats::nobs(tree)\n end <- start + n\n data[[i]] <- fortify_data_frame(\n tree,\n priority = priority,\n center = center,\n type = type,\n leaf_pos = seq(start + 1L, end),\n leaf_braches = rep_len(.subset(branches, i), n),\n reorder_branches = FALSE,\n root = root,\n double = TRUE,\n call = self$call\n )\n start <- end\n }\n data <- lapply(\n list(\n node = data,\n edge = lapply(data, ggalign_attr, \"edge\")\n ),\n function(dat) {\n ans <- vec_rbind(!!!dat, .names_to = \"parent\")\n ans$.panel <- factor(.subset2(ans, \".panel\"), branches)\n ans\n }\n )\n edge <- .subset2(data, \"edge\")\n node <- .subset2(data, \"node\")\n } else {\n if (nlevels(panel) > 1L && type == \"triangle\" && self$in_linear) {\n cli_warn(c(paste(\n \"{.arg type} of {.arg triangle}\",\n \"is not well support for facet dendrogram\"\n ), i = \"will use {.filed rectangle} dendrogram instead\"))\n type <- \"rectangle\"\n }\n data <- fortify_data_frame(\n statistics,\n priority = priority,\n center = center,\n type = type,\n leaf_braches = as.character(panel),\n # panel has been reordered by the dendrogram index\n reorder_branches = FALSE,\n root = root,\n double = TRUE,\n call = self$call\n )\n edge <- ggalign_attr(data, \"edge\")\n node <- data\n }\n\n # add names\n if (!is.null(self$labels)) {\n node$.names <- .subset(self$labels, .subset2(node, \".index\"))\n }\n if (is_horizontal(direction)) {\n edge <- rename(\n edge,\n c(x = \"y\", xend = \"yend\", y = \"x\", yend = \"xend\")\n )\n node <- rename(node, c(x = \"y\", y = \"x\"))\n }\n\n # we do some tricks, since ggplot2 won't remove the attributes\n # we attach the `edge` data\n plot <- gguse_data(plot, ggalign_data_set(node, edge = edge))\n\n if (plot_cut_height && !is.null(height <- .subset2(self, \"height\"))) {\n plot <- plot +\n switch_direction(\n direction,\n ggplot2::geom_vline(\n xintercept = height, linetype = \"dashed\"\n ),\n ggplot2::geom_hline(\n yintercept = height, linetype = \"dashed\"\n )\n )\n }\n position <- .subset2(self, \"position\")\n if (!self$in_linear || # for circular layout\n # for bottom annotation, reverse y-axis\n (!is.null(position) && position == \"bottom\")) {\n plot <- reverse_continuous_axis(plot, \"y\")\n } else if (!is.null(position) && position == \"left\") {\n # for left annotation, reverse x-axis\n plot <- reverse_continuous_axis(plot, \"x\")\n }\n\n # always turn off clip, this is what dendrogram dependends on\n old_coord <- plot$coordinates\n if (!identical(old_coord$clip, \"off\")) {\n # to prevent from changing the input of user.\n plot$coordinates <- ggproto(NULL, old_coord, clip = \"off\")\n }\n plot\n }\n)\n\ntree_one_node <- function(index, label) {\n structure(\n index,\n class = \"dendrogram\",\n leaf = TRUE,\n height = 0,\n label = label,\n members = 1L\n )\n}\n\n# this function won't set the right `midpoint`, but `dendrogram_data` function\n# won't use it, so, it has no hurt to use.\nmerge_dendrogram <- function(parent, children) {\n if (is.null(parent)) { # if no parent, call the merge function from `stats`\n return(Reduce(function(x, y) {\n merge(x, y, adjust = \"none\")\n }, children))\n }\n children_heights <- vapply(\n children, attr, numeric(1L), \"height\",\n USE.NAMES = FALSE\n )\n parent_branch_heights <- tree_branch_heights(parent)\n cutoff_height <- max(children_heights) + min(parent_branch_heights) * 0.5\n .merge_dendrogram <- function(dend) {\n if (stats::is.leaf(dend)) { # base version, leaf should be the index\n .subset2(children, dend)\n } else { # for a branch, we should update the members, height\n attrs <- attributes(dend)\n # we recursively run for each node of current branch\n dend <- lapply(dend, .merge_dendrogram)\n heights <- vapply(dend, attr, numeric(1L), \"height\",\n USE.NAMES = FALSE\n )\n n_members <- vapply(dend, attr, integer(1L), \"members\",\n USE.NAMES = FALSE\n )\n # we update height and members\n attrs$height <- .subset2(attrs, \"height\") + max(heights)\n attrs$members <- sum(n_members)\n attributes(dend) <- attrs\n dend\n }\n }\n ans <- .merge_dendrogram(parent)\n attr(ans, \"cutoff_height\") <- cutoff_height\n ans\n}\n\n#' @importFrom stats reorder\nreorder_dendrogram <- function(dend, wts) {\n if (inherits(dend, \"hclust\")) dend <- stats::as.dendrogram(dend)\n reorder(x = dend, wts = wts, agglo.FUN = mean)\n}\n\ntree_branch_heights <- function(dend) {\n if (stats::is.leaf(dend)) {\n return(NULL)\n } else {\n c(\n attr(dend, \"height\"),\n unlist(lapply(dend, tree_branch_heights), FALSE, FALSE)\n )\n }\n}\n"], ["/ggalign/R/mark.R", "#' Define the links to connect the marked observations\n#'\n#' @description\n#' This function allows users to define links between marked observations and\n#' plot panel (e.g., for creating visual connections for related data), which\n#' could help explain the observations.\n#'\n#' @param .draw A function used to draw the links. The function must return a\n#' [`grob()`][grid::grob] object. If the function does not return a valid\n#' `grob`, nothing will be drawn. The input data for the function must contain\n#' two arguments: a data frame for the panel side coordinates and a data frame\n#' for the marked observation coordinates.\n#' @inheritParams .mark_draw\n#' @seealso\n#' - [`mark_line()`]\n#' - [`mark_tetragon()`]\n#' - [`mark_triangle()`]\n#' - [`.mark_draw()`]\n#' @importFrom rlang is_empty inject\n#' @importFrom grid gTree gList\n#' @export\nmark_draw <- function(.draw, ...) {\n if (!is.function(draw <- allow_lambda(.draw))) {\n cli_abort(\"{.arg .draw} must be a function\")\n }\n new_draw <- function(data) {\n ans <- lapply(data, function(dd) {\n draw(.subset2(dd, \"panel\"), .subset2(dd, \"link\"))\n })\n ans <- ans[vapply(ans, is.grob, logical(1L), USE.NAMES = FALSE)]\n if (!is_empty(ans)) {\n gTree(children = inject(gList(!!!ans)))\n }\n }\n .mark_draw(new_draw, ...)\n}\n\n#' @inherit mark_draw title\n#'\n#' @description\n#' A base version of [`mark_draw`], designed for performance optimization. This\n#' function is used to build other `mark_*` functions that manage the drawing of\n#' links between marked observations.\n#'\n#' @param .draw A function used to draw the links. The function must return a\n#' [`grob()`][grid::grob] object. If the function does not return a valid\n#' `grob`, nothing will be drawn. The input data for the function contains a\n#' list, where each item is a list of two data frames: one for the panel side\n#' coordinates (`\"panel\"`) and one for the marked observations coordinates\n#' (`\"link\"`).\n#'\n#' @inheritParams pair_links\n#' @seealso [`mark_draw()`]\n#' @export\n.mark_draw <- function(.draw, ...) {\n if (override_call(call <- caller_call())) {\n call <- current_call()\n }\n if (!is.function(draw <- allow_lambda(.draw))) {\n cli_abort(\"{.arg .draw} must be a function\", call = call)\n }\n links <- pair_links(...)\n structure(list(draw = draw, links = links), class = \"ggalign_mark_draw\")\n}\n\n#' @export\nprint.ggalign_mark_draw <- function(x, ...) {\n header <- sprintf(\"<%s>\", vec_ptype_full(x))\n cat(header, sep = \"\\n\")\n obj_print_data(.subset2(x, \"links\"))\n invisible(x)\n}\n\n#' Link the observations and the panel with a line\n#'\n#' @inheritParams .mark_draw\n#' @param .element A [`element_line()`][ggplot2::element_line] object.\n#' Vectorized fields will be recycled to match the total number of groups, or\n#' you can wrap the element with [`I()`] to recycle to match the drawing\n#' groups. The drawing groups typically correspond to the number of\n#' observations, as each observation will be linked with the plot panel.\n#' @importFrom ggplot2 element_line\n#' @export\nmark_line <- function(..., .element = NULL) {\n assert_s3_class(.element, \"element_line\", allow_null = TRUE)\n default <- calc_element(\"ggalign.line\", complete_theme(theme_get()))\n if (is.null(.element)) {\n .element <- default\n } else {\n .element <- ggplot2::merge_element(.element, default)\n }\n .mark_draw(.draw = function(data) {\n data <- lapply(data, function(d) {\n panel <- .subset2(d, \"panel\")\n link <- .subset2(d, \"link\")\n data_frame0(\n # there is only one row for panel, it's safe to use\n # vec_interleave directly\n x = vec_interleave(\n (panel$x + panel$xend) / 2L,\n (link$x + link$xend) / 2L\n ),\n y = vec_interleave(\n (panel$y + panel$yend) / 2L,\n (link$y + link$yend) / 2L\n )\n )\n })\n if (inherits(.element, \"AsIs\")) {\n .element <- element_rep_len(.element,\n length.out = sum(list_sizes(data)) / 2L\n )\n } else {\n .element <- element_rep_len(.element, length.out = length(data))\n .element <- element_vec_rep_each(.element,\n times = list_sizes(data) / 2L\n )\n }\n data <- vec_rbind(!!!data)\n element_grob(\n .element,\n x = data$x, y = data$y,\n id.lengths = vec_rep(2L, vec_size(data) / 2L),\n default.units = \"native\"\n )\n }, ...)\n}\n\n#' Link the observations and the panel with a quadrilateral\n#'\n#' @inheritParams .mark_draw\n#' @param .element A [`element_polygon()`] object. Vectorized fields will be\n#' recycled to match the total number of groups, or you can wrap the element\n#' with [`I()`] to recycle to match the drawing groups. The drawing groups\n#' are usually the same as the defined groups, but they will differ when the\n#' defined group of observations is separated and cannot be linked with a\n#' single quadrilateral. In such cases, the number of drawing groups will be\n#' larger than the number of defined groups.\n#' @export\nmark_tetragon <- function(..., .element = NULL) {\n assert_s3_class(.element, \"element_polygon\", allow_null = TRUE)\n default <- calc_element(\"ggalign.polygon\", complete_theme(theme_get()))\n if (is.null(.element)) {\n .element <- default\n } else {\n .element <- ggplot2::merge_element(.element, default)\n }\n .mark_draw(.draw = function(data) {\n data <- lapply(data, function(d) {\n panel <- .subset2(d, \"panel\")\n link <- .subset2(d, \"link\")\n\n # find the consecutive groups\n index <- .subset2(link, \"link_index\")\n oindex <- order(index)\n group <- cumsum(c(0L, diff(index[oindex])) != 1L)\n\n # restore the order\n group <- group[order(oindex)]\n\n # split link into groups\n link <- vec_split(link, group)\n\n # for each group, we draw a quadrilateral\n vec_rbind(!!!lapply(.subset2(link, \"val\"), function(dd) {\n data_frame0(\n x = vec_c(panel$x, panel$xend, max(dd$xend), min(dd$x)),\n y = vec_c(panel$y, panel$yend, max(dd$yend), min(dd$y))\n )\n }))\n })\n if (inherits(.element, \"AsIs\")) {\n .element <- element_rep_len(.element,\n length.out = sum(list_sizes(data)) / 4L\n )\n } else {\n .element <- element_rep_len(.element, length.out = length(data))\n .element <- element_vec_rep_each(.element,\n times = list_sizes(data) / 4L\n )\n }\n data <- vec_rbind(!!!data)\n if (vec_size(data)) {\n element_grob(\n .element,\n x = data$x, y = data$y,\n id.lengths = vec_rep(4L, nrow(data) / 4L),\n default.units = \"native\"\n )\n }\n }, ...)\n}\n\n#' Link the observations and the panel with a triangle\n#'\n#' @inheritParams .mark_draw\n#' @param orientation A single string, either `\"plot\"` or `\"observation\"`,\n#' indicating the base of the triangle.\n#' @param .element An [`element_polygon()`] object. Vectorized fields will be\n#' recycled to match the total number of groups, or you can wrap the element\n#' with [`I()`] to recycle to match the drawing groups.\n#' - When `orientation` is `\"plot\"`, the drawing groups typically correspond\n#' to the number of observations.\n#' - When `orientation` is `\"observation\"`, the drawing groups usually match\n#' the defined groups, but will differ if the defined group of observations\n#' is separated and cannot be linked with a single triangle. In this case,\n#' the number of drawing groups will be larger than the number of defined\n#' groups.\n#' @importFrom rlang arg_match0\n#' @export\nmark_triangle <- function(..., orientation = \"plot\", .element = NULL) {\n assert_s3_class(.element, \"element_polygon\", allow_null = TRUE)\n default <- calc_element(\"ggalign.polygon\", complete_theme(theme_get()))\n if (is.null(.element)) {\n .element <- default\n } else {\n .element <- ggplot2::merge_element(.element, default)\n }\n orientation <- arg_match0(orientation, c(\"plot\", \"observation\"))\n .mark_draw(.draw = function(data) {\n data <- lapply(data, function(d) {\n panel <- .subset2(d, \"panel\")\n link <- .subset2(d, \"link\")\n if (identical(orientation, \"plot\")) {\n # for each link, we draw a triangle\n triangle_list <- lapply(vec_seq_along(link), function(i) {\n dd <- vec_slice(link, i)\n data_frame0(\n x = vec_c(panel$x, panel$xend, (dd$x + dd$xend) / 2L),\n y = vec_c(panel$y, panel$yend, (dd$y + dd$yend) / 2L),\n )\n })\n } else {\n # find the consecutive groups\n index <- .subset2(link, \"link_index\")\n oindex <- order(index)\n group <- cumsum(c(0L, diff(index[oindex])) != 1L)\n\n # restore the order\n group <- group[order(oindex)]\n\n # split link into groups\n link <- vec_split(link, group)\n\n # for each group, we draw a triangle\n triangle_list <- lapply(.subset2(link, \"val\"), function(dd) {\n data_frame0(\n x = vec_c(\n (panel$x + panel$xend) / 2L,\n max(dd$xend), min(dd$x)\n ),\n y = vec_c(\n (panel$y + panel$yend) / 2L,\n max(dd$yend), min(dd$y)\n )\n )\n })\n }\n vec_rbind(!!!triangle_list)\n })\n if (inherits(.element, \"AsIs\")) {\n .element <- element_rep_len(.element,\n length.out = sum(list_sizes(data)) / 3L\n )\n } else {\n .element <- element_rep_len(.element, length.out = length(data))\n .element <- element_vec_rep_each(.element,\n times = list_sizes(data) / 3L\n )\n }\n data <- vec_rbind(!!!data)\n if (vec_size(data)) {\n element_grob(\n .element,\n x = data$x, y = data$y,\n id.lengths = vec_rep(3L, nrow(data) / 3L),\n default.units = \"native\"\n )\n }\n }, ...)\n}\n\n#####################################################\n#' @export\n`[.ggalignMarkGtable` <- function(x, i, j) {\n # subset will violate the `ggalignMarkGtable` `shape`\n # we always use the next method\n x <- remove_class(x, \"ggalignMarkGtable\")\n x$ggalign_link_data <- NULL\n NextMethod()\n}\n\n#' @importFrom ggplot2 ggproto\n#' @export\nalignpatch.ggalign_mark_plot <- function(x) {\n ggproto(NULL, PatchAlignMark, plot = x)\n}\n\n#' @importFrom ggplot2 ggproto ggproto_parent\n#' @include alignpatch-ggplot2.R\nPatchAlignMark <- ggproto(\n \"PatchAlignMark\", PatchGgplot,\n patch_gtable = function(self, theme, guides, plot = self$plot) {\n ans <- ggproto_parent(PatchGgplot, self)$patch_gtable(plot = plot)\n # re-define the draw method, we assign new class\n ans <- add_class(ans, \"ggalignMarkGtable\")\n ans$ggalign_link_data <- plot$ggalign_link_data\n ans\n },\n add_plot = function(self, gt, plot, t, l, b, r, name, z = 2L) {\n gtable_add_grob(\n gt,\n grobs = plot,\n # t = 8, l = 6, b = 14, r = 12\n # t = t + 7L, l = l + 5L, b = b - 6L, r = r - 5L,\n t = t + TOP_BORDER, l = l + LEFT_BORDER,\n name = name, z = z\n )\n },\n add_background = function(self, gt, bg, t, l, b, r, name, z = 1L) {\n gtable_add_grob(\n gt,\n grobs = bg,\n t = t + TOP_BORDER, l = l + LEFT_BORDER,\n name = name, z = z\n )\n },\n get_sizes = function(self, free = NULL, gt = self$gt) {\n ggproto_parent(PatchGgplot, self)$get_sizes(.tlbr, gt = gt)\n },\n align_border = function(self, t = NULL, l = NULL, b = NULL, r = NULL,\n gt = self$gt) {\n gt # free from alignment\n }\n)\n\n# preDraw:\n# - makeContext\n# - pushvpgp\n# - preDrawDetails: by default, do noting\n# makeContent:\n# drawDetails:\n# postDraw:\n# - postDrawDetails: by default, do noting\n# - popgrobvp\n#' @importFrom grid makeContent unit convertHeight convertWidth viewport\n#' @importFrom stats reorder\n#' @export\nmakeContent.ggalignMarkGtable <- function(x) {\n # Grab viewport information\n width <- convertWidth(unit(1, \"npc\"), \"mm\", valueOnly = TRUE)\n height <- convertHeight(unit(1, \"npc\"), \"mm\", valueOnly = TRUE)\n\n # Grab grob metadata\n plot_widths <- compute_null_width(.subset2(x, \"widths\"),\n valueOnly = TRUE\n )\n plot_widths <- scales::rescale(plot_widths, c(0, 1), from = c(0, width))\n plot_heights <- compute_null_height(.subset2(x, \"heights\"),\n valueOnly = TRUE\n )\n plot_heights <- scales::rescale(plot_heights, c(0, 1), from = c(0, height))\n\n panel_loc <- find_panel(x)\n data <- .subset2(x, \"ggalign_link_data\")\n full_data1 <- .subset2(data, \"full_data1\")\n full_data2 <- .subset2(data, \"full_data2\")\n direction <- .subset2(data, \"direction\")\n link_index_list <- .subset2(data, \"link_index\")\n data_index_list <- .subset2(data, \"data_index\")\n obs_size <- .subset2(data, \"obs_size\")\n\n # prepare output for current for loop\n coords <- vector(\"list\", 2L)\n names(coords) <- c(\"hand1\", \"hand2\")\n for (link in names(coords)) {\n link_index <- lapply(link_index_list, .subset2, link)\n data_index <- lapply(data_index_list, .subset2, link)\n # early exit and step into next cycle if no link\n if (all(vapply(link_index, is.null, logical(1L), USE.NAMES = FALSE))) {\n coords[link] <- list(link_index)\n next\n }\n full_breaks <- switch(link,\n hand1 = full_data1,\n hand2 = full_data2\n )\n\n spacing <- .subset2(data, switch(link,\n hand1 = \"spacing1\",\n hand2 = \"spacing2\"\n ))\n\n # each value represent an `observation`, for panel space, we use `NA`\n # obs arranged from left to top, and from bottom to top\n points <- unlist(vec_interleave(full_breaks, list(NA)), FALSE, FALSE)\n # remove the last panel space, shouldn't exist\n points <- points[-length(points)]\n sizes <- numeric(length(points))\n n_spacing <- length(full_breaks) - 1L\n\n # then, we define the link grobs\n if (is_horizontal(direction)) { # the link should be in left or right\n spacing <- convertHeight(spacing, \"mm\", valueOnly = TRUE)\n spacing <- scales::rescale(spacing, c(0, 1), from = c(0, height))\n sizes[is.na(points)] <- spacing\n obs_height <- (1 - spacing * n_spacing) / sum(!is.na(points))\n sizes[!is.na(points)] <- obs_height # nobs\n yend <- cumsum(sizes)\n link_x <- switch(link,\n hand1 = 0,\n hand2 = 1\n )\n # by default, the height for each observation is `1`,\n # if we define obs size, we just re-scale it\n removed <- (1 - obs_size) * obs_height\n link_coord <- data_frame0(\n x = link_x, xend = link_x,\n y = yend - sizes + removed / 2L,\n yend = yend - removed / 2L\n )\n link_coord <- vec_slice(link_coord, !is.na(points))\n\n # from bottom to the top, following the ordering of the `breaks`\n panel_index <- seq(\n from = .subset2(panel_loc, \"b\"),\n to = .subset2(panel_loc, \"t\"),\n length.out = length(link_index)\n )\n l_border <- plot_widths[seq_len(.subset2(panel_loc, \"l\") - 1L)]\n r_border <- plot_widths[-seq_len(.subset2(panel_loc, \"r\"))]\n\n # for a gtable, heights are from top to the bottom,\n # we reverse the heights\n # we have reversed the `plot_cum_heights`, so the ordering index\n # should also be reversed\n panel_index <- nrow(x) - panel_index + 1L\n panel_yend <- cumsum(rev(plot_heights))\n panel_x <- switch(link,\n hand1 = sum(l_border),\n hand2 = 1 - sum(r_border)\n )\n panel_coord <- data_frame0(\n x = panel_x,\n xend = panel_x,\n y = (panel_yend - rev(plot_heights))[panel_index],\n yend = panel_yend[panel_index]\n )\n } else { # the link should be in top or bottom\n spacing <- convertWidth(spacing, \"mm\", valueOnly = TRUE)\n spacing <- scales::rescale(spacing, c(0, 1), from = c(0, width))\n sizes[is.na(points)] <- spacing\n obs_width <- (1 - spacing * n_spacing) / sum(!is.na(points))\n sizes[!is.na(points)] <- obs_width\n xend <- cumsum(sizes)\n link_y <- switch(link,\n hand1 = 1,\n hand2 = 0\n )\n # by default, the width for each observation is `1`,\n # if we define obs size, we just re-scale it\n removed <- (1 - obs_size) * obs_width\n link_coord <- data_frame0(\n x = xend - sizes + removed / 2L,\n xend = xend - removed / 2L,\n y = link_y, yend = link_y\n )\n link_coord <- vec_slice(link_coord, !is.na(points))\n\n panel_index <- seq(\n from = .subset2(panel_loc, \"l\"),\n to = .subset2(panel_loc, \"r\"),\n length.out = length(link_index)\n )\n t_border <- plot_heights[seq_len(.subset2(panel_loc, \"t\") - 1L)]\n b_border <- plot_heights[-seq_len(.subset2(panel_loc, \"b\"))]\n panel_xend <- cumsum(plot_widths)\n panel_y <- switch(link,\n hand1 = 1 - sum(t_border),\n hand2 = sum(b_border)\n )\n panel_coord <- data_frame0(\n x = (panel_xend - plot_widths)[panel_index],\n xend = panel_xend[panel_index],\n y = panel_y, yend = panel_y\n )\n }\n hand <- switch(link,\n hand1 = switch_direction(direction, \"left\", \"top\"),\n hand2 = switch_direction(direction, \"right\", \"bottom\")\n )\n nms <- names(link_index)\n link_panels <- vec_rep_each(names(full_breaks), list_sizes(full_breaks))\n coords[[link]] <- lapply(seq_along(link_index), function(i) {\n l_index <- .subset2(link_index, i)\n if (is.null(l_index)) return(NULL) # styler: off\n d_index <- .subset2(data_index, i)\n link <- vec_slice(link_coord, l_index)\n link$link_id <- nms[i]\n link$link_panel <- reorder(\n vec_slice(link_panels, l_index), l_index,\n order = FALSE\n )\n link$link_index <- l_index\n link$.hand <- hand\n link$.index <- d_index\n panel <- vec_slice(panel_coord, i)\n list(panel = panel, link = link)\n })\n }\n coords <- vec_interleave(\n .subset2(coords, \"hand1\"),\n .subset2(coords, \"hand2\")\n )\n coords <- list_drop_empty(coords)\n draw <- .subset2(data, \"draw\")\n if (is.gList(grob <- draw(coords))) {\n grob <- gTree(children = grob)\n }\n\n if (is.grob(grob)) {\n layout <- .subset2(x, \"layout\")\n panels <- layout[\n grepl(\"^panel\", .subset2(layout, \"name\")), ,\n drop = FALSE\n ]\n x <- gtable_add_grob(\n x,\n grobs = grob,\n t = 1L, l = 1L, b = -1L, r = -1L,\n # always draw with panel area\n z = min(panels$z)\n )\n }\n NextMethod()\n}\n"], ["/ggalign/R/alignpatch-align_plots.R", "#' Arrange multiple plots into a grid\n#'\n#' @param ... <[dyn-dots][rlang::dyn-dots]> A list of plots, ususally the\n#' ggplot object. Use `NULL` to indicate an empty spacer.\n#' @param ncol,nrow The dimensions of the grid to create - if both are `NULL` it\n#' will use the same logic as [`facet_wrap()`][ggplot2::facet_wrap] to set the\n#' dimensions\n#' @param byrow If `FALSE` the plots will be filled in in column-major order.\n#' @param widths,heights The relative widths and heights of each column and row\n#' in the grid. Will get repeated to match the dimensions of the grid. The\n#' special value of `NA` will behave as `1null` unit unless a fixed aspect plot\n#' is inserted in which case it will allow the dimension to expand or contract\n#' to match the aspect ratio of the content.\n#' @param area Specification of the location of areas in the layout. Can\n#' either be specified as a text string or by concatenating calls to\n#' [`area()`] together.\n#' @param guides A string with one or more of `r oxford_and(c(.tlbr, \"i\"))`\n#' indicating which side of guide legends should be collected. Defaults to\n#' [`waiver()`][ggplot2::waiver()], which inherits from the parent layout. If\n#' there is no parent layout, or if `NULL` is provided, no guides will be\n#' collected.\n#' @param theme A [`theme()`][ggplot2::theme] object used to customize various\n#' elements of the layout. By default, the theme will inherit from the parent\n#' `layout`.\n#' @param design An alias for `area`, retained for backward compatibility.\n#' @return An `AlignPatches` object.\n#' @seealso\n#' - [layout_design()]\n#' - [layout_title()]\n#' - [layout_theme()]\n#' @examples\n#' # directly copied from patchwork\n#' p1 <- ggplot(mtcars) +\n#' geom_point(aes(mpg, disp))\n#' p2 <- ggplot(mtcars) +\n#' geom_boxplot(aes(gear, disp, group = gear))\n#' p3 <- ggplot(mtcars) +\n#' geom_bar(aes(gear)) +\n#' facet_wrap(~cyl)\n#' p4 <- ggplot(mtcars) +\n#' geom_bar(aes(carb))\n#' p5 <- ggplot(mtcars) +\n#' geom_violin(aes(cyl, mpg, group = cyl))\n#'\n#' # Either add the plots as single arguments\n#' align_plots(p1, p2, p3, p4, p5)\n#'\n#' # Or use bang-bang-bang to add a list\n#' align_plots(!!!list(p1, p2, p3), p4, p5)\n#'\n#' # Match plots to areas by name\n#' area <- \"#BB\n#' AA#\"\n#' align_plots(B = p1, A = p2, area = area)\n#'\n#' # Compare to not using named plot arguments\n#' align_plots(p1, p2, area = area)\n#' @export\nalign_plots <- function(..., ncol = NULL, nrow = NULL, byrow = TRUE,\n widths = NA, heights = NA, area = NULL,\n guides = waiver(), theme = NULL, design = NULL) {\n plots <- rlang::dots_list(..., .ignore_empty = \"all\", .named = NULL)\n nms <- names(plots)\n area <- area %||% design\n if (!is.null(nms) && is.character(area)) {\n area_names <- unique(trimws(.subset2(strsplit(area, \"\"), 1L)))\n area_names <- sort(vec_set_difference(area_names, c(\"\", \"#\")))\n if (all(nms %in% area_names)) {\n plot_list <- vector(\"list\", length(area_names))\n names(plot_list) <- area_names\n plot_list[nms] <- plots\n plots <- plot_list\n }\n }\n\n for (plot in plots) {\n if (!has_method(plot, \"alignpatch\", default = FALSE)) {\n cli_abort(\"Cannot align {.obj_type_friendly {plot}}\")\n }\n }\n\n # setup layout parameters\n layout <- layout_design(\n ncol = ncol, nrow = nrow, byrow = byrow,\n widths = widths, heights = heights, area = area,\n guides = guides\n )\n AlignPatches(plots = plots, layout = layout, theme = theme)\n}\n\n#' @importFrom ggplot2 is_theme\n#' @importFrom S7 new_object S7_object prop prop<-\nAlignPatches <- S7::new_class(\"AlignPatches\",\n properties = list(\n plots = S7::new_property(\n S7::class_list,\n setter = function(self, value) {\n if (!is.null(prop(self, \"plots\"))) {\n cli_abort(\"'@plots' is read-only\")\n }\n prop(self, \"plots\", check = FALSE) <- value\n self\n }\n ),\n layout = S7::new_property(\n S7::class_list,\n setter = function(self, value) {\n if (!inherits(value, \"layout_design\")) {\n cli_abort(\"'@layout' must be a {.fn layout_design} object\")\n }\n old <- prop(self, \"layout\") %||% list(\n ncol = NULL, nrow = NULL, byrow = TRUE,\n widths = NA, heights = NA, area = NULL,\n guides = waiver()\n )\n guides <- .subset2(value, \"guides\")\n value$guides <- NULL # guides need special consideration\n old <- update_non_waive(old, value)\n if (is.null(guides) || is.waive(guides)) {\n old[\"guides\"] <- list(guides)\n } else if (!identical(guides, NA)) {\n old[\"guides\"] <- list(setup_guides(guides))\n }\n prop(self, \"layout\", check = FALSE) <- old\n self\n }\n ),\n titles = S7::new_property(\n S7::class_list,\n setter = function(self, value) {\n if (!inherits(value, \"layout_title\")) {\n cli_abort(\"'@titles' must be a {.fn layout_title} object'\")\n }\n old <- prop(self, \"titles\") %||%\n list(title = NULL, subtitle = NULL, caption = NULL)\n prop(self, \"titles\", check = FALSE) <- update_non_waive(\n old, value\n )\n self\n }\n ),\n theme = S7::new_property(\n S7::class_any,\n setter = function(self, value) {\n if (!is.null(value) && !is_theme(value)) {\n cli_abort(\"'@theme' must be a {.cls theme} object'\")\n }\n if (is.null(prop(self, \"theme\")) || is.null(value)) {\n prop(self, \"theme\", check = FALSE) <- value\n } else {\n prop(self, \"theme\", check = FALSE) <- prop(self, \"theme\") +\n value\n }\n self\n },\n default = NULL\n )\n ),\n constructor = function(plots = list(), layout = NULL,\n titles = NULL, theme = NULL) {\n out <- new_object(\n S7_object(),\n plots = plots,\n layout = layout %||% layout_design(),\n titles = titles %||% layout_title(),\n theme = theme\n )\n # for backward compatibility\n add_class(out, \"alignpatches\")\n }\n)\n\n#' @importFrom rlang caller_env\nlocal(\n S7::method(`+`, list(AlignPatches, S7::class_any)) <-\n function(e1, e2) {\n # Get the name of what was passed in as e2, and pass along so that\n # it can be displayed in error messages\n if (missing(e2)) {\n cli_abort(c(\n \"Cannot use {.code +} with a single argument.\",\n \"i\" = \"Did you accidentally put {.code +} on a new line?\"\n ))\n }\n e2name <- deparse(substitute(e2, env = caller_env(2)))\n alignpatches_add(e2, e1, e2name)\n }\n)\n\n#' @importFrom S7 S7_dispatch\nalignpatches_add <- S7::new_generic(\n \"alignpatches_add\", \"object\",\n function(object, patches, objectname) S7_dispatch()\n)\n\nS7::method(alignpatches_add, S7::class_any) <-\n function(object, patches, objectname) {\n if (is.null(object)) return(patches) # styler: off\n cli_abort(c(\n \"Cannot add {objectname}\",\n \"x\" = \"Only other layout elements or compatible objects can be added.\"\n ))\n }\n\n#############################################################\n#' Define the grid to compose plots in\n#'\n#' To control how different plots are laid out, you need to add a layout design\n#' specification. If you are nesting grids, the layout is scoped to the current\n#' nesting level.\n#' @inheritParams align_plots\n#' @return A `layout_design` object.\n#' @examples\n#' p1 <- ggplot(mtcars) +\n#' geom_point(aes(mpg, disp))\n#' p2 <- ggplot(mtcars) +\n#' geom_boxplot(aes(gear, disp, group = gear))\n#' p3 <- ggplot(mtcars) +\n#' geom_bar(aes(gear)) +\n#' facet_wrap(~cyl)\n#' align_plots(p1, p2, p3) +\n#' layout_design(nrow = 1L)\n#' align_plots(p1, p2, p3) +\n#' layout_design(ncol = 1L)\n#' @importFrom ggplot2 waiver\n#' @export\nlayout_design <- function(ncol = waiver(), nrow = waiver(), byrow = waiver(),\n widths = waiver(), heights = waiver(),\n area = waiver(), guides = NA, design = waiver()) {\n if (!is.waive(ncol)) {\n assert_number_whole(ncol, min = 1, allow_na = TRUE, allow_null = TRUE)\n }\n if (!is.waive(nrow)) {\n assert_number_whole(nrow, min = 1, allow_na = TRUE, allow_null = TRUE)\n }\n if (!is.waive(byrow)) assert_bool(byrow)\n area <- area %|w|% design\n if (!is.waive(area)) area <- as_areas(area)\n if (!identical(guides, NA) && !is.waive(guides) && !is.null(guides)) {\n assert_guides(guides)\n }\n structure(\n list(\n ncol = ncol,\n nrow = nrow,\n byrow = byrow,\n widths = widths,\n heights = heights,\n area = area,\n guides = guides\n ),\n class = c(\"layout_design\", \"plot_layout\")\n )\n}\n\nS3_layout_design <- S7::new_S3_class(\"layout_design\")\n\nS7::method(alignpatches_add, S3_layout_design) <-\n function(object, patches, objectname) {\n patches@layout <- object\n patches\n }\n\nS7::method(alignpatches_add, S7::new_S3_class(\"plot_layout\")) <-\n function(object, patches, objectname) {\n object$area <- object$design # pathwork use `design`\n object <- .subset(object, names(layout_design()))\n if (is.waive(object$guides)) {\n object$guides <- NA\n } else if (identical(object$guides, \"auto\")) {\n object$guides <- waiver()\n } else if (identical(object$guides, \"collect\")) {\n object$guides <- \"tlbr\"\n } else if (identical(object$guides, \"keep\")) {\n object[\"guides\"] <- list(NULL)\n }\n alignpatches_add(add_class(object, \"layout_design\"), patches)\n }\n\n##############################################################\n#' Annotate the whole layout\n#'\n#' @inheritParams ggplot2::labs\n#' @return A `layout_title` object.\n#' @examples\n#' p1 <- ggplot(mtcars) +\n#' geom_point(aes(mpg, disp))\n#' p2 <- ggplot(mtcars) +\n#' geom_boxplot(aes(gear, disp, group = gear))\n#' p3 <- ggplot(mtcars) +\n#' geom_bar(aes(gear)) +\n#' facet_wrap(~cyl)\n#' align_plots(p1, p2, p3) +\n#' layout_title(title = \"I'm title\")\n#' @importFrom ggplot2 waiver\n#' @export\nlayout_title <- function(title = waiver(), subtitle = waiver(),\n caption = waiver()) {\n if (!is.waive(title)) assert_string(title, allow_null = TRUE)\n if (!is.waive(subtitle)) assert_string(subtitle, allow_null = TRUE)\n if (!is.waive(caption)) assert_string(caption, allow_null = TRUE)\n structure(\n list(title = title, subtitle = subtitle, caption = caption),\n class = c(\"layout_title\", \"plot_annotation\")\n )\n}\n\nS3_layout_title <- S7::new_S3_class(\"layout_title\")\n\nS7::method(alignpatches_add, S3_layout_title) <-\n function(object, patches, objectname) {\n patches@titles <- object\n patches\n }\n\n##############################################################\n#' Modify theme of the layout\n#'\n#' @inherit ggplot2::theme\n#' @param ... A [`theme()`][ggplot2::theme] object or additional element\n#' specifications not part of base ggplot2. In general, these should also be\n#' defined in the `element tree` argument. [`Splicing`][rlang::splice] a list\n#' is also supported.\n#'\n#' @details\n#' A [`theme()`][ggplot2::theme] object used to customize various elements of\n#' the layout, including `guides`, `title`, `subtitle`, `caption`, `margins`,\n#' `panel.border`, and `background`. By default, the theme will inherit from the\n#' parent `layout`.\n#'\n#' - `guides`, `panel.border`, and `background` will always be used even for the\n#' nested `alignpatches` object.\n#'\n#' - `title`, `subtitle`, `caption`, and `margins` will be added for the\n#' top-level `alignpatches` object only.\n#'\n#' @examples\n#' p1 <- ggplot(mtcars) +\n#' geom_point(aes(mpg, disp))\n#' p2 <- ggplot(mtcars) +\n#' geom_boxplot(aes(gear, disp, group = gear))\n#' p3 <- ggplot(mtcars) +\n#' geom_bar(aes(gear)) +\n#' facet_wrap(~cyl)\n#' align_plots(\n#' p1 + theme(plot.background = element_blank()),\n#' p2 + theme(plot.background = element_blank()),\n#' p3 + theme(plot.background = element_blank())\n#' ) +\n#' layout_theme(plot.background = element_rect(fill = \"red\"))\n#' @importFrom ggplot2 theme\n#' @export\nlayout_theme <- rlang::new_function(\n # We utilize editor completion by listing all `theme()` arguments here.\n # By placing `...` at the beginning, we can check if the first\n # following argument is a `theme()` object rather than individual theme\n # elements.\n c(\n rlang::exprs(... = ),\n .subset(\n rlang::fn_fmls(theme),\n vec_set_difference(names(rlang::fn_fmls(theme)), \"...\")\n )\n ),\n quote({\n elements <- ggfun(\"find_args\")(..., complete = NULL, validate = NULL)\n ans <- theme(!!!elements)\n th <- NULL\n for (i in seq_len(...length())) {\n if (inherits(t <- ...elt(i), \"theme\")) {\n th <- ggfun(\"add_theme\")(th, t)\n }\n }\n add_class(ggfun(\"add_theme\")(th, ans), \"layout_theme\")\n })\n)\n\nS3_layout_theme <- S7::new_S3_class(\"layout_theme\")\n\nS7::method(alignpatches_add, S3_layout_theme) <-\n function(object, patches, objectname) {\n patches@theme <- object\n patches\n }\n\nS7::method(alignpatches_add, S7::new_S3_class(\"plot_annotation\")) <-\n function(object, patches, objectname) {\n patches@titles <- .subset(object, names(layout_title()))\n patches@theme <- .subset2(object, \"theme\")\n patches\n }\n\nupdate_layout_theme <- function(old, new) {\n if (is.null(old) || is.null(new)) return(new) # styler: off\n old + new\n}\n\n#' Add layout annotation (internal use)\n#'\n#' This function is a placeholder for future extensions.\n#' If you're trying to apply a theme, use [layout_theme()] instead.\n#'\n#' @param ... Currently unused. May accept a theme in the future.\n#' @param theme A theme object. If not `waiver()`, an error will be raised.\n#'\n#' @return None. This function is used for input validation.\n#' @importFrom ggplot2 is_theme\n#' @export\n#' @keywords internal\nlayout_annotation <- function(..., theme = waiver()) {\n if (is_theme(...elt(1)) || !is.waive(theme)) {\n cli_abort(\"Please use {.fn layout_theme} instead; {.fn layout_annotation} is reserved for future extensions.\")\n }\n}\n"], ["/ggalign/R/layout-chain-.R", "# Used by both `circle_layout()` and `stack_layout()`\n#' @keywords internal\n#' @include layout-.R\nmethods::setClass(\n \"ChainLayout\",\n contains = \"LayoutProto\",\n list(\n data = \"ANY\",\n name = \"character\", # used to provide message\n plot_list = \"list\", # save the list of plots\n design = \"ANY\" # used to align axis\n )\n)\n\n#' Finalize plot modifications from a ChainLayout object.\n#'\n#' This generic function lets a ChainLayout apply any final transformations\n#' to the composed plot before returning it. It does not extract or store\n#' the plot, but instead allows the layout to inject custom modifications\n#' (e.g., spacing guides, annotations, alignment fixes) at the last step.\n#'\n#' @param layout A ChainLayout object.\n#' @param plot The plot being finalized.\n#' @keywords internal\nchain_decorate <- function(layout, plot) UseMethod(\"chain_decorate\")\n\n#' @export\nchain_decorate.ChainLayout <- function(layout, plot) plot\n\n#' @export\nis_layout_discrete.ChainLayout <- function(x, ...) {\n is_discrete_design(x@design)\n}\n\n#' @export\nis_layout_continuous.ChainLayout <- function(x, ...) {\n is_continuous_design(x@design)\n}\n\n#############################################################\n# To-DO: Use double dispatch\n#' @keywords internal\nchain_layout_add <- function(object, layout, object_name) {\n UseMethod(\"chain_layout_add\")\n}\n\n#' @export\nchain_layout_add.layout_title <- function(object, layout, object_name) {\n layout@titles <- update_non_waive(layout@titles, object)\n layout\n}\n\n#' @export\nchain_layout_add.list <- function(object, layout, object_name) {\n for (o in object) layout <- chain_layout_add(o, layout, object_name)\n layout\n}\n\n#' @export\nchain_layout_add.NULL <- function(object, layout, object_name) {\n layout\n}\n\n#' @export\nchain_layout_add.CraftBox <- function(object, layout, object_name) {\n craftsman <- object@craftsman\n # To-Do: Use S7 and double dispatch\n if (is.null(active_index <- layout@active) ||\n is_craftbox(plot <- .subset2(layout@plot_list, active_index))) {\n # unlock the object\n craftsman$unlock()\n\n # we lock the `Craftsman` object to prevent user from modifying this\n # object in `$build_plot()` method, we shouldn't do any calculations in\n # `$build_plot()` method\n on.exit(craftsman$lock())\n\n # initialize the necessary parameters for `Craftsman` object\n if (is_stack_layout(layout)) {\n craftsman$direction <- layout@direction\n craftsman$position <- .subset2(layout@heatmap, \"position\")\n } else if (is_circle_layout(layout)) {\n # we treat circle layout as a vertical stack layout\n craftsman$direction <- \"vertical\"\n }\n craftsman$in_linear <- is_linear(layout)\n craftsman$layout_name <- object_name(layout)\n\n # firstly, we let the object do some changes in the layout\n layout <- craftsman$interact_layout(layout)\n\n # this step, the object will act with the stack layout\n # group rows into panel or reorder rows, we can also\n # initialize object data\n new_design <- craftsman$setup_design(layout@design)\n\n # initialize the plot object\n object@plot <- craftsman$setup_plot(object@plot)\n\n layout <- chain_add_plot(layout, object, object@active, object_name)\n } else { # should be a QuadLayout object\n plot <- quad_layout_add(object, plot, object_name)\n layout@plot_list[[active_index]] <- plot\n new_design <- slot(plot, layout@direction)\n }\n update_design(layout, design = new_design, object_name = object_name)\n}\n\n#' @export\nchain_layout_add.continuous_limits <- function(object, layout, object_name) {\n if (is_discrete_design(layout@design)) {\n cli_abort(c(\n sprintf(\n \"Cannot add {.var {object_name}} to %s\",\n object_name(layout)\n ),\n i = sprintf(\n \"%s cannot align continuous variables\",\n object_name(layout)\n )\n ))\n }\n update_design(layout, design = object, object_name = object_name)\n}\n\n#' @export\nchain_layout_add.ggplot <- function(object, layout, object_name) {\n chain_layout_add(ggfree(data = object), layout, object_name)\n}\n\n# Add ggplot2 elements\n#' @export\nchain_layout_add.default <- function(object, layout, object_name) {\n if (is.null(active_index <- layout@active)) {\n cli_abort(c(\n sprintf(\n \"Cannot add {.var {object_name}} to %s\",\n object_name(layout)\n ),\n i = \"No active plot component\",\n i = paste(\n \"Did you forget to initialize a {.cls ggplot} object\",\n \"with {.fn ggalign} or {.fn ggfree}?\"\n )\n ))\n }\n plot <- .subset2(layout@plot_list, active_index)\n if (is_craftbox(plot)) {\n plot <- chain_plot_add(plot, object, object_name, TRUE)\n } else {\n plot <- quad_layout_add(object, plot, object_name)\n }\n layout@plot_list[[active_index]] <- plot\n layout\n}\n\n#' @export\nchain_layout_add.layout_theme <- function(object, layout, object_name) {\n if (is.null(active_index <- layout@active) ||\n is_craftbox(plot <- .subset2(layout@plot_list, active_index))) {\n layout@theme <- update_layout_theme(layout@theme, object)\n } else {\n layout@plot_list[[active_index]] <- quad_layout_add(\n object, plot, object_name\n )\n }\n layout\n}\n\nchain_plot_add <- function(plot, object, object_name, force) {\n # if `align` has plot, we added the object\n if (force || !is.null(plot@plot)) {\n plot <- craftbox_add(object, plot, object_name)\n }\n plot\n}\n\nchain_add_plot <- function(layout, plot, active, object_name) {\n # set up context index\n plot_list <- layout@plot_list\n if (.subset2(active, \"use\")) {\n active_index <- length(plot_list) + 1L\n } else {\n active_index <- layout@active\n }\n # check the name is unique\n if (!is.na(name <- .subset2(active, \"name\"))) {\n if (any(names(plot_list) == name)) {\n cli_warn(\n \"Adding {.var {object_name}} will replace existing {.field {name}} plot\"\n )\n }\n plot_list[[name]] <- plot\n } else {\n plot_list <- c(plot_list, list(plot))\n }\n\n # add QuadLayout\n layout@plot_list <- plot_list\n layout@active <- active_index\n layout\n}\n\nswitch_chain_plot <- function(layout, what, call = caller_call()) {\n if (!is.waive(what)) {\n if (!is.null(what)) {\n what <- vec_as_location2(\n what,\n vec_size(layout@plot_list),\n vec_names(layout@plot_list),\n missing = \"error\",\n arg = \"what\", call = call\n )\n }\n layout@active <- what\n }\n layout\n}\n\n##############################################################\n# for `stack_layout()` only\n#' @export\nchain_layout_add.ggalign_with_quad <- function(object, layout, object_name) {\n if (!is_stack_layout(layout)) {\n cli_abort(sprintf(\n \"Cannot add {.var {object_name}} to %s\",\n object_name(layout)\n ))\n }\n if (is.null(active_index <- layout@active) ||\n is_craftbox(plot <- .subset2(layout@plot_list, active_index))) {\n cli_abort(c(\n sprintf(\n \"Cannot add {.var {object_name}} to %s\",\n object_name(layout)\n ),\n i = \"Did you forget to add a {.fn quad_layout}?\"\n ))\n } else {\n layout@plot_list[[active_index]] <- quad_layout_add(\n object, plot, object_name\n )\n }\n layout\n}\n\n#' @export\nchain_layout_add.quad_active <- chain_layout_add.ggalign_with_quad\n\n#' @export\nchain_layout_add.quad_anno <- chain_layout_add.quad_active\n\n#' @export\nchain_layout_add.StackLayout <- chain_layout_add.quad_active\n\n#' @export\nchain_layout_add.StackCross <- function(object, layout, object_name) {\n if (!is_stack_layout(layout)) {\n cli_abort(sprintf(\n \"Cannot add {.var {object_name}} to %s\",\n object_name(layout)\n ))\n }\n\n # preventing from adding `stack_cross` with the same direction in this way,\n # `stack_cross()` cannot be added to the heatmap annotation parallelly with\n # the `stack_layout()`\n if (identical(object@direction, layout@direction)) {\n cli_abort(c(\n sprintf(\n \"Cannot add {.var {object_name}} to %s\",\n object_name(layout)\n ),\n i = \"Cannot add {.fn stack_cross} with the same direction as {.fn stack_discrete}.\"\n ))\n }\n NextMethod() # call StackLayout method\n}\n\n#' @export\nchain_layout_add.stack_switch <- function(object, layout, object_name) {\n if (!is_stack_layout(layout)) {\n cli_abort(c(\n sprintf(\n \"Cannot add {.var {object_name}} to %s\",\n object_name(layout)\n ),\n i = \"Did you want to add a {.fn circle_switch}?\"\n ))\n }\n layout <- switch_chain_plot(\n layout, .subset2(object, \"what\"),\n quote(stack_switch())\n )\n if (!is.null(sizes <- .subset2(object, \"sizes\"))) {\n layout@sizes <- sizes\n }\n layout\n}\n\n#' @importFrom methods slot\n#' @export\nchain_layout_add.QuadLayout <- function(object, layout, object_name) {\n if (!is_stack_layout(layout)) {\n cli_abort(sprintf(\n \"Cannot add {.var {object_name}} to %s\",\n object_name(layout)\n ))\n }\n\n # preventing from adding `stack_cross` with the same direction\n # `cross_link()` cannot be added to the heatmap annotation\n # parallelly with the `stack_cross()`\n if (is_horizontal(direction <- layout@direction)) {\n if (is_cross_layout(object@left) || is_cross_layout(object@right)) {\n cli_abort(c(\n sprintf(\n \"Cannot add {.var {object_name}} to %s\",\n object_name(layout)\n ),\n i = sprintf(\n \"{.field left} or {.field right} annotation contains %s\",\n \"{.fn stack_cross}\"\n )\n ))\n }\n } else if (is_cross_layout(object@top) || is_cross_layout(object@bottom)) {\n cli_abort(c(\n sprintf(\n \"Cannot add {.var {object_name}} to %s\",\n object_name(layout)\n ),\n i = sprintf(\n \"{.field top} or {.field bottom} annotation contains %s\",\n \"{.fn stack_cross}\"\n )\n ))\n }\n\n # check quad layout is compatible with stack layout\n quad_data <- object@data\n stack_design <- layout@design\n quad_design <- slot(object, direction)\n if (is_continuous_design(quad_design)) {\n if (is_discrete_design(stack_design)) {\n cli_abort(c(\n sprintf(\n \"Cannot add %s to %s\",\n object_name(object), object_name(layout)\n ),\n i = sprintf(\n \"%s cannot align continuous variable\",\n object_name(layout)\n )\n ))\n }\n # `quad_layout()` will align continuous variables,\n # `data` can be `NULL`\n extra_design <- slot(object, vec_set_difference(\n c(\"vertical\", \"horizontal\"), direction\n ))\n allow_null <- is_continuous_design(extra_design)\n if (is.waive(quad_data) || is.function(quad_data)) {\n # check if we should initialize the `quad_layout()` data\n if (is.null(stack_data <- layout@data)) {\n if (allow_null) {\n quad_data <- NULL\n } else {\n cli_abort(c(\n sprintf(\n \"you must provide {.arg data} argument in %s\",\n object_name(object)\n ),\n i = sprintf(\n \"no data was found in %s\",\n object_name(layout)\n )\n ))\n }\n } else {\n data <- stack_data # should be a data frame\n if (is.waive(quad_data)) { # inherit from the stack layout\n if (!allow_null) { # we need a matrix\n cli_abort(c(\n sprintf(\n \"Cannot add %s to %s\",\n object_name(object), object_name(layout)\n ),\n i = sprintf(\n \"{.arg data} in %s is %s, but %s need a {.cls matrix}.\",\n object_name(layout),\n \"{.obj_type_friendly {data}}\",\n object_name(object)\n ),\n i = sprintf(\n \"Try provide {.arg data} in %s\",\n object_name(object)\n )\n ))\n }\n } else { # `quad_data` is a function\n data <- quad_data(data)\n # check the data format is correct\n if (allow_null) { # we need a data frame\n if (!is.data.frame(data)) {\n cli_abort(sprintf(\n \"{.arg data} in %s must return a {.cls data.frame}\",\n object_name(object)\n ))\n }\n } else if (!is.matrix(data)) { # we need a matrix\n cli_abort(sprintf(\n \"{.arg data} in %s must return a {.cls matrix}\",\n object_name(object)\n ))\n } else {\n if (NROW(data) == 0L || ncol(data) == 0L) {\n cli_abort(sprintf(\n \"{.arg data} in %s return an empty matrix\",\n object_name(object)\n ))\n }\n }\n }\n # we initialize the `nobs` of the extra_design for the\n # `quad_layout()`\n if (is_horizontal(direction)) {\n if (is_discrete_design(slot(object, \"vertical\"))) {\n slot(object, \"vertical\")$nobs <- ncol(data)\n }\n } else {\n if (is_discrete_design(slot(object, \"horizontal\"))) {\n slot(object, \"horizontal\")$nobs <- nrow(data)\n }\n }\n }\n # restore the ggalign attribute\n object@data <- ggalign_data_restore(data, stack_data)\n }\n layout_design <- quad_design\n } else if (is_discrete_design(stack_design)) {\n # both `quad_layout()` and `stack_layout()` will align discrete\n # variables\n if (is.waive(quad_data) || is.function(quad_data)) {\n if (is.null(stack_data <- layout@data)) {\n cli_abort(c(\n sprintf(\n \"you must provide {.arg data} argument in %s\",\n object_name(object)\n ),\n i = sprintf(\n \"no data was found in %s\",\n object_name(layout)\n )\n ))\n }\n # set `quad_layout()` data\n data <- switch_direction(direction, stack_data, t(stack_data))\n if (is.function(quad_data)) {\n data <- quad_data(data)\n if (!is.matrix(data)) {\n cli_abort(sprintf(\n \"{.arg data} in %s must return a matrix\",\n object_name(object)\n ))\n }\n if (NROW(data) == 0L || ncol(data) == 0L) {\n cli_abort(sprintf(\n \"{.arg data} in %s return an empty matrix\",\n object_name(object)\n ))\n }\n } else {\n if (NROW(data) == 0L || ncol(data) == 0L) {\n cli_abort(c(\n sprintf(\n \"Cannot use data from %s in %s\",\n object_name(layout), object_name(object)\n ),\n i = sprintf(\n \"{.arg data} in %s is an empty matrix\",\n object_name(layout)\n )\n ))\n }\n }\n # set the `nobs` for `quad_layout()`\n if (is_horizontal(direction)) {\n quad_design$nobs <- nrow(data)\n if (is_discrete_design(slot(object, \"vertical\"))) {\n slot(object, \"vertical\")$nobs <- ncol(data)\n }\n } else {\n quad_design$nobs <- ncol(data)\n if (is_discrete_design(slot(object, \"horizontal\"))) {\n slot(object, \"horizontal\")$nobs <- nrow(data)\n }\n }\n # restore the ggalign attribute\n object@data <- ggalign_data_restore(data, stack_data)\n }\n layout_design <- melt_discrete_design(\n stack_design, quad_design,\n old_name = object_name(layout),\n new_name = object_name\n )\n } else {\n cli_abort(c(\n sprintf(\n \"Cannot add %s to %s\",\n object_name(object), object_name(layout)\n ),\n i = sprintf(\n \"%s cannot align discrete variable\",\n object_name(layout)\n )\n ))\n }\n stack <- chain_add_plot(layout, object, object@plot_active, object_name)\n update_design(\n stack,\n design = layout_design,\n object_name = object_name\n )\n}\n\n##################################################\n#' @export\nchain_layout_add.circle_switch <- function(object, layout, object_name) {\n if (!is_circle_layout(layout)) {\n cli_abort(c(\n sprintf(\n \"Cannot add {.var {object_name}} to %s\",\n object_name(layout)\n ),\n i = \"Did you want to add a {.fn stack_switch}?\"\n ))\n }\n if (!is.waive(radial <- .subset2(object, \"radial\"))) {\n layout@radial <- radial\n }\n if (!is.null(direction <- .subset2(object, \"direction\"))) {\n layout@direction <- direction\n }\n layout <- switch_chain_plot(\n layout, .subset2(object, \"what\"),\n quote(circle_switch())\n )\n layout\n}\n"], ["/ggalign/R/layout-heatmap-oncoplot.R", "#' Create an OncoPrint\n#'\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' The `ggoncoplot()` function generates `oncoPrint` visualizations that display\n#' genetic alterations in a matrix format. This function is especially useful\n#' for visualizing complex genomic data, such as mutations, copy number\n#' variations, and other genomic alterations in cancer research.\n#'\n#' @details\n#' `ggoncoplot()` is a wrapper around the [`ggheatmap()`] function, designed to\n#' simplify the creation of `OncoPrint`-style visualizations. The function\n#' automatically processes the input character matrix by splitting the encoded\n#' alterations (delimited by `r oxford_or(c(\";\", \":\", \",\", \"|\"))`) into\n#' individual genomic events and unnesting the columns for visualization.\n#'\n#' @param data A character matrix which encodes the alterations, you can use\n#' `r oxford_or(c(\";\", \":\", \",\", \"|\"))` to separate multiple alterations.\n#' @inheritParams heatmap_layout\n#' @param map_width,map_height A named numeric value defines the width/height of\n#' each alterations.\n#'\n#' @param reorder_row A boolean value indicating whether to reorder the rows\n#' based on the frequency of alterations. You can set this to `FALSE`, then add\n#' `align_order(~rowSums(!is.na(.x)), reverse = TRUE)` to achieve the same\n#' result. You may also need to set `strit = FALSE` in [`align_order()`] if\n#' there are already groups.\n#'\n#' @param reorder_column A boolean value indicating whether to reorder the\n#' columns based on the characteristics of the alterations. You can set this to\n#' `FALSE`, then add `align_order2(memo_order)` to achieve the same result. You\n#' may also need to set `strit = FALSE` in [`align_order2()`] if there are\n#' already groups.\n#'\n#' @param remove_duplicates A logical value indicating whether to remove\n#' duplicated variants within the same cell.\n#'\n#' @param filling Same as [`ggheatmap()`], but only `\"tile\"` can be used.\n#' @examples\n#' # A simple example from `ComplexHeatmap`\n#' mat <- read.table(textConnection(\n#' \"s1,s2,s3\n#' g1,snv;indel,snv,indel\n#' g2,,snv;indel,snv\n#' g3,snv,,indel;snv\"\n#' ), row.names = 1, header = TRUE, sep = \",\", stringsAsFactors = FALSE)\n#'\n#' ggoncoplot(mat, map_width = c(snv = 0.5), map_height = c(indel = 0.9)) +\n#' guides(fill = \"none\") +\n#' anno_top(size = 0.5) +\n#' ggalign() +\n#' geom_bar(aes(fill = value), data = function(x) {\n#' subset(x, !is.na(value))\n#' }) +\n#' anno_right(size = 0.5) +\n#' ggalign() +\n#' geom_bar(aes(fill = value), orientation = \"y\", data = function(x) {\n#' subset(x, !is.na(value))\n#' }) &\n#' scale_fill_brewer(palette = \"Dark2\", na.translate = FALSE)\n#' @inherit heatmap_layout return\n#' @importFrom ggplot2 aes\n#' @export\nggoncoplot <- function(data = NULL, mapping = aes(), ...,\n map_width = NULL, map_height = NULL,\n reorder_row = reorder_column,\n reorder_column = TRUE,\n remove_duplicates = FALSE,\n width = NA, height = NA, filling = waiver(),\n theme = NULL, active = NULL) {\n UseMethod(\"ggoncoplot\")\n}\n\n#' @export\nggoncoplot.NULL <- function(data = NULL, mapping = aes(), ...) {\n cli_abort(\"{.fn ggoncoplot} only accept a valid character matrix\")\n}\n\n#' @export\nggoncoplot.functon <- ggoncoplot.NULL\n\n#' @export\nggoncoplot.formula <- ggoncoplot.functon\n\n#' @importFrom ggplot2 aes\n#' @importFrom rlang arg_match0\n#' @export\n#' @rdname ggoncoplot\nggoncoplot.default <- function(data = NULL, mapping = aes(), ...,\n map_width = NULL, map_height = NULL,\n reorder_row = reorder_column,\n reorder_column = TRUE,\n remove_duplicates = FALSE,\n width = NA, height = NA, filling = waiver(),\n theme = NULL, active = NULL) {\n # prepare the matrix\n data <- fortify_matrix(data = data, ...)\n if (!is.character(data)) {\n cli_abort(\"{.arg data} must be a character matrix\")\n }\n\n assert_bool(reorder_column)\n assert_bool(reorder_row)\n assert_bool(remove_duplicates)\n\n # convert empty string into NA\n data <- trimws(data, whitespace = \"[\\\\h\\\\v]\")\n data[data == \"\"] <- NA_character_\n\n # check filling\n if (isTRUE(filling) || is.waive(filling)) {\n filling <- \"tile\"\n } else if (isFALSE(filling)) {\n filling <- NULL\n } else if (!is.null(filling)) {\n filling <- arg_match0(filling, c(\"tile\", \"raster\"))\n if (filling == \"raster\") {\n cli_warn(\"Cannot use {.fn geom_raster} in oncoplot\")\n filling <- \"tile\"\n }\n }\n\n # prepare the plot data action\n pdata <- function(data) {\n vars <- strsplit(data$value, split = \"\\\\s*[;:,|]\\\\s*\", perl = TRUE)\n if (remove_duplicates) vars <- lapply(vars, vec_unique)\n lvls <- ggalign_lvls_get(data)\n data <- vec_rep_each(data, list_sizes(vars))\n value <- unlist(vars, recursive = FALSE, use.names = FALSE)\n if (!is.null(lvls)) value <- factor(value, levels = lvls)\n data$value <- value\n data\n }\n\n # draw the oncoplot\n ans <- heatmap_layout(\n data = data, mapping = mapping,\n width = width, height = height,\n theme = theme, active = active, filling = NULL\n ) -\n # set the default `scheme_data()`\n scheme_data(data = pdata)\n\n # prepare counts matrix to reorder the column or rows\n if (reorder_column || reorder_row) {\n counts <- !is.na(data)\n storage.mode(counts) <- \"integer\"\n weights <- rowSums(counts)\n row_index <- order(weights, decreasing = TRUE)\n }\n\n if (reorder_row) {\n ans <- ans + anno_left() + align_order(row_index, reverse = TRUE)\n }\n if (reorder_column) {\n column_scores <- .memo_order(vec_slice(counts, row_index))\n ans <- ans +\n anno_top() +\n align_order(order(column_scores, decreasing = TRUE))\n }\n\n # reset the active context\n ans <- ans + quad_active()\n if (!is.null(filling)) {\n # we always make sure heatmap body has such action data\n ans <- ans + scheme_data(data = pdata)\n\n # set mapping for width and height\n tile_mapping <- aes(\n .data$.x, .data$.y,\n fill = .data$value,\n width = replace_na(map_width[.data$value], 1),\n height = replace_na(map_height[.data$value], 1)\n )\n if (!is.null(map_width)) {\n if (!rlang::is_named(map_width) || !is.numeric(map_width)) {\n cli_abort(\"{.arg map_width} must be a named numeric\")\n }\n } else {\n tile_mapping$width <- NULL\n }\n if (!is.null(map_height)) {\n if (!rlang::is_named(map_height) || !is.numeric(map_height)) {\n cli_abort(\"{.arg map_height} must be a named numeric\")\n }\n } else {\n tile_mapping$height <- NULL\n }\n # check if user has provided and manual fill mapping\n if (!is.null(.subset2(ans@plot$mapping, \"fill\"))) {\n tile_mapping$fill <- NULL\n }\n ans <- ans + ggplot2::geom_tile(tile_mapping)\n }\n ans\n}\n\n#' Sort matrix for better visualization\n#'\n#' Helper function used to order the Oncoplot samples. Typically, you would use\n#' this in combination with [`align_order2()`], e.g.,\n#' `align_order2(memo_order)`.\n#'\n#' @param x A matrix, where `NA` values will be treated as empty.\n#' @return A vector of ordering weights.\n#' @export\nmemo_order <- function(x) {\n # For `align_order2()`, rows are considered as the observations\n # `.memo_order` will regard the columns as the observations\n .memo_order(t(x), counts = FALSE, reorder_rows = TRUE)\n}\n\n# Following code is modified from\n# \n.memo_order <- function(x, counts = TRUE, reorder_rows = FALSE) {\n if (!isTRUE(counts)) {\n x <- !is.na(x)\n storage.mode(x) <- \"integer\"\n }\n if (isTRUE(reorder_rows)) {\n row_index <- order(rowSums(x), decreasing = TRUE)\n x <- vec_slice(x, row_index)\n }\n structure(\n apply(x, 2L, function(x) {\n score <- 2^(length(x) - seq_along(x))\n score[x == 0L] <- 0\n sum(score)\n }),\n class = \"memo_weights\"\n )\n}\n\n#' @export\n#' @rdname order2\norder2.memo_weights <- function(x) order(x, decreasing = TRUE)\n"], ["/ggalign/R/layout-operator.R", "#' Layout operator\n#'\n#' @description\n#' `r lifecycle::badge('experimental')`\n#'\n#' - `+`: Adds elements to the active plot in the active layout.\n#' - `&`: Applies elements to all plots in the layout.\n#' - `-`: Adds elements to multiple plots in the layout.\n#'\n#' @details\n#' The `+` operator is straightforward and should be used as needed.\n#'\n#' In order to reduce code repetition `ggalign` provides two operators for\n#' adding ggplot elements (geoms, themes, facets, etc.) to multiple/all plots in\n#' `r rd_layout()`: `-` and `&`.\n#'\n#' @param e1 A `r rd_layout()`.\n#' @param e2 An object to be added to the plot.\n#' @return A modified `Layout` object.\n#' @examples\n#' set.seed(123)\n#' small_mat <- matrix(rnorm(56), nrow = 7)\n#' ggheatmap(small_mat) +\n#' anno_top() +\n#' ggalign() +\n#' geom_point(aes(y = value))\n#'\n#' # `&` operator apply it to all plots\n#' ggheatmap(small_mat) +\n#' anno_top() +\n#' align_dendro() &\n#' theme(panel.border = element_rect(\n#' colour = \"red\", fill = NA, linewidth = unit(2, \"mm\")\n#' ))\n#'\n#' # If the active layout is the annotation stack, the `-` operator will only\n#' # add the elements to all plots in the active annotation stack:\n#' ggheatmap(small_mat) +\n#' anno_left(size = 0.2) +\n#' align_dendro(aes(color = branch), k = 3L) +\n#' align_dendro(aes(color = branch), k = 3L) -\n#' # Modify the the color scales of all plots in the left annotation\n#' scale_color_brewer(palette = \"Dark2\")\n#'\n#' # If the active layout is the `stack_layout()` itself, `-`\n#' # applies the elements to all plots in the layout except the nested\n#' # `ggheatmap()`/`quad_layout()`.\n#' stack_alignv(small_mat) +\n#' align_dendro() +\n#' ggtitle(\"I'm from the parent stack\") +\n#' ggheatmap() +\n#' # remove any active context\n#' stack_active() +\n#' align_dendro() +\n#' ggtitle(\"I'm from the parent stack\") -\n#' # Modify the the color scales of all plots in the stack layout except the\n#' # heatmap layout\n#' scale_color_brewer(palette = \"Dark2\") -\n#' # set the background of all plots in the stack layout except the heatmap\n#' # layout\n#' theme(plot.background = element_rect(fill = \"red\"))\n#'\n#' @name layout-operator\nNULL\n\nutils::globalVariables(\".Generic\")\n\nmethods::setMethod(\"Ops\", c(\"LayoutProto\", \"ANY\"), function(e1, e2) {\n if (missing(e2)) {\n cli_abort(c(\n \"Cannot use {.code {.Generic}} with a single argument.\",\n \"i\" = \"Did you accidentally put {.code {.Generic}} on a new line?\"\n ))\n }\n\n if (is.null(e2)) return(e1) # styler: off\n\n # Get the name of what was passed in as e2, and pass along so that it\n # can be displayed in error messages\n e2name <- deparse(substitute(e2))\n switch(.Generic, # nolint\n `+` = layout_add(e1, e2, e2name),\n `-` = layout_subtract(e1, e2, e2name),\n `&` = layout_and_add(e1, e2, e2name),\n stop_incompatible_op(.Generic, e1, e2)\n )\n})\n\n#################################################################\nlayout_add <- function(layout, object, object_name) {\n UseMethod(\"layout_add\")\n}\n\n#' @export\nlayout_add.QuadLayout <- function(layout, object, object_name) {\n quad_layout_add(object, layout, object_name)\n}\n\n#' @export\nlayout_add.ChainLayout <- function(layout, object, object_name) {\n chain_layout_add(object, layout, object_name)\n}\n\n#################################################################\nlayout_subtract <- function(layout, object, object_name) {\n UseMethod(\"layout_subtract\")\n}\n\n#' @export\nlayout_subtract.QuadLayout <- function(layout, object, object_name) {\n quad_layout_subtract(object, layout, object_name)\n}\n\n#' @export\nlayout_subtract.ChainLayout <- function(layout, object, object_name) {\n chain_layout_subtract(object, layout, object_name)\n}\n\n#################################################################\n# we use and_add suffix here, since `and` is very similar with `add`.\nlayout_and_add <- function(layout, object, object_name) {\n UseMethod(\"layout_and_add\")\n}\n\n#' @export\nlayout_and_add.QuadLayout <- function(layout, object, object_name) {\n quad_layout_and_add(object, layout, object_name)\n}\n\n#' @export\nlayout_and_add.ChainLayout <- function(layout, object, object_name) {\n chain_layout_and_add(object, layout, object_name)\n}\n\n# For objects cannot be used with `-` or `&`\n#' @include layout-quad-operator.R\n#' @include layout-chain-operator.R\nlapply(\n c(\n \"quad_layout_subtract\", \"chain_layout_subtract\",\n \"quad_layout_and_add\", \"chain_layout_and_add\"\n ),\n function(genname) {\n params <- .subset2(strsplit(genname, \"_\"), 1L)\n\n # function argument list\n pairlist <- rlang::pairlist2(object = , layout = , object_name = )\n names(pairlist) <- c(\"object\", .subset(params, 1L), \"object_name\")\n operator <- switch(.subset(params, 3L),\n subtract = \"-\",\n and = \"&\"\n )\n # styler: off\n for (class in c(\"ggplot\", \"quad_active\", \"quad_anno\", \"layout_title\",\n \"layout_theme\", \"CraftBox\", \"ChainLayout\",\n \"QuadLayout\", \"continuous_limits\")) {\n # styler: on\n registerS3method(\n genname, class,\n rlang::new_function(pairlist, substitute(\n {\n cli_abort(c(\n sprintf(\n \"Cannot add %s with {.code %s}\",\n name, operator\n ),\n i = \"Try to use {.code +} instead\"\n ))\n },\n list(\n name = switch(class,\n CraftBox = ,\n ChainLayout = ,\n QuadLayout = quote(object_name(object)),\n # for all others\n \"{.var {object_name}}\"\n ),\n operator = operator\n )\n ))\n )\n }\n }\n)\n"], ["/ggalign/R/utils-assert.R", "# `assert_*()` functions will do the side effects\n# `check_*()` functions will return the arguments\n#' @importFrom rlang caller_arg caller_call\nassert_gp <- function(gp, arg = caller_arg(gp), call = caller_call()) {\n assert_s3_class(gp, \"gpar\", arg = arg, call = call)\n}\n\n#' @importFrom rlang caller_arg caller_call\nassert_mapping <- function(mapping, arg = caller_arg(mapping),\n call = caller_call()) {\n if (!inherits(mapping, \"uneval\")) {\n cli_abort(c(\"{.arg {arg}} must be created with {.fn aes}.\",\n x = \"You've supplied {.obj_type_friendly {mapping}}.\"\n ), call = call)\n }\n}\n\nassert_mismatch_nobs <- function(align, n, nobs, arg) {\n if (n != nobs) {\n cli_abort(sprintf(\n \"{.arg %s} (nobs: %d) of %s is not compatible with the %s (nobs: %d)\",\n arg, nobs, object_name(align), align$layout_name, n\n ))\n }\n}\n\nassert_sub_split <- function(align, panel) {\n if (!is.null(panel)) {\n cli_abort(c(\n sprintf(\"%s cannot do sub-split\", object_name(align)),\n i = sprintf(\n \"Group of layout %s-axis already exists\",\n to_coord_axis(align$direction)\n )\n ), call = align$call)\n }\n}\n\nassert_reorder <- function(align, panel, index, strict) {\n if (!is.null(panel) && nlevels(panel) > 1L && strict &&\n !all(index == reorder_index(panel, index))) {\n layout_name <- align$layout_name\n object_name <- object_name(align)\n cli_abort(c(\n sprintf(\"Cannot add %s to %s\", object_name, layout_name),\n i = sprintf(\n \"Group of %s will disrupt the ordering index of %s\", layout_name, object_name\n ),\n i = \"try to set {.code strict = FALSE} to reorder within each group\"\n ), call = align$call)\n }\n}\n\nassert_position <- function(position, arg = caller_arg(position),\n call = caller_call()) {\n assert_string(position, empty_ok = FALSE, arg = arg, call = call)\n if (grepl(\"[^tlbr]\", position)) {\n cli_abort(sprintf(\n \"{.arg {arg}} can only contain the %s characters\",\n oxford_and(.tlbr)\n ), call = call)\n }\n}\n\nassert_guides <- function(guides, arg = caller_arg(guides),\n call = caller_call()) {\n assert_string(guides, empty_ok = FALSE, arg = arg, call = call)\n if (grepl(\"[^tlbri]\", guides)) {\n cli_abort(sprintf(\n \"{.arg {arg}} can only contain the %s characters\",\n oxford_and(c(.tlbr, \"i\"))\n ), call = call)\n }\n}\n\nassert_layout_position <- function(position, arg = caller_arg(position),\n call = caller_call()) {\n if (!is.waive(position) && !is.null(position)) {\n assert_position(position, arg = arg, call = call)\n }\n}\n\nassert_layout_guides <- function(guides, arg = caller_arg(guides),\n call = caller_call()) {\n if (!is.waive(guides) && !is.null(guides)) {\n assert_guides(guides, arg = arg, call = call)\n }\n}\n\n#' @importFrom grid is.unit\ncheck_stack_sizes <- function(sizes, arg = caller_arg(sizes),\n call = caller_call()) {\n if (!(all(is.na(sizes)) || is.numeric(sizes) || is.unit(sizes))) {\n cli_abort(\n \"{.arg {arg}} must be a numeric or {.cls unit} object\",\n call = call\n )\n }\n l <- length(sizes)\n if (l != 1L && l != 3L) {\n cli_abort(\n \"{.arg {arg}} must have size `1` or `3`, not size {l}\",\n call = call\n )\n }\n if (!is.unit(sizes)) sizes <- unit(sizes, \"null\")\n sizes\n}\n\n#' @importFrom rlang arg_match0\ncheck_direction <- function(direction, arg = caller_arg(direction),\n call = caller_call()) {\n direction <- arg_match0(direction, c(\"h\", \"v\"),\n arg_nm = arg, error_call = call\n )\n switch(direction, h = \"horizontal\", v = \"vertical\") # styler: off\n}\n\nassert_limits <- function(limits, allow_null = TRUE, arg = caller_arg(limits),\n call = caller_call()) {\n if (is.null(limits) && allow_null) {\n return(invisible(NULL))\n }\n if (!inherits(limits, \"continuous_limits\")) {\n cli_abort(\n \"{.arg {arg}} must be specified with {.fn continuous_limits}\",\n call = call\n )\n }\n if (rlang::is_named(limits)) {\n cli_abort(\n \"{.arg {arg}} shouldn't be created with {.arg x}/{.arg y} argument in {.fn continuous_limits}\",\n call = call\n )\n }\n}\n\n#' @importFrom grid is.unit\ncheck_size <- function(size, arg = caller_arg(size), call = caller_call()) {\n if (!is_scalar(size) &&\n !(is.na(size) || is.numeric(size) || is.unit(size))) {\n cli_abort(\n \"{.arg {arg}} must be a single numeric or unit object\",\n call = call\n )\n }\n if (!is.unit(size)) size <- unit(size, \"null\")\n size\n}\n\ncheck_scheme_data <- function(data, arg = caller_arg(data),\n call = caller_call()) {\n if (!is.waive(data) && !is.null(data) &&\n !is.function(data <- allow_lambda(data))) {\n cli_abort(paste(\n \"{.arg {arg}} must be a function,\",\n \"{.code NULL} or {.fn waiver}\"\n ), call = call)\n }\n data\n}\n\ncheck_stack_context <- function(what, arg = caller_arg(what),\n call = caller_call()) {\n if (is.null(what)) return(what) # styler: off\n if (.rlang_check_number(what, allow_decimal = FALSE, min = 1) != 0L &&\n !is_string(what)) {\n cli_abort(\n \"{.arg {arg}} must be a single positive integer number or string\",\n call = call\n )\n }\n what\n}\n\ncheck_order <- function(order, arg = caller_arg(order), call = caller_call()) {\n if (is.null(order)) {\n NA_integer_\n } else if (.rlang_check_number(order, allow_decimal = FALSE) == 0L) {\n as.integer(order)\n } else {\n cli_abort(\"{.arg {arg}} must be single integer number\", call = call)\n }\n}\n\nassert_align <- function(x, arg = caller_arg(x), call = caller_call()) {\n if (!inherits(x, \"scheme_align\")) {\n cli_abort(\n \"{.arg {arg}} must be created by {.fn scheme_align}\",\n call = call\n )\n }\n}\n\nassert_active <- function(x, allow_null = TRUE,\n arg = caller_arg(x), call = caller_call()) {\n if (is.null(x) && allow_null) {\n return(invisible(NULL))\n }\n if (!inherits(x, \"ggalign_active\")) {\n cli_abort(\n \"{.arg {arg}} must be created by {.fn active}\",\n call = call\n )\n }\n}\n\nassert_obs_size <- function(obs_size, arg = caller_arg(obs_size),\n call = caller_call()) {\n if (.rlang_check_number(obs_size, allow_decimal = TRUE, # styler: off\n .Machine$double.eps, 1) != 0L) { # styler: off\n cli_abort(\n \"{.arg {arg}} must be a single number in `(0, 1]`\",\n call = call\n )\n }\n}\n"], ["/ggalign/R/with_quad.R", "#' Modify operated Context in `quad_layout()`\n#'\n#' @description\n#' `r lifecycle::badge('experimental')`\n#'\n#' The `with_quad()` function modifies the application context of elements in\n#' `ggheatmap()`/`quad_layout()`. It controls how objects like themes, scales,\n#' or other plot modifications apply to specific annotation stacks or the main\n#' plot without altering the currently active layout or plot.\n#'\n#' @param x An object which can be added to the ggplot, including\n#' **schemes**. See [`scheme_align()`], [`scheme_data()`], and\n#' [`scheme_theme()`]\n#' @param position A string specifying one or more positions-\n#' `r oxford_and(.tlbr)`- to indicate the annotation stack context for `x`. If\n#' `NULL`, will change the operated context to the `quad_layout()` itself. For\n#' default behaivours, see `details` section.\n#' @param main A single boolean value indicating whether `x` should apply to the\n#' main plot, used only when `position` is not `NULL`. By default, if `position`\n#' is `waiver()` and the active context of `quad_layout()` is an annotation\n#' stack or the active context of `stack_layout()` is itself, `main` will be set\n#' to `TRUE`; otherwise, it defaults to `FALSE`.\n#' @return The original object with an added attribute that sets the specified\n#' context.\n#' @details\n#' Default Behavior when adding object wrapped with `with_quad()`:\n#'\n#' For `quad_layout()` object:\n#'\n#' - When `ggheatmap()`/`quad_layout()` has no active annotation stack, objects\n#' added via `+` or `-` operate normally without `with_quad()`.\n#' - When the active annotation stack is set, `with_quad()` ensures the applied\n#' object also modifies:\n#' * The main plot (by default).\n#' * Opposite annotation stacks when using `-`.\n#'\n#' For `stack_layout()` object:\n#'\n#' - When the active layout is the `stack_layout()` itself:\n#' * `-` operator will apply changes to all plots along the\n#' `stack_layout()`, which means if the stack layout is in `horizontal`,\n#' `-` operator will also add the element to the `left` and `right`\n#' annotation, if the stack layout is in `vertical`, `-` operator will\n#' also add element to the `top` and `bottom` annotation.\n#' * `+` operator won't do anything special.\n#' - When the active layout is the nested `ggheatmap()`/`quad_layout()`, the\n#' `+`/`-` operator applies the elements to this nested layout, following the\n#' same principles as for `ggheatmap()`/`quad_layout()`.\n#'\n#' @examples\n#' set.seed(123)\n#' small_mat <- matrix(rnorm(56), nrow = 7)\n#'\n#' # By wrapping object with `with_quad()`, the `+` operator will apply the\n#' # object not only to the active plot in the annotation stack, but also to\n#' # the main plot unless specified by `main` argument otherwise.\n#' ggheatmap(small_mat) +\n#' # initialize the left annotation\n#' anno_left(size = 0.2) +\n#' align_dendro() +\n#' # apply the object not only to the active plot in the annotation stack,\n#' # but also to the main plot\n#' with_quad(theme(plot.background = element_rect(fill = \"red\")))\n#'\n#' # the `-` operator will apply changes not only to the active annotation\n#' # stack but also to the opposite one (i.e., bottom if top is active, and\n#' # vice versa). The same principle applies to the left and right annotation.\n#' ggheatmap(small_mat) +\n#' anno_left(size = 0.2) +\n#' align_dendro(aes(color = branch), k = 3L) +\n#' # Change the active layout to the left annotation\n#' anno_top(size = 0.2) +\n#' align_dendro(aes(color = branch), k = 3L) +\n#' anno_bottom(size = 0.2) +\n#' align_dendro(aes(color = branch), k = 3L) -\n#' # Modify the color scale of all plots in the bottom and the opposite\n#' # annotation, in this way, the `main` argument by default would be `TRUE`\n#' with_quad(scale_color_brewer(palette = \"Dark2\", name = \"Top and bottom\"))\n#'\n#' # When the `position` argument is manually set, the\n#' # default value of the `main` argument will be `FALSE`.\n#' ggheatmap(small_mat) +\n#' anno_left(size = 0.2) +\n#' align_dendro(aes(color = branch), k = 3L) +\n#' anno_top(size = 0.2) +\n#' align_dendro(aes(color = branch), k = 3L) +\n#' anno_bottom(size = 0.2) +\n#' align_dendro(aes(color = branch), k = 3L) -\n#' # Modify the background of all plots in the left and top annotation\n#' with_quad(theme(plot.background = element_rect(fill = \"red\")), \"tl\")\n#' @export\nwith_quad <- function(x, position = waiver(), main = NULL) {\n UseMethod(\"with_quad\")\n}\n\n#' @export\nwith_quad.default <- function(x, position = waiver(), main = NULL) {\n assert_layout_position(position)\n assert_bool(main, allow_null = TRUE)\n structure(\n list(\n object = x,\n object_name = paste(deparse(substitute(x)), collapse = \" \"),\n position = position, main = main\n ),\n class = \"ggalign_with_quad\"\n )\n}\n\n#' @export\nprint.ggalign_with_quad <- function(x, ...) {\n print(.subset2(x, \"object\"))\n invisible(x)\n}\n\n#' @export\nwith_quad.CraftBox <- function(x, position = waiver(), main = NULL) {\n cli_abort(sprintf(\"Cannot used with %s\", object_name(x)))\n}\n\n#' @export\nwith_quad.layout_title <- function(x, position = waiver(), main = NULL) {\n cli_abort(\"Cannot used with {.obj_type_friendly {x}}\")\n}\n\n#' @export\nwith_quad.layout_theme <- with_quad.layout_title\n\n#' @export\nwith_quad.layout_annotation <- with_quad.layout_title\n\n#' @export\nwith_quad.quad_active <- with_quad.layout_title\n\n#' @export\nwith_quad.quad_anno <- with_quad.layout_title\n\n#' @export\nwith_quad.stack_switch <- with_quad.layout_title\n\nquad_operated_context <- function(with, active, operator) {\n if (is.waive(ans <- .subset2(with, \"position\"))) {\n if (operator == \"-\") {\n # if wrap with `with_quad`\n # we determine the `context` from current actual active position\n if (is.null(active)) {\n ans <- NULL\n } else {\n ans <- c(active, opposite_pos(active))\n if (is.null(main <- .subset2(with, \"main\")) || main) {\n ans <- c(ans, list(NULL))\n }\n }\n } else if (operator == \"+\") {\n ans <- active\n if (!is.null(ans)) {\n if (is.null(main <- .subset2(with, \"main\")) || main) {\n ans <- c(ans, list(NULL))\n }\n }\n } else {\n cli_abort(\"Not implement for {operator}\")\n }\n } else if (!is.null(ans)) { # if set manually\n ans <- setup_pos(ans)\n if (!is.null(main <- .subset2(with, \"main\")) && main) {\n ans <- c(ans, list(NULL))\n }\n }\n ans\n}\n\n#' @importFrom ggplot2 ggplot_add\n#' @export\nggplot_add.ggalign_with_quad <- function(object, plot, object_name, ...) {\n object <- .subset2(object, \"object\")\n object_name <- .subset2(object, \"object_name\")\n ggplot_add(object, plot, object_name)\n}\n"], ["/ggalign/R/layout-chain-circle-.R", "#' Arrange plots in a circular layout\n#'\n#' @description\n#' `r lifecycle::badge('experimental')`\n#'\n#' If `limits` is provided, a continuous variable will be required and aligned\n#' in the direction specified (`circle_continuous`). Otherwise, a discrete\n#' variable will be required and aligned (`circle_discrete`).\n#'\n#' @param radial A [`coord_circle()`]/[`coord_radial()`][ggplot2::coord_radial]\n#' object that defines the global parameters for coordinate across all plots\n#' in the layout. The parameters `start`, `end`, `direction`, and `expand` will\n#' be inherited and applied uniformly to all plots within the layout. The\n#' parameters `theta` and `r.axis.inside` will always be ignored and will be set\n#' to `\"x\"` and `TRUE`, respectively, for all plots.\n#' @param direction A single string of `r oxford_or(c(\"inward\", \"outward\"))`,\n#' indicating the direction in which the plot is added.\n#' - `outward`: The plot is added from the inner to the outer.\n#' - `inward`: The plot is added from the outer to the inner.\n#' @inheritParams stack_layout\n#' @return A `CircleLayout` object.\n#' @examples\n#' set.seed(123)\n#'\n#' small_mat <- matrix(rnorm(56), nrow = 7)\n#' rownames(small_mat) <- paste0(\"row\", seq_len(nrow(small_mat)))\n#' colnames(small_mat) <- paste0(\"column\", seq_len(ncol(small_mat)))\n#'\n#' # circle_layout\n#' # same for circle_discrete()\n#' circle_layout(small_mat) +\n#' ggalign() +\n#' geom_tile(aes(y = .column_index, fill = value)) +\n#' scale_fill_viridis_c() +\n#' align_dendro(aes(color = branch), k = 3L) +\n#' scale_color_brewer(palette = \"Dark2\")\n#'\n#' # same for circle_continuous()\n#' circle_layout(mpg, limits = continuous_limits(c(3, 5))) +\n#' ggalign(mapping = aes(displ, hwy, colour = class)) +\n#' geom_point(size = 2) +\n#' ggalign(mapping = aes(displ, hwy, colour = class)) +\n#' geom_point(size = 2) &\n#' scale_color_brewer(palette = \"Dark2\") &\n#' theme_bw()\n#'\n#' @export\ncircle_layout <- function(data = NULL, ..., radial = NULL,\n direction = \"outward\", sector_spacing = NULL,\n limits = waiver(), theme = NULL,\n spacing_theta = deprecated()) {\n if (is.waive(limits)) {\n circle_discrete(\n data = data, ..., radial = radial,\n direction = direction, sector_spacing = sector_spacing,\n theme = theme, spacing_theta = spacing_theta\n )\n } else {\n circle_continuous(\n data = data, ..., radial = radial,\n direction = direction, theme = theme, limits = limits,\n spacing_theta = spacing_theta\n )\n }\n}\n\n############################################################\n#' @inheritParams facet_sector\n#' @examples\n#' # circle_discrete()\n#' # direction outward\n#' circle_discrete(small_mat) +\n#' align_dendro(aes(color = branch), k = 3L) +\n#' scale_color_brewer(palette = \"Dark2\") +\n#' ggalign() +\n#' geom_tile(aes(y = .column_index, fill = value)) +\n#' scale_fill_viridis_c()\n#'\n#' # direction inward\n#' circle_discrete(small_mat, direction = \"inward\") +\n#' ggalign() +\n#' geom_tile(aes(y = .column_index, fill = value)) +\n#' scale_fill_viridis_c() +\n#' align_dendro(aes(color = branch), k = 3L) +\n#' scale_color_brewer(palette = \"Dark2\")\n#'\n#' @export\n#' @rdname circle_layout\ncircle_discrete <- function(data = NULL, ..., radial = NULL,\n direction = \"outward\", sector_spacing = NULL,\n theme = NULL, spacing_theta = deprecated()) {\n UseMethod(\"circle_discrete\", data)\n}\n\n#' @export\ncircle_discrete.default <- function(data = NULL, ..., radial = NULL,\n direction = \"outward\",\n sector_spacing = NULL,\n theme = NULL,\n spacing_theta = deprecated()) {\n # the observations are rows, we use matrix to easily\n # reshape it into a long formated data frame for ggplot,\n # and we can easily determine the number of observations\n # from matrix\n data <- data %|w|% NULL\n data <- fortify_matrix(data = data, ...)\n schemes <- default_schemes()\n if (!is.null(data) && !is.function(data)) {\n # if we have provided data, we initialize the `nobs`\n nobs <- vec_size(data)\n } else {\n nobs <- NULL\n }\n new_circle_layout(\n data = data,\n design = discrete_design(nobs = nobs),\n radial = radial, direction = direction, sector_spacing = sector_spacing,\n schemes = schemes, theme = theme, spacing_theta = spacing_theta\n )\n}\n\n#' @export\ncircle_discrete.function <- function(data = NULL, ...) {\n cli_abort(paste0(\n \"{.arg data} must be a {.cls matrix}, \",\n \"or an object coercible by {.fn fortify_matrix}, or a valid \",\n \"{.cls matrix}-like object coercible by {.fn as.matrix}\"\n ))\n}\n\n#' @export\ncircle_discrete.formula <- circle_discrete.function\n\n################################################################\n#' @examples\n#' # circle_continuous()\n#' circle_continuous(mpg, limits = continuous_limits(c(3, 5))) +\n#' ggalign(mapping = aes(displ, hwy, colour = class)) +\n#' geom_point(size = 2) +\n#' ggalign(mapping = aes(displ, hwy, colour = class)) +\n#' geom_point(size = 2) &\n#' scale_color_brewer(palette = \"Dark2\") &\n#' theme_bw()\n#' @export\n#' @rdname circle_layout\ncircle_continuous <- function(data = NULL, ..., radial = NULL,\n direction = \"outward\", sector_spacing = NULL,\n limits = NULL, theme = NULL,\n spacing_theta = deprecated()) {\n UseMethod(\"circle_continuous\", data)\n}\n\n#' @export\ncircle_continuous.default <- function(data = NULL, ..., radial = NULL,\n direction = \"outward\",\n sector_spacing = NULL,\n limits = NULL, theme = NULL,\n spacing_theta = deprecated()) {\n assert_limits(limits)\n data <- data %|w|% NULL\n data <- fortify_data_frame(data = data, ...)\n schemes <- default_schemes()\n new_circle_layout(\n data = data, design = limits,\n radial = radial, direction = direction, sector_spacing = sector_spacing,\n schemes = schemes, theme = theme, spacing_theta = spacing_theta\n )\n}\n\n#' @export\ncircle_continuous.function <- function(data = NULL, ...) {\n cli_abort(paste0(\n \"{.arg data} must be a {.cls data.frame}, \",\n \"or an object coercible by {.fn fortify_data_frame}, or a valid \",\n \"{.cls data.frame}-like object coercible by {.fn as.data.frame}\"\n ))\n}\n\n#' @export\ncircle_continuous.formula <- circle_continuous.function\n\n#' @importFrom methods new\nnew_circle_layout <- function(data, design, radial, direction,\n sector_spacing = NULL, schemes = NULL,\n theme = NULL, name = NULL,\n spacing_theta = deprecated(),\n call = caller_call()) {\n if (!is.null(theme)) assert_s3_class(theme, \"theme\", call = call)\n if (!is.null(radial) && !inherits(radial, c(\"CoordRadial\"))) {\n cli_abort(\"{.arg radial} must be created with {.fn coord_circle}\",\n call = call\n )\n }\n if (!is.null(radial) && abs(diff(radial$arc)) < pi / 2L) {\n cli_abort(\n \"Cannot create circle of acute angle < 90 in {.arg radial}\",\n call = call\n )\n }\n direction <- arg_match0(direction, c(\"inward\", \"outward\"))\n if (is.null(name)) {\n if (is_continuous_design(design)) {\n name <- \"circle_continuous\"\n } else {\n name <- \"circle_discrete\"\n }\n }\n if (lifecycle::is_present(spacing_theta)) {\n lifecycle::deprecate_warn(\n \"1.0.2\",\n \"facet_sector(spacing_theta = )\",\n \"facet_sector(sector_spacing = )\"\n )\n if (is.null(sector_spacing)) sector_spacing <- spacing_theta\n }\n new(\n \"CircleLayout\",\n name = name, data = data,\n schemes = schemes, # used by the layout\n design = design,\n sector_spacing = sector_spacing,\n theme = theme,\n radial = radial, direction = direction\n )\n}\n\n############################################################\n# Used to place multiple objects in one axis\n#' @importFrom grid unit\n#' @importFrom ggplot2 waiver\n#' @keywords internal\n#' @include layout-chain-.R\nmethods::setClass(\"CircleLayout\",\n contains = \"ChainLayout\",\n list(radial = \"ANY\", sector_spacing = \"ANY\", direction = \"character\")\n)\n"], ["/ggalign/R/craftbox-.R", "# Use S4 to override the double dispatch problem of ggplot2\n# And it's easy to convert a S4 Class to a S7 Class\nmethods::setClass(\n \"CraftBox\",\n list(\n plot = \"ANY\", # To avoid modify in place, we put plot in a slot\n active = \"ANY\",\n size = \"ANY\",\n schemes = \"ANY\",\n craftsman = \"ANY\" # `Craftsman` object\n )\n)\n\n#' Show `CraftBox` information\n#' @param object A `CraftBox` object.\n#' @return The input invisiblely.\n#' @keywords internal\nmethods::setMethod(\"show\", \"CraftBox\", function(object) {\n print(object)\n})\n\n#' @importFrom methods new\nnew_craftbox <- function(craftsman = NULL, ...,\n plot = NULL, active = NULL, size = NULL,\n schemes = NULL, call = caller_call()) {\n assert_active(active, allow_null = FALSE, call = call)\n if (is.null(size)) {\n size <- unit(NA, \"null\")\n } else {\n size <- check_size(size, call = call)\n }\n new(\n \"CraftBox\",\n # `call`: used to provide error message\n craftsman = ggproto(NULL, craftsman %||% Craftsman, ..., call = call),\n schemes = schemes %||% default_schemes(),\n plot = plot, active = active, size = size\n )\n}\n\n#' @export\nprint.CraftBox <- function(x, ...) {\n cat(x@craftsman$summary(x@plot), sep = \"\\n\")\n invisible(x)\n}\n\n#' @export\nplot.CraftBox <- function(x, ...) {\n cli_abort(sprintf(\"Cannot plot %s object directly\", object_name(x)))\n}\n\n#' @importFrom grid grid.draw\n#' @exportS3Method\ngrid.draw.CraftBox <- plot.CraftBox\n\n#' Add custom objects to ggalign plot\n#' @keywords internal\nmethods::setMethod(\"+\", c(\"CraftBox\", \"ANY\"), function(e1, e2) {\n if (missing(e2)) {\n cli_abort(c(\n \"Cannot use {.code {.Generic}} with a single argument.\",\n \"i\" = \"Did you accidentally put {.code {.Generic}} on a new line?\"\n ))\n }\n\n if (is.null(e2)) return(e1) # styler: off\n\n # Get the name of what was passed in as e2, and pass along so that it\n # can be displayed in error messages\n e2name <- paste(deparse(substitute(e2)), collapse = \" \")\n switch(.Generic, # nolint\n `+` = craftbox_add(e2, e1, e2name),\n stop_incompatible_op(.Generic, e1, e2)\n )\n})\n\n#' @importFrom methods is\nis_craftbox <- function(x) is(x, \"CraftBox\")\n\nis_cross_plot <- function(x) is_craftbox(x) && is_cross(x@craftsman)\n\nis_cross <- function(x) inherits(x, \"CraftCross\")\n\n#######################################################\n#' @importFrom ggplot2 ggproto\nCraftsman <- ggproto(\"Craftsman\",\n call = NULL,\n\n # following fields will be added when added to the layout\n in_linear = NULL,\n layout_name = NULL,\n direction = NULL,\n position = NULL, # for stack_layout() in quad_layout()\n labels = NULL,\n\n # A single boolean value indicates whether we should set facet and coord\n free_facet = FALSE,\n free_coord = FALSE,\n free_limits = FALSE,\n\n # we always prevent user from modifying the object in `$build_plot()` and\n # `$finish_plot()` methods\n locked = TRUE,\n lock = function(self) {\n assign(\"locked\", value = TRUE, envir = self)\n },\n unlock = function(self) {\n assign(\"locked\", value = FALSE, envir = self)\n },\n\n ############################################################\n # when added to the `Layout` object, will call following methods\n\n # we usually, define the `nobs` in `interact_layout`, since we can\n # act with the layout data in `interact_layout` method\n interact_layout = function(self, layout) layout,\n\n # we define the `panel` and `index` method in `setup_design` method\n setup_design = function(self, design) design,\n setup_plot = function(self, plot) plot,\n\n ##############################################################\n # Don't change the facet and coord in following methods\n build_plot = function(self, plot, design, extra_design = NULL,\n previous_design = NULL) {\n plot\n },\n finish_plot = function(self, plot, schemes, theme) {\n plot <- plot_add_schemes(plot, schemes)\n ggremove_margin(plot, self$direction) + theme_recycle()\n },\n\n # utils method to print the object, should return a character vector\n summary = function(self, plot) {\n cls <- class(self)\n cls <- cls[seq_len(which(cls == \"Craftsman\"))]\n sprintf(\"\", paste(cls, collapse = \" \"))\n }\n)\n\n# Used to lock the `Craftsman` object\n#' @export\n`$<-.Craftsman` <- function(x, name, value) {\n if (x$locked) {\n cli_abort(c(\n sprintf(\"Cannot modify %s\", object_name(x)),\n i = sprintf(\"%s is locked\", object_name(x))\n ), call = x$call)\n }\n NextMethod()\n}\n\n#################################################################\ncraftbox_add <- function(object, craftbox, object_name) {\n if (is.null(craftbox@plot)) {\n cli_abort(c(\n sprintf(\n \"Cannot add {.var {object_name}} to %s\",\n object_name(craftbox)\n ),\n i = sprintf(\"no plot found for %s\", object_name(craftbox))\n ))\n }\n UseMethod(\"craftbox_add\")\n}\n\n#' @importFrom ggplot2 ggplot_add\n#' @export\ncraftbox_add.default <- function(object, craftbox, object_name) {\n craftbox@plot <- ggplot_add(\n object,\n ggfun(\"plot_clone\")(craftbox@plot),\n object_name\n )\n craftbox\n}\n\n#' @export\ncraftbox_add.ggalign_scheme <- function(object, craftbox, object_name) {\n name <- ggalign_scheme_name(object)\n craftbox@schemes[name] <- list(update_scheme(\n object, .subset2(craftbox@schemes, name), object_name\n ))\n craftbox\n}\n\n######################################################################\nplot_build <- function(align, ..., schemes, theme) {\n plot <- align$build_plot(plot@plot, ...)\n align$finish_plot(plot, schemes, theme)\n}\n"], ["/ggalign/R/fortify-matrix-maftools.R", "#' Build a Matrix for OncoPrint\n#'\n#' @description\n#' Convert `MAF` object to a matrix:\n#' - `fortify_matrix.MAF`: Extract genomic alterations for genes.\n#' - `fortify_matrix.MAF_pathways`: Extract genomic alterations for pathways.\n#' [`tune.MAF()`] helps convert `MAF` object to a `MAF_pathways` object.\n#'\n#' @inheritParams rlang::args_dots_empty\n#' @param data A [`MAF`][maftools::read.maf] object.\n#' @param genes An atomic character defines the genes to draw.\n#' @param n_top A single number indicates how many top genes to be drawn.\n#' @param remove_empty_genes A single boolean value indicats whether to drop\n#' genes without any genomic alterations.\n#' @param remove_empty_samples A single boolean value indicats whether to drop\n#' samples without any genomic alterations.\n#' @param collapse_vars A single boolean value indicating whether to collapse\n#' multiple alterations in the same sample and gene into a single value\n#' `\"Multi_Hit\"`. Alternatively, you can provide a single string indicates the\n#' collapsed values.\n#' @param use_syn A single boolean value indicates whether to include synonymous\n#' variants when Classifies SNPs into transitions and transversions.\n#' @param missing_genes A string, either `\"error\"` or `\"remove\"`, specifying the\n#' action for handling missing genes.\n#' @inheritParams fortify_matrix\n#' @section ggalign attributes:\n#' For `fortify_matrix.MAF`:\n#' - `gene_summary`: A data frame of gene summary informations. See\n#' `maftools::getGeneSummary()` for details.\n#' - `sample_summary`: A data frame of sample summary informations. See\n#' `maftools::getSampleSummary()` for details.\n#' - `sample_anno`: A data frame of sample clinical informations. See\n#' `maftools::getClinicalData()` for details.\n#' - `variant_weights`: A data frame of variant weights. Each gene in a sample\n#' is assigned a total weight of `1`. When multiple variants occur in the\n#' same gene-sample pair, the weight for each variant reflects its proportion\n#' of the total.\n#' - `n_genes`: Total number of genes.\n#' - `n_samples`: Total number of samples.\n#' - `titv`: A list of data frame with Transitions and Transversions\n#' summary. See `maftools::titv()` for details.\n#'\n#' The levels of `Variant_Classification` will be stored in [`ggalign_lvls()`].\n#' If they do not exist, alphabetical ordering will be used.\n#'\n#' @family fortify_matrix\n#' @importFrom utils getFromNamespace\n#' @importFrom rlang is_string\n#' @export\nfortify_matrix.MAF <- function(data, ..., genes = NULL, n_top = NULL,\n remove_empty_genes = TRUE,\n remove_empty_samples = TRUE,\n collapse_vars = TRUE, use_syn = TRUE,\n missing_genes = \"error\",\n data_arg = NULL, call = NULL) {\n call <- call %||% current_call()\n rlang::check_dots_empty(call = call)\n rlang::check_installed(\n \"maftools\", \"to make alterations matrix from `MAF` object\"\n )\n # prepare arguments\n missing_genes <- arg_match0(\n missing_genes, c(\"error\", \"remove\"),\n error_call = call\n )\n if (isTRUE(collapse_vars)) {\n collapse_vars <- \"Multi_Hit\"\n } else if (isFALSE(collapse_vars)) {\n collapse_vars <- NULL\n } else if (is_string(collapse_vars)) {\n if (collapse_vars == \"\") {\n cli_abort(\"{.arg collapse_vars} cannot be an empty string\",\n call = call\n )\n }\n } else {\n cli_abort(\n paste(\n \"{.arg collapse_vars} must be a single boolean value or a string,\",\n \"but you provide {.obj_type_friendly {collapse_vars}}\"\n ),\n call = call\n )\n }\n\n getSampleSummary <- getExportedValue(\"maftools\", \"getSampleSummary\")\n getGeneSummary <- getExportedValue(\"maftools\", \"getGeneSummary\")\n getClinicalData <- getExportedValue(\"maftools\", \"getClinicalData\")\n\n # if `maftools` is installed, `data.table` must have been installed\n # No need to check if `data.table` is installed\n dcast <- getExportedValue(\"data.table\", \"dcast\")\n setDT <- getExportedValue(\"data.table\", \"setDT\")\n setDF <- getExportedValue(\"data.table\", \"setDF\")\n\n sample_summary <- new_data_frame(getSampleSummary(data))\n gene_summary <- new_data_frame(getGeneSummary(data))\n sample_anno <- new_data_frame(getClinicalData(data))\n\n titv <- getExportedValue(\"maftools\", \"titv\")\n titv <- titv(data, useSyn = use_syn, plot = FALSE)\n titv <- lapply(titv, new_data_frame)\n\n # we transform the data into a normal data frame\n data <- new_data_frame(data@data)[\n c(\"Tumor_Sample_Barcode\", \"Hugo_Symbol\", \"Variant_Classification\")\n ]\n n_genes <- vec_unique_count(.subset2(data, \"Hugo_Symbol\"))\n n_samples <- vec_unique_count(.subset2(data, \"Tumor_Sample_Barcode\"))\n\n # filter by genes --------------------------------------\n if (!is.null(genes)) {\n # reorder the gene annotation based on the provided genes\n genes <- vec_cast(genes, character())\n if (vec_any_missing(genes)) {\n cli_abort(\n \"{.arg genes} cannot contain missing values\",\n call = call\n )\n }\n if (vec_duplicate_any(genes)) {\n cli_abort(\n \"{.arg genes} cannot contain duplicated values\",\n call = call\n )\n }\n if (identical(missing_genes, \"remove\")) {\n genes <- genes[genes %in% .subset2(gene_summary, \"Hugo_Symbol\")]\n }\n if (is_empty(genes)) {\n cli_abort(\n \"No {.arg genes} remain after removing missing genes\",\n call = call\n )\n }\n gene_summary <- vec_slice(\n gene_summary,\n vec_as_location(\n genes,\n n = vec_size(gene_summary),\n names = .subset2(gene_summary, \"Hugo_Symbol\"),\n missing = \"error\"\n )\n )\n }\n genes <- .subset2(gene_summary, \"Hugo_Symbol\")\n if (!is.null(n_top)) {\n n_top <- min(n_top, vec_size(genes))\n index <- vec_slice(\n order(gene_summary$AlteredSamples, decreasing = TRUE),\n seq_len(n_top)\n )\n index <- sort(index) # don't change the order, we do only subset\n genes <- vec_slice(genes, index)\n gene_summary <- vec_slice(gene_summary, index)\n }\n data <- vec_slice(data, .subset2(data, \"Hugo_Symbol\") %in% genes)\n\n # Group variants --------------------------------------\n indices <- vec_group_loc(data[c(\"Tumor_Sample_Barcode\", \"Hugo_Symbol\")])\n vars <- .subset2(data, \"Variant_Classification\")\n lvls <- levels(vars) %||% sort(vec_unique(vars))\n nlvls <- vec_size(lvls)\n var_list <- vec_chop(as.character(vars), indices = .subset2(indices, \"loc\"))\n\n # calcualte the variant weights -----------------------\n variant_weights <- lapply(var_list, function(var) {\n o <- numeric(nlvls)\n names(o) <- lvls\n counts <- vec_count(var)\n o[.subset2(counts, \"key\")] <- .subset2(counts, \"count\") /\n sum(.subset2(counts, \"count\"))\n o\n })\n variant_weights <- inject(rbind(!!!variant_weights))\n gene_indices <- vec_group_loc(\n .subset2(.subset2(indices, \"key\"), \"Hugo_Symbol\")\n )\n variant_weights <- lapply(\n vec_chop(variant_weights, indices = .subset2(gene_indices, \"loc\")),\n colSums\n )\n variant_weights <- vec_cbind(\n Hugo_Symbol = .subset2(gene_indices, \"key\"),\n vec_rbind(!!!variant_weights)\n )\n\n # collapse the vars ------------------------------------\n if (is.null(collapse_vars)) {\n vars <- vapply(var_list, function(var) {\n if (length(var) > 1L) {\n paste(var, collapse = \";\")\n } else {\n var\n }\n }, character(1L), USE.NAMES = FALSE)\n } else {\n vars <- vapply(var_list, function(var) {\n if (vec_unique_count(var) > 1L) {\n collapse_vars\n } else if (length(var) > 1L) {\n paste(var, collapse = \";\")\n } else {\n var\n }\n }, character(1L), USE.NAMES = FALSE)\n if (any(vars == collapse_vars)) lvls <- c(lvls, collapse_vars)\n }\n ans <- vec_cbind(\n .subset2(indices, \"key\"),\n new_data_frame(list(Variant_Classification = vars))\n )\n\n # restore all samples, this will introduce `NA` in `Hugo_Symbol`\n ans <- right_join(ans, data_frame0(\n Tumor_Sample_Barcode = vec_unique(sample_summary$Tumor_Sample_Barcode)\n ))\n setDT(ans)\n ans <- dcast(ans, Hugo_Symbol ~ Tumor_Sample_Barcode,\n value.var = \"Variant_Classification\"\n )\n setDF(ans)\n ans <- vec_slice(ans, !is.na(.subset2(ans, \"Hugo_Symbol\")))\n\n # convert data into a matrix\n if (remove_empty_genes) {\n # convert to a matrix\n ans <- as.matrix(column_to_rownames(ans, \"Hugo_Symbol\"))\n\n # reorder the rows based on the `genes` specified\n index <- match(genes, rownames(ans))\n ans <- vec_slice(ans, index[!is.na(index)])\n } else {\n # restore all genes\n ans <- right_join(ans, data_frame0(Hugo_Symbol = genes))\n\n # convert to a matrix\n ans <- as.matrix(column_to_rownames(ans, \"Hugo_Symbol\"))\n\n # reorder the rows based on the `genes` specified\n ans <- vec_slice(ans, genes)\n }\n\n # filter samples when necessary\n if (remove_empty_samples) {\n keep <- colSums(!is.na(ans)) > 0L\n ans <- ans[, keep, drop = FALSE]\n }\n\n # reorder the rows based on the gene ordering\n gene_summary <- vec_slice(\n gene_summary,\n vec_as_location(\n rownames(ans),\n n = vec_size(gene_summary),\n names = vec_cast(gene_summary$Hugo_Symbol, character())\n )\n )\n variant_weights <- vec_slice(\n variant_weights,\n vec_as_location(\n rownames(ans),\n n = vec_size(variant_weights),\n names = variant_weights$Hugo_Symbol\n )\n )\n\n # reorder columns based on the sample ordering\n sample_summary <- vec_slice(\n sample_summary,\n vec_as_location(\n colnames(ans),\n n = vec_size(sample_summary),\n names = vec_cast(sample_summary$Tumor_Sample_Barcode, character())\n )\n )\n sample_anno <- vec_slice(\n sample_anno,\n vec_as_location(\n colnames(ans),\n n = vec_size(sample_anno),\n names = sample_anno$Tumor_Sample_Barcode\n )\n )\n titv <- lapply(titv, function(data) {\n data <- left_join(\n data_frame0(Tumor_Sample_Barcode = colnames(ans)),\n data\n )\n vec_slice(data, vec_as_location(\n colnames(ans),\n n = vec_size(data),\n names = vec_cast(data$Tumor_Sample_Barcode, character())\n ))\n })\n ggalign_data_set(ans,\n sample_summary = sample_summary,\n gene_summary = gene_summary,\n sample_anno = sample_anno,\n variant_weights = variant_weights,\n n_samples = n_samples, n_genes = n_genes, titv = titv,\n .lvls = lvls\n )\n}\n\n#' Convert the shape of a MAF for fortify method\n#'\n#' @param data A [`MAF`][maftools::read.maf] object.\n#' @param shape Not used currently.\n#' @seealso [`fortify_matrix.MAF_pathways()`]\n#' @family tune\n#' @export\ntune.MAF <- function(data, shape = NULL) {\n if (!is.null(shape)) {\n cli_abort(\"{.arg shape} cannot be used currently for {.cls MAF} object\")\n }\n new_tune(data, class = \"MAF_pathways\")\n}\n\n#' @param pathdb A string of `r oxford_or(c(\"smgbp\", \"sigpw\"))`, or a named list\n#' of genes to define the pathways.\n#' @param remove_empty_pathways A single boolean value indicats whether to drop\n#' pathways without any genomic alterations.\n#' @section ggalign attributes:\n#' For `fortify_matrix.MAF_pathways`:\n#' - `gene_list`: the pathway contents.\n#' - `pathway_summary`: pathway summary informations. See\n#' `maftools::pathways()` for details.\n#' - `sample_summary`: sample summary informations. See\n#' `maftools::getSampleSummary()` for details.\n#' - `sample_anno`: sample clinical informations. See\n#' `maftools::getClinicalData()` for details.\n#' @export\n#' @rdname fortify_matrix.MAF\nfortify_matrix.MAF_pathways <- function(data, ..., pathdb = \"smgbp\",\n remove_empty_pathways = TRUE,\n remove_empty_samples = TRUE,\n data_arg = NULL,\n call = NULL) {\n call <- call %||% current_call()\n rlang::check_dots_empty(call = call)\n rlang::check_installed(\n \"maftools\", \"to make alterations matrix from `MAF` object\"\n )\n get_pw_summary <- getFromNamespace(\"get_pw_summary\", \"maftools\")\n maf <- tune_data(data)\n if (rlang::is_string(pathdb)) {\n pathdb <- arg_match0(pathdb, c(\"sigpw\", \"smgbp\"))\n pathway_summary <- get_pw_summary(maf, pathways = pathdb)\n } else if (is.data.frame(pathdb)) {\n cli_abort(\"{.arg pathdb} cannot be a data frame\", call = call)\n } else if (is.list(pathdb)) {\n if (!rlang::is_named(pathdb)) {\n cli_abort(sprintf(\n \"{.arg pathdb} must be a named list of a single string of %s\",\n oxford_or(c(\"sigpw\", \"smgbp\"))\n ), call = call)\n }\n pathdb <- data_frame0(\n Pathway = factor(\n vec_rep_each(names(pathdb), lengths(pathdb)),\n names(pathdb)\n ),\n Gene = unlist(pathdb, FALSE, FALSE)\n )\n pathdb <- vec_unique(pathdb)\n pathway_summary <- get_pw_summary(maf, pathways = pathdb)\n }\n getSampleSummary <- getExportedValue(\"maftools\", \"getSampleSummary\")\n getClinicalData <- getExportedValue(\"maftools\", \"getClinicalData\")\n sample_summary <- new_data_frame(getSampleSummary(maf))\n sample_anno <- new_data_frame(getClinicalData(maf))\n\n gene_list <- attr(pathway_summary, \"genes\") # a list of genes\n ans <- new_data_frame(maf@data)[\n c(\"Tumor_Sample_Barcode\", \"Hugo_Symbol\", \"Variant_Classification\")\n ]\n full_genes <- unlist(gene_list, FALSE, FALSE)\n ans$pathways <- vec_slice(\n vec_set_names(\n vec_rep_each(names(gene_list), lengths(gene_list)),\n full_genes\n ),\n if_else(ans$Hugo_Symbol %in% full_genes,\n ans$Hugo_Symbol, NA_character_\n )\n )\n ans$Alt <- if_else(is.na(.subset2(ans, \"pathways\")), NA_character_, \"Alt\")\n ans <- vec_unique(ans[c(\"Tumor_Sample_Barcode\", \"pathways\", \"Alt\")])\n\n # if `maftools` is installed, `data.table` must have been installed\n # No need to check if `data.table` is installed\n dcast <- getExportedValue(\"data.table\", \"dcast\")\n setDT <- getExportedValue(\"data.table\", \"setDT\")\n setDF <- getExportedValue(\"data.table\", \"setDF\")\n setDT(ans)\n ans <- dcast(ans, pathways ~ Tumor_Sample_Barcode,\n value.var = \"Alt\", fill = NA_character_\n )\n setDF(ans)\n ans <- vec_slice(ans, !is.na(.subset2(ans, \"pathways\")))\n\n # convert data into a matrix\n if (remove_empty_pathways) {\n # convert to a matrix\n ans <- as.matrix(column_to_rownames(ans, \"pathways\"))\n\n # reorder the rows based on the `pathways` specified\n index <- match(names(gene_list), rownames(ans))\n gene_list <- gene_list[!is.na(index)]\n ans <- vec_slice(ans, index[!is.na(index)])\n } else {\n # restore all pathways\n ans <- right_join(ans, data_frame0(pathways = names(gene_list)))\n\n # convert to a matrix\n ans <- as.matrix(column_to_rownames(ans, \"pathways\"))\n\n # reorder the rows based on the `pathways` specified\n ans <- vec_slice(ans, names(gene_list))\n }\n\n # filter samples when necessary\n if (remove_empty_samples) {\n keep <- colSums(!is.na(ans)) > 0L\n ans <- ans[, keep, drop = FALSE]\n }\n\n # reorder the rows based on the pathways ordering\n setDF(pathway_summary)\n pathway_summary <- vec_slice(\n pathway_summary,\n vec_as_location(\n rownames(ans),\n n = vec_size(pathway_summary),\n names = vec_cast(pathway_summary$Pathway, character())\n )\n )\n\n # reorder columns based on the sample ordering\n sample_summary <- vec_slice(\n sample_summary,\n vec_as_location(\n colnames(ans),\n n = vec_size(sample_summary),\n names = vec_cast(sample_summary$Tumor_Sample_Barcode, character())\n )\n )\n sample_anno <- vec_slice(\n sample_anno,\n vec_as_location(\n colnames(ans),\n n = vec_size(sample_anno),\n names = sample_anno$Tumor_Sample_Barcode\n )\n )\n ggalign_data_set(ans,\n gene_list = gene_list,\n pathway_summary = pathway_summary,\n sample_summary = sample_summary,\n sample_anno = sample_anno\n )\n}\n\n#' Build a matrix from a maftools object\n#'\n#' @inheritParams rlang::args_dots_empty\n#' @param data A [`GISTIC`][maftools::readGistic] object.\n#' @param n_top A single number indicates how many top bands to be drawn.\n#' @param bands An atomic character defines the bands to draw.\n#' @param ignored_bands An atomic character defines the bands to be ignored.\n#' @param sample_anno A data frame of sample clinical features to be added.\n#' @param remove_empty_samples A single boolean value indicating whether to drop\n#' samples without any genomic alterations.\n#' @inheritParams fortify_matrix\n#' @section ggalign attributes:\n#' - `sample_anno`: sample clinical informations provided in `sample_anno`.\n#' - `sample_summary`: sample copy number summary informations. See\n#' `data@@cnv.summary` for details.\n#' - `cytoband_summary`: cytoband summary informations. See\n#' `data@@cytoband.summary` for details.\n#' - `gene_summary`: gene summary informations. See\n#' `data@@gene.summary` for details.\n#' - `summary`: A data frame of summary information. See `data@@summary` for\n#' details.\n#' @family fortify_matrix\n#' @export\nfortify_matrix.GISTIC <- function(data, ..., n_top = NULL, bands = NULL,\n ignored_bands = NULL, sample_anno = NULL,\n remove_empty_samples = TRUE,\n data_arg = NULL,\n call = NULL) {\n call <- call %||% current_call()\n rlang::check_dots_empty(call = call)\n rlang::check_installed(\n \"maftools\",\n \"to make CNV matrix from `GISTIC` object\"\n )\n assert_number_whole(n_top,\n allow_null = TRUE,\n call = call\n )\n assert_character(bands,\n allow_null = TRUE,\n call = call\n )\n assert_character(ignored_bands,\n allow_null = TRUE,\n call = call\n )\n assert_s3_class(sample_anno, \"data.frame\",\n allow_null = TRUE,\n call = call\n )\n assert_bool(remove_empty_samples,\n call = call\n )\n cn_mat <- data@cnMatrix\n if (is.null(bands)) {\n bands <- rownames(cn_mat)\n } else {\n bands <- intersect(bands, rownames(cn_mat))\n }\n if (!is.null(ignored_bands)) {\n bands <- setdiff(bands, ignored_bands)\n }\n if (!is.null(bands)) {\n cn_mat <- vec_slice(cn_mat, rownames(cn_mat) %in% bands)\n }\n if (!is.null(n_top)) {\n cn_mat <- vec_slice(cn_mat, seq_len(min(n_top, nrow(cn_mat))))\n }\n if (remove_empty_samples) {\n keep <- colSums(cn_mat != \"\") > 0L\n cn_mat <- cn_mat[, keep, drop = FALSE]\n }\n if (!is.null(sample_anno)) {\n loc <- vec_locate_matches(\n colnames(cn_mat),\n .subset2(sample_anno, \"Tumor_Sample_Barcode\") %||%\n .subset2(sample_anno, 1L),\n relationship = \"one-to-one\",\n needles_arg = \"data\",\n haystack_arg = \"sample_anno\",\n error_call = call\n )\n sample_anno <- vec_slice(sample_anno, .subset2(loc, \"haystack\"))\n }\n sample_summary <- new_data_frame(data@cnv.summary)\n sample_summary <- vec_slice(\n sample_summary,\n vec_as_location(\n colnames(cn_mat),\n n = vec_size(sample_summary),\n names = vec_cast(sample_summary$Tumor_Sample_Barcode, character())\n )\n )\n gene_summary <- new_data_frame(data@gene.summary)\n cytoband_sumamry <- new_data_frame(data@cytoband.summary)\n cytoband_sumamry <- vec_slice(\n cytoband_sumamry,\n vec_as_location(\n rownames(cn_mat),\n n = vec_size(cytoband_sumamry),\n names = vec_cast(cytoband_sumamry$Unique_Name, character())\n )\n )\n ggalign_data_set(cn_mat,\n sample_anno = sample_anno,\n sample_summary = sample_summary,\n cytoband_sumamry = cytoband_sumamry,\n gene_summary = gene_summary,\n sumamry = data@summary\n )\n}\n"], ["/ggalign/R/layout-quad-.R", "#' Arrange plots in the quad-side of a main plot\n#'\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' This function arranges plots around the quad-sides of a main plot, aligning\n#' both horizontal and vertical axes, and can handle either discrete or\n#' continuous variables.\n#'\n#' - If `xlim` is provided, a continuous variable will be required and aligned\n#' in the vertical direction. Otherwise, a discrete variable will be required\n#' and aligned.\n#' - If `ylim` is provided, a continuous variable will be required and aligned\n#' in the horizontal direction. Otherwise, a discrete variable will be\n#' required and aligned.\n#'\n#' The `quad_discrete` is a special case where both `xlim` and `ylim` are not\n#' provided.\n#'\n#' The `quad_continuous` is a special case where both `xlim` and `ylim` are\n#' provided.\n#'\n#' For historical reasons, the following aliases are available:\n#' - `quad_alignh`: Align discrete variables in the horizontal direction and\n#' continuous variables in vertical direction.\n#' - `quad_alignv`: Align discrete variables in the vertical direction and\n#' continuous variables in horizontal direction.\n#' - `quad_alignb` is an alias for `quad_discrete`.\n#' - `quad_free` is an alias for `quad_continuous`.\n#'\n#' @param data `r rd_layout_data()`. By default, this will attempt\n#' to inherit from the parent layout.\n#'\n#' If both `xlim` and `ylim` are provided, a `data frame` is required, and\n#' [`fortify_data_frame()`] will be used to convert the data to a data frame.\n#' When inherited by an annotation stack, no transposition will be applied.\n#'\n#' Otherwise, a `matrix` is required, and [`fortify_matrix()`] will be used to\n#' convert the data to a matrix. When inherited by the column annotation\n#' stack, the data will be transposed.\n#' @param mapping Default list of aesthetic mappings to use for main plot in the\n#' layout. If not specified, must be supplied in each layer added to the main\n#' plot.\n#' @param xlim,ylim A [`continuous_limits()`] object specifying the left/lower\n#' limit and the right/upper limit of the scale. Used to align the continuous\n#' axis.\n#' @param width,height The relative width/height of the main plot, can be a\n#' [`unit`][grid::unit] object.\n#' @inheritParams stack_layout\n#' @inheritParams align\n#' @return A `QuadLayout` object.\n#' @section ggplot2 specification:\n#' If either `xlim` or `ylim` is not provided, the data input will be converted\n#' to a matrix using [`fortify_matrix()`], and the data in the underlying main\n#' plot will contain the following columns:\n#'\n#' - `.panel_x` and `.panel_y`: the column and row panel groups.\n#'\n#' - `.x` and `.y`: an integer index of `x` and `y` coordinates\n#'\n#' - `.discrete_x` and `.discrete_y`: a factor of the data labels (only\n#' applicable when `.row_names` and `.column_names` exists).\n#'\n#' - `.row_names` and `.column_names`: A character of the row and column names\n#' of the original matrix (only applicable when names exist).\n#'\n#' - `.row_index` and `.column_index`: the row and column index of the original\n#' matrix.\n#'\n#' - `value`: the actual matrix value.\n#'\n#' Otherwise, the data input will be used for the main plot.\n#'\n#' @export\nquad_layout <- function(data = waiver(), mapping = aes(),\n xlim = waiver(), ylim = waiver(),\n ...,\n theme = NULL, active = NULL,\n width = NA, height = NA) {\n if (is.waive(xlim) && is.waive(ylim)) {\n quad_discrete(\n data = data, mapping = mapping,\n ..., active = active, theme = theme,\n width = width, height = height\n )\n } else if (!is.waive(xlim) && !is.waive(ylim)) {\n quad_continuous(\n data = data, mapping = mapping, xlim = xlim, ylim = ylim,\n ..., active = active, theme = theme,\n width = width, height = height\n )\n } else {\n data <- fortify_matrix(data = data, ...)\n new_quad_layout(\n name = \"quad_layout\",\n data = data, ylim = ylim, xlim = xlim,\n mapping = mapping, active = active, theme = theme,\n width = width, height = height\n )\n }\n}\n\n#' @export\n#' @rdname quad_layout\nquad_alignh <- function(..., ylim = waiver()) {\n quad_layout(..., xlim = NULL, ylim = ylim)\n}\n\n#' @export\n#' @rdname quad_layout\nquad_alignv <- function(..., xlim = waiver()) {\n quad_layout(..., xlim = xlim, ylim = NULL)\n}\n\n##########################################################\n#' @export\n#' @rdname quad_layout\nquad_discrete <- function(data = waiver(), mapping = aes(),\n ...,\n theme = NULL, active = NULL,\n width = NA, height = NA) {\n UseMethod(\"quad_discrete\")\n}\n\n#' @export\n#' @rdname quad_layout\n#' @usage NULL\nquad_alignb <- quad_discrete\n\n#' @export\nquad_discrete.default <- function(data = waiver(), mapping = aes(),\n ...,\n theme = NULL, active = NULL,\n width = NA, height = NA) {\n data <- fortify_matrix(data = data, ...)\n new_quad_layout(\n name = \"quad_discrete\", data = data, xlim = waiver(), ylim = waiver(),\n mapping = mapping, active = active, theme = theme,\n width = width, height = height\n )\n}\n\n#' @export\nquad_discrete.uneval <- function(data, ...) {\n cli_abort(c(\n \"{.arg data} cannot be {.obj_type_friendly {data}}\",\n \"i\" = \"Have you misspelled the {.arg data} argument in {.fn quad_discrete}\"\n ))\n}\n\n#############################################################\n#' @export\n#' @rdname quad_layout\nquad_continuous <- function(data = waiver(), mapping = aes(),\n xlim = NULL, ylim = NULL,\n ...,\n theme = NULL, active = NULL,\n width = NA, height = NA) {\n UseMethod(\"quad_continuous\")\n}\n\n#' @usage NULL\n#' @export\n#' @rdname quad_layout\nggside <- quad_continuous\n\n#' @usage NULL\n#' @export\n#' @rdname quad_layout\nquad_free <- quad_continuous\n\n#' @export\nquad_continuous.default <- function(data = waiver(), mapping = aes(),\n xlim = NULL, ylim = NULL,\n ...,\n theme = NULL, active = NULL,\n width = NA, height = NA) {\n xlim <- xlim %|w|% NULL\n ylim <- ylim %|w|% NULL\n data <- fortify_data_frame(data = data, ...)\n new_quad_layout(\n name = \"quad_continuous\",\n data = data, xlim = xlim, ylim = ylim,\n mapping = mapping, active = active, theme = theme,\n width = width, height = height\n )\n}\n\n#' @export\nquad_continuous.uneval <- function(data, ...) {\n cli_abort(c(\n \"{.arg data} cannot be {.obj_type_friendly {data}}\",\n \"i\" = \"Have you misspelled the {.arg data} argument in {.fn quad_free}\"\n ))\n}\n\n#####################################################\n#' @importFrom ggplot2 ggplot\n#' @importFrom methods new\nnew_quad_layout <- function(name, data, xlim = waiver(), ylim = waiver(),\n mapping = aes(), theme = NULL, active = NULL,\n width = NA, height = NA,\n class = \"QuadLayout\",\n call = caller_call()) {\n if (!is.waive(xlim)) assert_limits(xlim, call = call)\n if (!is.waive(ylim)) assert_limits(ylim, call = call)\n if (is.waive(xlim) || is.waive(ylim)) {\n # If we need align discrete variables, data cannot be `NULL` and\n # must be provided, here, we convert it to waiver() to indicate\n # inherit from the parent layout\n data <- data %||% waiver()\n if (!is.waive(data) && !is.function(data)) {\n nrows <- NROW(data)\n ncols <- ncol(data)\n\n # for data has dimention but one dimention is 0\n # as.matrix(data.frame(row.names = letters))\n if (nrows == 0L || ncols == 0L) {\n cli_abort(\"empty data is no allowed\")\n }\n } else {\n nrows <- NULL\n ncols <- NULL\n }\n }\n horizontal <- ylim %|w|% discrete_design(nobs = nrows)\n vertical <- xlim %|w|% discrete_design(nobs = ncols)\n\n # always remove default axis titles\n # https://stackoverflow.com/questions/72402570/why-doesnt-gplot2labs-overwrite-update-the-name-argument-of-scales-function\n # There are multiple ways to set labels in a plot, which take different\n # priorities. Here are the priorities from highest to lowest.\n # 1. The guide title.\n # 2. The scale name.\n # 3. The `labs()` function.\n # 4. The captured expression in aes().\n plot <- ggplot(mapping = mapping) +\n ggplot2::labs(x = NULL, y = NULL)\n\n if (!is.null(theme)) assert_s3_class(theme, \"theme\", call = call)\n # for `QuadLayout`, we use `NULL` to inherit data from parent layout\n # since `QuadLayout` must have data, and won't be waiver()\n # if inherit from the parent layout data, we'll inherit\n # the action data function\n schemes <- default_schemes(\n if (is.null(data)) waiver() else NULL,\n th = theme_no_strip()\n )\n\n # check arguments -----------------------------------\n width <- check_size(width, call = call)\n height <- check_size(height, call = call)\n assert_active(active, call = call)\n\n # Here we use S4 object to override the double dispatch of `+.gg` method\n new(\n class,\n # used by the layout\n data = data, theme = theme,\n schemes = schemes,\n plot_active = update_active(active, new_active(use = TRUE)),\n name = name,\n # used by the main body\n body_schemes = default_schemes(waiver()),\n # following parameters can be controlled by `quad_switch`\n width = width, height = height,\n # following parameters are used internally\n plot = plot, horizontal = horizontal, vertical = vertical\n )\n}\n\n# Used to create the QuadLayout\n#' @include layout-.R\nmethods::setClass(\n \"QuadLayout\",\n contains = \"LayoutProto\",\n list(\n data = \"ANY\", plot = \"ANY\", body_schemes = \"list\", name = \"character\",\n # parameters for main body\n width = \"ANY\", height = \"ANY\",\n # Used to align axis\n horizontal = \"ANY\", vertical = \"ANY\",\n # top, left, bottom, right must be a StackLayout object.\n top = \"ANY\", left = \"ANY\", bottom = \"ANY\", right = \"ANY\",\n # If we regard `QuadLayout` as a plot, and put it into the stack\n # layout, we need following arguments to control it's behavour\n plot_active = \"ANY\"\n ),\n prototype = list(\n # used by QuadLayout\n top = NULL, left = NULL, bottom = NULL, right = NULL\n )\n)\n\n#' @export\nis_layout_discrete.QuadLayout <- function(x, direction, ...) {\n is_discrete_design(slot(x, direction))\n}\n\n#' @export\nis_layout_continuous.QuadLayout <- function(x, direction, ...) {\n is_continuous_design(slot(x, direction))\n}\n"], ["/ggalign/R/layout-quad-upset.R", "#' Create an UpSet plot\n#'\n#' @description\n#' `r lifecycle::badge('experimental')`\n#'\n#' `ggupset` is a specialized version of [`quad_discrete()`], which simplifies\n#' the creation of Upset plot.\n#'\n#' @param data Data used to create the UpSet plot. [`fortify_matrix()`] will be\n#' used to convert the data to a matrix. Currently, only\n#' [`fortify_matrix.list_upset`] and [`fortify_matrix.matrix_upset`] are\n#' suitable for creating an UpSet plot.\n#' @param ... Additional arguments passed to [`fortify_matrix()`].\n#' @inheritParams quad_layout\n#' @param direction A string indicating the direction of the UpSet plot,\n#' `\"h\"`(`horizontal`) or `\"v\"`(`vertical`). In a vertical UpSet plot, the\n#' columns of the matrix correspond to the sets, and the rows correspond to the\n#' intersections. By default, the horizontal UpSet plot is used, where the rows\n#' of the matrix correspond to the sets and the columns correspond to the\n#' intersections.\n#' @param point A list of parameters passed to\n#' [`geom_point()`][ggplot2::geom_point()].\n#' @param line A list of parameters passed to\n#' [`geom_line()`][ggplot2::geom_line()].\n#' @param rect A list of parameters passed to\n#' [`geom_rect()`][ggplot2::geom_rect()].\n#'\n#' @inheritSection heatmap_layout ggplot2 specification\n#' @examples\n#' set.seed(123)\n#' lt <- list(\n#' a = sample(letters, 5),\n#' b = sample(letters, 10),\n#' c = sample(letters, 15)\n#' )\n#' ggupset(tune(lt)) +\n#' scale_fill_manual(values = c(\"#F0F0F0\", \"white\"), guide = \"none\") +\n#' scale_color_manual(values = c(\"grey\", \"black\"), guide = \"none\") +\n#' anno_top() +\n#' ggalign(data = function(d) ggalign_attr(d, \"intersection_sizes\")) +\n#' ggplot2::geom_bar(aes(y = .data$value), stat = \"identity\") +\n#' anno_right() +\n#' ggalign(data = function(d) ggalign_attr(d, \"set_sizes\")) +\n#' ggplot2::geom_bar(aes(x = .data$value),\n#' stat = \"identity\",\n#' orientation = \"y\"\n#' )\n#' @importFrom ggplot2 aes\n#' @export\nggupset <- function(data = NULL, mapping = aes(),\n ...,\n direction = \"h\",\n point = NULL, line = NULL, rect = NULL,\n width = NA, height = NA,\n theme = NULL, active = NULL) {\n UseMethod(\"ggupset\")\n}\n\n# Don't allow inherit from the parent layout, since data for upset plot is\n# usually different with others\n#' @export\nggupset.NULL <- function(data, ...) {\n cli_abort(\"{.arg data} must be provided to create upset plot\")\n}\n\n#' @export\nggupset.waiver <- ggupset.NULL\n\n#' @importFrom ggplot2 aes\n#' @export\nggupset.default <- function(data = NULL, mapping = aes(),\n ...,\n direction = \"h\",\n point = NULL, line = NULL, rect = NULL,\n width = NA, height = NA,\n theme = NULL, active = NULL) {\n direction <- check_direction(direction)\n # we need a matrix to melted into long formated data frame\n data <- fortify_matrix(data = data, ...)\n if (is_vertical(direction)) data <- ggalign_data_restore(t(data), data)\n ans <- new_quad_layout(\n name = \"ggupset\",\n data = data,\n mapping = mapping,\n theme = theme,\n active = active\n )\n ans@plot <- ggadd_default(ans@plot, mapping = aes(.data$.x, .data$.y)) +\n ggplot2::labs(x = NULL, y = NULL) +\n upset_rect(direction, rect) +\n upset_point(point) +\n upset_line(direction, line)\n ans\n}\n\nmerge_mapping <- function(x, y) {\n if (is.null(x)) {\n return(y)\n }\n for (i in names(y)) {\n x[[i]] <- .subset2(y, i)\n }\n x\n}\n\nmerge_data_fn <- function(plot_data, user_data) {\n if (is.null(user_data) || is.waive(user_data)) {\n plot_data\n } else if (is.function(user_data <- allow_lambda(user_data))) {\n force(plot_data)\n function(data) user_data(plot_data(data))\n } else {\n user_data\n }\n}\n\nupset_rect <- function(direction, rect) {\n if (is_horizontal(direction)) {\n rect$mapping <- merge_mapping(rect$mapping, aes(\n ymin = .data$.ymin, ymax = .data$.ymax, fill = .data$rect_group\n ))\n rect$data <- merge_data_fn(function(data) {\n column <- c(\n \".y\", \".panel_x\", \".panel_y\",\n \".row_index\", \".row_names\", \".discrete_y\"\n )\n o <- vec_unique(data[vec_set_intersect(column, names(data))])\n o$rect_group <- (.subset2(o, \".y\") %% 2L) == 0L\n o$.ymin <- o$.y - 0.5\n o$.ymax <- o$.y + 0.5\n o\n }, rect$data)\n inject(ggplot2::geom_rect(!!!rect,\n xmin = -Inf, xmax = Inf, inherit.aes = FALSE\n ))\n } else {\n rect$mapping <- merge_mapping(rect$mapping, aes(\n xmin = .data$.xmin, xmax = .data$.xmax,\n fill = .data$rect_group\n ))\n rect$data <- merge_data_fn(function(data) {\n column <- c(\n \".x\", \".panel_x\", \".panel_y\",\n \".column_index\", \".column_names\", \".discrete_x\"\n )\n o <- vec_unique(data[vec_set_intersect(column, names(data))])\n o$rect_group <- (.subset2(o, \".x\") %% 2L) == 0L\n o$.xmin <- o$.x - 0.5\n o$.xmax <- o$.x + 0.5\n o\n }, rect$data)\n inject(ggplot2::geom_rect(!!!rect,\n ymin = -Inf, ymax = Inf, inherit.aes = FALSE\n ))\n }\n}\n\nupset_point <- function(point) {\n point$mapping <- merge_mapping(point$mapping, aes(\n x = .data$.x, y = .data$.y, color = .data$point_group\n ))\n point$data <- merge_data_fn(function(data) {\n data$point_group <- .subset2(data, \"value\")\n data\n }, point$data)\n inject(ggplot2::geom_point(!!!point, inherit.aes = FALSE))\n}\n\nupset_line <- function(direction, line) {\n line$mapping <- merge_mapping(line$mapping, switch_direction(\n direction,\n aes(.data$.x, .data$.y, group = paste(.data$.panel_x, .data$.x)),\n aes(.data$.x, .data$.y, group = paste(.data$.panel_y, .data$.y))\n ))\n line$data <- merge_data_fn(function(data) {\n if (is_horizontal(direction)) {\n dlist <- vec_split(data, data[c(\".panel_x\", \".x\")])\n dlist <- lapply(.subset2(dlist, \"val\"), function(d) {\n o <- vec_slice(d, .subset2(d, \"value\"))\n if (vec_size(o) < 2L) {\n return(NULL)\n }\n vec_slice(o, c(\n which.min(.subset2(o, \".y\")),\n which.max(.subset2(o, \".y\"))\n ))\n })\n vec_rbind(!!!dlist)\n } else {\n dlist <- vec_split(data, data[c(\".panel_y\", \".y\")])\n dlist <- lapply(.subset2(dlist, \"val\"), function(d) {\n o <- vec_slice(d, .subset2(d, \"value\"))\n if (vec_size(o) < 2L) {\n return(NULL)\n }\n vec_slice(o, c(\n which.min(.subset2(o, \".x\")),\n which.max(.subset2(o, \".x\"))\n ))\n })\n vec_rbind(!!!dlist)\n }\n }, line$data)\n inject(ggplot2::geom_line(!!!line, inherit.aes = FALSE))\n}\n"], ["/ggalign/R/layout-chain-stack-.R", "#' Arrange plots horizontally or vertically\n#'\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' If `limits` is provided, a continuous variable will be required and aligned\n#' in the direction specified (`stack_continuous`). Otherwise, a discrete\n#' variable will be required and aligned (`stack_discrete`).\n#'\n#' Several aliases are provided for convenience:\n#' - `stack_vertical`: A special case of `stack_layout` that sets `direction\n#' = \"v\"`.\n#' - `stack_horizontal`: A special case of `stack_layout` that sets `direction\n#' = \"h\"`.\n#' - `stack_discretev`: A special case of `stack_discrete` that sets `direction\n#' = \"v\"`.\n#' - `stack_discreteh`: A special case of `stack_discrete` that sets `direction\n#' = \"h\"`.\n#' - `stack_continuousv()`: A special case of `stack_free` that sets `direction\n#' = \"v\"`.\n#' - `stack_continuoush()`: A special case of `stack_free` that sets `direction\n#' = \"h\"`.\n#'\n#' For historical reasons, the following aliases are available:\n#' - `stack_align` is an alias for `stack_discrete`.\n#' - `stack_alignv` is an alias for `stack_discretev`.\n#' - `stack_alignh` is an alias for `stack_discreteh`.\n#' - `stack_free` is an alias for `stack_continuous`.\n#' - `stack_freev` is an alias for `stack_continuousv`.\n#' - `stack_freeh` is an alias for `stack_continuoush`.\n#'\n#' @param direction A string indicating the direction of the stack layout,\n#' either `\"h\"`(`horizontal`) or `\"v\"`(`vertical`).\n#' @param data `r rd_layout_data()`:\n#' - If `limits` is not provided, [`fortify_matrix()`] will be used to get a\n#' matrix.\n#' - If `limits` is specified, [`fortify_data_frame()`] will be used to get a\n#' data frame.\n#'\n#' @param ... Additional arguments passed to [`fortify_data_frame()`] or\n#' [`fortify_matrix()`].\n#' @param theme A [`theme()`][ggplot2::theme] object used to customize various\n#' elements of the layout, including `guides`, `title`, `subtitle`, `caption`,\n#' `margins`, `panel.border`, and `background`. By default, the theme will\n#' inherit from the parent `layout`. It also controls the panel spacing for all\n#' plots in the layout.\n#'\n#' @param sizes A numeric value or a [`unit`][grid::unit] object. When used for\n#' the [`quad_layout()`] annotation, it must be of length `1`. When used in the\n#' [`stack_layout()`] with a nested [`quad_layout()`], it should be of length\n#' `3`, specifying the relative heights (for `direction = \"h\"`) or widths (for\n#' `direction = \"v\"`) to be applied to the layout.\n#' @param limits A [`continuous_limits()`] object specifying the left/lower\n#' limit and the right/upper limit of the scale. Used to align the continuous\n#' axis.\n#' @return A `StackLayout` object.\n#' @examples\n#' set.seed(123)\n#' small_mat <- matrix(rnorm(56), nrow = 7L)\n#'\n#' stack_horizontal(small_mat) + align_dendro()\n#'\n#' # this is the same with:\n#' stack_discrete(\"h\", small_mat) + align_dendro()\n#'\n#' stack_discreteh(small_mat) + align_dendro()\n#'\n#' # For vertical layout:\n#' stack_vertical(small_mat) + align_dendro()\n#'\n#' @export\nstack_layout <- function(direction, data = NULL, ...,\n theme = NULL, sizes = NA, limits = waiver()) {\n if (is.waive(limits)) {\n stack_discrete(\n data = data, direction = direction, ...,\n theme = theme, sizes = sizes\n )\n } else {\n stack_continuous(\n data = data, direction = direction, ...,\n theme = theme, sizes = sizes, limits = limits\n )\n }\n}\n\n#' @export\n#' @rdname stack_layout\nstack_horizontal <- function(data = NULL, ..., limits = waiver()) {\n stack_layout(data = data, direction = \"h\", limits = limits, ...)\n}\n\n#' @export\n#' @rdname stack_layout\nstack_vertical <- function(data = NULL, ..., limits = waiver()) {\n stack_layout(data = data, direction = \"v\", limits = limits, ...)\n}\n\n###################################################################\n#' @export\n#' @rdname stack_layout\nstack_discrete <- function(direction, data = NULL, ...,\n theme = NULL, sizes = NA) {\n UseMethod(\"stack_discrete\", data)\n}\n\n#' @usage NULL\n#' @export\n#' @rdname stack_layout\nstack_align <- stack_discrete\n\n#' @export\n#' @rdname stack_layout\nstack_discretev <- function(data = NULL, ...) {\n stack_discrete(data = data, direction = \"v\", ...)\n}\n\n#' @usage NULL\n#' @export\n#' @rdname stack_layout\nstack_alignv <- stack_discretev\n\n#' @export\n#' @rdname stack_layout\nstack_discreteh <- function(data = NULL, ...) {\n stack_discrete(data = data, direction = \"h\", ...)\n}\n\n#' @usage NULL\n#' @export\n#' @rdname stack_layout\nstack_alignh <- stack_discreteh\n\n#' @export\nstack_discrete.default <- function(direction, data = NULL, ...,\n theme = NULL, sizes = NA) {\n direction <- check_direction(direction)\n # the observations are rows, we use matrix to easily\n # reshape it into a long formated data frame for ggplot,\n # and we can easily determine the number of observations\n # from matrix\n data <- data %|w|% NULL\n data <- fortify_matrix(data = data, ...)\n schemes <- default_schemes()\n if (!is.null(data) && !is.function(data)) {\n # if we have provided data, we initialize the `nobs`\n nobs <- vec_size(data)\n\n # for data has dimention but one dimention is 0\n # as.matrix(data.frame(row.names = letters))\n if (nobs == 0L) {\n cli_abort(\"empty data is no allowed\")\n }\n } else {\n nobs <- NULL\n }\n new_stack_layout(\n name = \"stack_discrete\",\n data = data, direction = direction,\n design = discrete_design(nobs = nobs),\n schemes = schemes, theme = theme, sizes = sizes\n )\n}\n\n#' @export\nstack_discrete.function <- function(direction, data = NULL, ...) {\n cli_abort(paste0(\n \"{.arg data} must be a {.cls matrix}, \",\n \"or an object coercible by {.fn fortify_matrix}, or a valid \",\n \"{.cls matrix}-like object coercible by {.fn as.matrix}\"\n ))\n}\n\n#' @export\nstack_discrete.formula <- stack_discrete.function\n\n################################################################\n#' @export\n#' @rdname stack_layout\nstack_continuous <- function(direction, data = NULL, ..., limits = NULL,\n theme = NULL, sizes = NA) {\n UseMethod(\"stack_continuous\", data)\n}\n\n#' @usage NULL\n#' @export\n#' @rdname stack_layout\nstack_free <- stack_continuous\n\n#' @export\n#' @rdname stack_layout\nstack_continuousv <- function(data = NULL, ...) {\n stack_continuous(data = data, direction = \"v\", ...)\n}\n\n#' @usage NULL\n#' @export\n#' @rdname stack_layout\nstack_freev <- stack_continuousv\n\n#' @export\n#' @rdname stack_layout\nstack_continuoush <- function(data = NULL, ...) {\n stack_continuous(data = data, direction = \"h\", ...)\n}\n\n#' @usage NULL\n#' @export\n#' @rdname stack_layout\nstack_freeh <- stack_continuoush\n\n#' @export\nstack_continuous.default <- function(direction, data = NULL, ...,\n limits = NULL, theme = NULL, sizes = NA) {\n assert_limits(limits)\n direction <- check_direction(direction)\n data <- data %|w|% NULL\n data <- fortify_data_frame(data = data, ...)\n schemes <- default_schemes()\n new_stack_layout(\n name = \"stack_continuous\",\n data = data, direction = direction, design = limits,\n schemes = schemes, theme = theme, sizes = sizes\n )\n}\n\n#' @export\nstack_continuous.function <- function(direction, data = NULL, ...) {\n cli_abort(paste0(\n \"{.arg data} must be a {.cls data.frame}, \",\n \"or an object coercible by {.fn fortify_data_frame}, or a valid \",\n \"{.cls data.frame}-like object coercible by {.fn as.data.frame}\"\n ))\n}\n\n#' @export\nstack_continuous.formula <- stack_continuous.function\n\n#' @importFrom methods new\nnew_stack_layout <- function(data, direction, design,\n schemes = NULL, theme = NULL, sizes = NA,\n name = NULL, call = caller_call()) {\n sizes <- check_stack_sizes(sizes, call = call)\n if (!is.null(theme)) assert_s3_class(theme, \"theme\", call = call)\n if (is.null(name)) {\n if (is_continuous_design(design)) {\n name <- \"stack_continuous\"\n } else {\n name <- \"stack_discrete\"\n }\n }\n new(\n \"StackLayout\",\n name = name, data = data,\n direction = direction,\n theme = theme, schemes = schemes, # used by the layout\n sizes = sizes, design = design\n )\n}\n\n############################################################\n# Used to place multiple objects in one axis\n#' @importFrom grid unit\n#' @importFrom ggplot2 waiver\n#' @keywords internal\n#' @include layout-chain-.R\nmethods::setClass(\n \"StackLayout\",\n contains = \"ChainLayout\",\n list(\n direction = \"character\",\n heatmap = \"list\", # used by heatmap annotation\n sizes = \"ANY\" # used by stack layout\n ),\n prototype = list(\n heatmap = list(\n position = NULL,\n free_guides = waiver(),\n # indicate whether or not the data is from the quad-layout matrix\n quad_matrix = FALSE\n )\n )\n)\n"], ["/ggalign/R/layout-chain-circle-switch.R", "#########################################################\n#' Determine the active context of circle layout\n#'\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' @inheritParams rlang::args_dots_empty\n#' @inheritParams circle_discrete\n#' @param what What should get activated for the [`circle_layout()`]?\n#' `r rd_chain_what()`.\n#' @return A `circle_switch` object which can be added to [`circle_layout()`].\n#' @examples\n#' set.seed(123)\n#' small_mat <- matrix(rnorm(56), nrow = 7)\n#' rownames(small_mat) <- paste0(\"row\", seq_len(nrow(small_mat)))\n#' colnames(small_mat) <- paste0(\"column\", seq_len(ncol(small_mat)))\n#' circle_discrete(small_mat) +\n#' ggalign() +\n#' geom_tile(aes(y = .column_index, fill = value)) +\n#' scale_fill_viridis_c() +\n#' align_dendro(aes(color = branch), k = 3L) +\n#' scale_color_brewer(palette = \"Dark2\")\n#' @export\ncircle_switch <- function(radial = waiver(), direction = NULL,\n what = waiver(), ...) {\n rlang::check_dots_empty()\n if (!is.waive(radial) && !is.null(radial)) {\n assert_s3_class(radial, \"CoordRadial\")\n if (abs(diff(radial$arc)) < pi / 2L) {\n cli_abort(\"Cannot use circle of acute angle < 90 in {.arg radial}\")\n }\n }\n if (!is.null(direction)) {\n direction <- arg_match0(direction, c(\"inward\", \"outward\"))\n }\n if (!is.waive(what)) what <- check_stack_context(what)\n structure(list(what = what, radial = radial, direction = direction),\n class = \"circle_switch\"\n )\n}\n"], ["/ggalign/R/raster-magick.R", "#' Rasterize the ggplot layers\n#'\n#' The function rasterizes input graphical objects (e.g., grob, layer, ggplot)\n#' and optionally processes the resulting raster using magick, a powerful image\n#' manipulation library. This allows for advanced graphical transformations\n#' directly within the plotting pipeline.\n#'\n#' @param x An object to rasterize, can be a [`grob()`][grid::grob],\n#' [`layer()`][ggplot2::layer], [`ggplot()`][ggplot2::ggplot], or a list of such\n#' objects.\n#'\n#' @inheritParams rlang::args_dots_empty\n#' @inheritParams magickGrob\n#' @examples\n#' # Currently, `magick` package require R >= 4.1.0\n#' if (requireNamespace(\"magick\")) {\n#' # data generated code was copied from `ComplexHeatmap`\n#' set.seed(123)\n#' small_mat <- matrix(rnorm(56), nrow = 7)\n#' rownames(small_mat) <- paste0(\"row\", seq_len(nrow(small_mat)))\n#' colnames(small_mat) <- paste0(\"column\", seq_len(ncol(small_mat)))\n#' ggheatmap(small_mat, aes(.x, .y), filling = NULL) +\n#' raster_magick(geom_tile(aes(fill = value)), res = 20)\n#'\n#' ggheatmap(small_mat, aes(.x, .y), filling = NULL) +\n#' # Use `magick::filter_types()` to check available `filter` arguments\n#' raster_magick(\n#' geom_tile(aes(fill = value)),\n#' magick = function(image) {\n#' magick::image_resize(image,\n#' geometry = \"50%x\", filter = \"Lanczos\"\n#' )\n#' }\n#' )\n#' }\n#' @return An object with the same class of the input.\n#' @seealso [`magickGrob()`]\n#' @export\nraster_magick <- function(x, magick = NULL, ...,\n res = NULL, interpolate = FALSE,\n vp = NULL) {\n rlang::check_installed(\"magick\", \"to use `raster_magick()`\")\n if (!is.null(magick) && !is.function(magick <- allow_lambda(magick))) {\n cli_abort(\"{.arg magick} must be a function\")\n }\n assert_number_whole(res, min = 1, allow_null = TRUE)\n assert_bool(interpolate)\n raster_magick0(\n x = x, ..., magick = magick,\n res = res, interpolate = interpolate,\n vp = vp\n )\n}\n\n# Used to do the actual process, but won't check the arguments\n#' @keywords internal\nraster_magick0 <- function(x, ...) {\n UseMethod(\"raster_magick0\")\n}\n\n#' @importFrom ggplot2 ggproto ggproto_parent\n#' @export\nraster_magick0.Layer <- function(x, ...) {\n ggproto(\n NULL, x,\n draw_geom = function(self, data, layout) {\n grobs <- ggproto_parent(x, self)$draw_geom(data, layout)\n if (!inherits(layout$coord, \"CoordCartesian\")) {\n cli_warn(\n \"{.fn raster_magick} only works with {.fn coord_cartesian}.\"\n )\n return(grobs)\n }\n raster_magick0(grobs, ...)\n }\n )\n}\n\n#' @export\nraster_magick0.ggplot <- function(x, ...) {\n x$layers <- lapply(x$layers, raster_magick0, ...)\n x\n}\n\n#' @export\nraster_magick0.list <- function(x, ...) lapply(x, raster_magick0, ...)\n\n#' @export\nraster_magick0.grob <- function(x, magick = NULL, ...,\n res = NULL, interpolate = FALSE,\n vp = NULL) {\n rlang::check_dots_empty()\n magickGrob0(\n grob = x, magick = magick,\n res = res, interpolate = interpolate, vp = vp\n )\n}\n\n#' @export\nraster_magick0.gList <- raster_magick0.grob\n\n#' @export\nraster_magick0.default <- function(x, ...) {\n cli_abort(\"Cannot rasterize {.obj_type_friendly {x}}\")\n}\n"], ["/ggalign/R/ggplot-geom-rect3d.R", "#' Add z-aesthetic for geom_tile\n#'\n#' @section new aesthetics:\n#' - `z`: the third dimention (in the z direction), use\n#' [`scale_z_continuous()`] to control the ranges.\n#' - `theta`: Angle between x-axis and z-axis.\n#' @inheritParams ggplot2::layer\n#' @inheritParams ggplot2::geom_polygon\n#' @inheritParams ggplot2::geom_path\n#' @aesthetics GeomRect3d\n#' @examples\n#' set.seed(123)\n#' small_mat <- matrix(rnorm(81), nrow = 9)\n#' rownames(small_mat) <- paste0(\"row\", seq_len(nrow(small_mat)))\n#' colnames(small_mat) <- paste0(\"column\", seq_len(ncol(small_mat)))\n#' ggheatmap(small_mat,\n#' filling = FALSE,\n#' theme = theme(\n#' legend.box.spacing = unit(10, \"mm\"),\n#' plot.margin = margin(t = 15, unit = \"mm\")\n#' )\n#' ) +\n#' geom_tile3d(\n#' aes(fill = value, z = value, width = 0.8, height = 0.8),\n#' color = \"black\"\n#' ) +\n#' scale_fill_viridis_c(\n#' option = \"plasma\",\n#' breaks = scales::breaks_pretty(3L)\n#' ) +\n#' coord_cartesian(clip = \"off\")\n#'\n#' @export\ngeom_rect3d <- function(mapping = NULL, data = NULL, stat = \"identity\",\n position = \"identity\", ...,\n lineend = \"butt\", linejoin = \"round\", linemitre = 10,\n na.rm = FALSE, show.legend = NA, inherit.aes = TRUE) {\n ggplot2::layer(\n data = data,\n mapping = mapping,\n stat = stat,\n geom = GeomRect3d,\n position = position,\n show.legend = show.legend,\n inherit.aes = inherit.aes,\n params = list(\n lineend = lineend,\n linejoin = linejoin,\n linemitre = linemitre,\n na.rm = na.rm, ...\n )\n )\n}\n\n#' @importFrom ggplot2 ggproto fill_alpha\nGeomRect3d <- ggproto(\n \"GeomRect3d\",\n ggplot2::GeomRect,\n required_aes = c(ggplot2::GeomRect$required_aes, \"z\"),\n non_missing_aes = c(ggplot2::GeomRect$non_missing_aes, \"z\", \"theta\"),\n setup_data = function(self, data, params) {\n theta <- data$theta %||% .subset2(params, \"theta\")\n if (!is.null(theta) && any(theta <= 0 || theta >= 90)) {\n cli_abort(\n \"value mapped to {.field theta} aesthetic must > 0 and < 90.\"\n )\n }\n data$theta <- theta %||% 60\n ggproto_parent(ggplot2::GeomRect, self)$setup_data(data, params)\n },\n draw_panel = function(self, data, panel_params, coord, lineend = \"butt\",\n linejoin = \"round\", linemitre = 10) {\n data <- setup_3d_data(data)\n # Transform to viewport coords\n coords <- coord$transform(data, panel_params)\n\n # collapse the gpar value\n data <- .subset2(\n vec_split(\n data[setdiff(names(data), c(\"x\", \"y\", \"width\", \"height\"))],\n .subset2(data, \"polygon_id\")\n ),\n \"val\"\n )\n data <- vec_rbind(!!!lapply(data, vec_unique))\n\n # Draw as grob\n grid::polygonGrob(\n x = coords$x,\n y = coords$y,\n id = coords$polygon_id,\n default.units = \"native\",\n gp = gpar(\n col = data$colour,\n fill = fill_alpha(data$fill, data$alpha),\n lwd = data$linewidth,\n lty = data$linetype,\n lineend = lineend,\n linejoin = linejoin,\n linemitre = linemitre\n )\n )\n }\n)\n\nsetup_3d_data <- function(data) {\n data <- vec_slice(\n data,\n order(\n .subset2(data, \"xmin\"),\n .subset2(data, \"ymin\"),\n decreasing = TRUE\n )\n )\n coords <- .mapply(\n function(xmin, xmax, ymin, ymax, z, theta, ...) {\n if (z == 0L) {\n # fallback to tile\n data_frame0(\n x = vec_c(xmin, xmax, xmax, xmin),\n y = vec_rep_each(c(ymin, ymax), 2L)\n )\n } else {\n offset_x <- z * cos(theta / 180 * pi)\n z_xmin <- xmin + offset_x\n z_xmax <- xmax + offset_x\n offset_y <- z * sin(theta / 180 * pi)\n z_ymin <- ymin + offset_y\n z_ymax <- ymax + offset_y\n data_frame0(\n x = vec_c(\n xmin, z_xmin, z_xmax, xmax, xmin, xmin,\n z_xmin, z_xmin, z_xmin, z_xmax, z_xmax, z_xmin\n ),\n y = vec_c(\n ymin, z_ymin, z_ymin, ymin, ymin, ymax,\n z_ymax, z_ymin, z_ymax, z_ymax, z_ymin, z_ymin\n )\n )\n }\n },\n data,\n MoreArgs = NULL\n )\n vec_cbind(\n vec_rbind(!!!coords),\n vec_rep_each(\n data[\n vec_set_difference(\n names(data),\n c(\"x\", \"xmin\", \"xmax\", \"y\", \"ymin\", \"ymax\", \"z\")\n )\n ],\n list_sizes(coords)\n ),\n polygon_id = vec_rep_each(seq_along(coords), list_sizes(coords))\n )\n}\n\n#' @aesthetics GeomTile3d\n#' @importFrom rlang list2\n#' @export\n#' @rdname geom_rect3d\ngeom_tile3d <- function(mapping = NULL, data = NULL, stat = \"identity\",\n position = \"identity\", ...,\n lineend = \"butt\", linejoin = \"round\", linemitre = 10,\n na.rm = FALSE, show.legend = NA, inherit.aes = TRUE) {\n ggplot2::layer(\n data = data,\n mapping = mapping,\n stat = stat,\n geom = GeomTile3d,\n position = position,\n show.legend = show.legend,\n inherit.aes = inherit.aes,\n params = list(\n lineend = lineend,\n linejoin = linejoin,\n linemitre = linemitre,\n na.rm = na.rm, ...\n )\n )\n}\n\n#' @importFrom ggplot2 ggproto ggproto_parent\nGeomTile3d <- ggproto(\n \"GeomTile3d\",\n ggplot2::GeomTile,\n required_aes = c(ggplot2::GeomTile$required_aes, \"z\"),\n non_missing_aes = c(ggplot2::GeomTile$non_missing_aes, \"z\", \"theta\"),\n setup_data = function(self, data, params) {\n theta <- data$theta %||% .subset2(params, \"theta\")\n if (!is.null(theta) && any(theta <= 0 || theta >= 90)) {\n cli_abort(\n \"value mapped to {.field theta} aesthetic must > 0 and < 90.\"\n )\n }\n data$theta <- theta %||% 60\n ggproto_parent(ggplot2::GeomTile, self)$setup_data(data, params)\n },\n draw_panel = function(self, data, panel_params, coord, lineend = \"butt\",\n linejoin = \"round\", linemitre = 10) {\n ggproto_parent(GeomRect3d, self)$draw_panel(\n data = data, panel_params = panel_params, coord = coord,\n lineend = lineend, linejoin = linejoin, linemitre = linemitre\n )\n }\n)\n\n#' z scales\n#'\n#' @param ... Other arguments passed on to\n#' [`continuous_scale()`][ggplot2::continuous_scale],\n#' [`binned_scale()`][ggplot2::binned_scale], or\n#' [`discrete_scale()`][ggplot2::discrete_scale] as appropriate, to control\n#' name, limits, breaks, labels and so forth.\n#' @param range Output range of z values. Must larger than 0.\n#' @inheritParams ggplot2::continuous_scale\n#' @seealso [`geom_tile3d()`]/[`geom_rect3d()`]\n#' @export\n#' @examples\n#'\n#' set.seed(7)\n#' mat <- matrix(runif(100), 10)\n#' rownames(mat) <- LETTERS[1:10]\n#' colnames(mat) <- letters[1:10]\n#' ggheatmap(mat,\n#' filling = FALSE,\n#' theme = theme(\n#' legend.box.spacing = unit(10, \"mm\"),\n#' plot.margin = margin(t = 15, unit = \"mm\")\n#' )\n#' ) +\n#' geom_tile3d(aes(fill = value, z = value, width = 0.8, height = 0.8)) +\n#' scale_z_continuous(range = c(0.2, 1)) +\n#' coord_cartesian(clip = \"off\")\n#' @export\nscale_z_continuous <- function(name = waiver(), ..., range = c(0.1, 1),\n guide = \"none\") {\n if (min(range) < 0) {\n cli_abort(\"{.arg range} must contain only positive values\")\n }\n ggplot2::continuous_scale(\"z\",\n name = name, palette = scales::pal_rescale(range), ...,\n guide = guide\n )\n}\n\n#' @rdname scale_z_continuous\n#' @export\nscale_z_binned <- function(name = waiver(), ..., range = c(0.1, 1),\n guide = \"none\") {\n if (min(range) < 0) {\n cli_abort(\"{.arg range} must contain only positive values\")\n }\n ggplot2::binned_scale(\"z\",\n name = name, palette = scales::pal_rescale(range), ...,\n guide = guide\n )\n}\n\n#' @rdname scale_z_continuous\n#' @export\nscale_z_discrete <- function(...) {\n cli_warn(\"Using {z} for a discrete variable is not advised.\")\n args <- list2(...)\n args$call <- args$call %||% current_call()\n rlang::exec(scale_z_ordinal, !!!args)\n}\n\n#' @rdname scale_z_continuous\n#' @export\nscale_z_ordinal <- function(name = waiver(), ..., range = c(0.1, 1),\n guide = \"none\") {\n if (min(range) < 0) {\n cli_abort(\"{.arg range} must contain only positive values\")\n }\n ggplot2::discrete_scale(\n \"z\",\n name = name,\n palette = function(n) seq(range[1], range[2], length.out = n),\n ...,\n gudie = guide\n )\n}\n\n#' @rdname scale_z_continuous\n#' @export\n#' @usage NULL\nscale_z_datetime <- function(name = waiver(), ..., range = c(0.1, 1),\n guide = \"none\") {\n if (min(range) < 0) {\n cli_abort(\"{.arg range} must contain only positive values\")\n }\n ggplot2::datetime_scale(\n aesthetics = \"z\", transform = \"time\", name = name,\n palette = scales::pal_rescale(range),\n ..., guide = guide\n )\n}\n\n#' @rdname scale_z_continuous\n#' @export\n#' @usage NULL\nscale_z_date <- function(name = waiver(), ..., range = c(0.1, 1),\n guide = \"none\") {\n if (min(range) < 0) {\n cli_abort(\"{.arg range} must contain only positive values\")\n }\n ggplot2::datetime_scale(\n aesthetics = \"z\", transform = \"date\", name = name,\n palette = scales::pal_rescale(range),\n ..., guide = guide\n )\n}\n"], ["/ggalign/R/craft-cross-none.R", "#' Reset layout ordering and panel group\n#'\n#' @param data The dataset to use for the layout. By default,\n#' [`fortify_matrix()`] will convert the data to a matrix. This argument\n#' allows you to change the layout data. If not specified, the original data\n#' will be used.\n#' @param ... <[dyn-dots][rlang::dyn-dots]> Additional arguments passed to\n#' [`fortify_matrix()`].\n#' @param inherit_index A boolean value indicating whether to inherit the\n#' ordering index. If `TRUE`, will match the layout ordering index with the\n#' data names.\n#' @param inherit_panel A boolean value indicating whether to inherit the\n#' panel group. If `TRUE`, will match the layout panel with the data names.\n#' @param inherit_nobs A boolean value indicating whether to inherit the\n#' number of observations (nobs). If `TRUE`, the `data` input must be\n#' compatible with the layout data.\n#' @export\ncross_none <- function(data = waiver(), ...,\n inherit_index = NULL,\n inherit_panel = NULL,\n inherit_nobs = NULL) {\n cross(CrossNone,\n data = data, data_params = list2(...), plot = NULL,\n active = new_active(use = FALSE),\n schemes = default_schemes(),\n inherit_index = inherit_index,\n inherit_panel = inherit_panel,\n inherit_nobs = inherit_nobs\n )\n}\n\n#' @importFrom ggplot2 ggproto ggproto_parent\n#' @include craft-cross-.R\nCrossNone <- ggproto(\"CrossNone\", CraftCross)\n"], ["/ggalign/R/alignpatch-alignpatches.R", "#' @importFrom ggplot2 ggproto\n#' @export\nalignpatch.alignpatches <- function(x) {\n ggproto(NULL, PatchAlignpatches, plot = x)\n}\n\n#' @noRd\nPatchAlignpatches <- ggproto(\"PatchAlignpatches\", Patch,\n set_guides = function(self, guides) guides,\n #' @importFrom gtable gtable gtable_add_grob\n #' @importFrom grid unit\n #' @importFrom ggplot2 wrap_dims calc_element zeroGrob theme_get\n #' @importFrom S7 prop\n patch_gtable = function(self, theme = theme_get(), guides = NULL,\n top_level = FALSE, plot = self$plot) {\n patches <- lapply(prop(plot, \"plots\"), alignpatch)\n layout <- prop(plot, \"layout\")\n\n # get the design areas and dims ------------------\n panel_widths <- .subset2(layout, \"widths\")\n panel_heights <- .subset2(layout, \"heights\")\n if (is.null(area <- .subset2(layout, \"area\"))) {\n if (is.null(layout$ncol) && length(panel_widths) > 1L) {\n layout$ncol <- length(panel_widths)\n }\n if (is.null(layout$nrow) && length(panel_heights) > 1L) {\n layout$nrow <- length(panel_heights)\n }\n dims <- wrap_dims(\n length(patches),\n .subset2(layout, \"nrow\"),\n .subset2(layout, \"ncol\")\n )\n area <- create_area(\n dims[2L], dims[1L],\n .subset2(layout, \"byrow\")\n )\n } else {\n dims <- c(max(field(area, \"b\")), max(field(area, \"r\")))\n }\n\n # filter `plots` based on the design areas --------------------\n if (vec_size(area) < vec_size(patches)) {\n cli_warn(\n \"Too few patch areas to hold all plots. Dropping plots\"\n )\n plots <- vec_slice(patches, vec_seq_along(area))\n } else {\n area <- vec_slice(area, seq_along(patches))\n }\n\n # remove NULL patch -----------------------------------\n keep <- !vapply(patches, is.null, logical(1L), USE.NAMES = FALSE)\n patches <- vec_slice(patches, keep)\n\n # if no plots, we return empty gtable -----------------\n if (is_empty(patches)) return(make_patch_table()) # styler: off\n self$patches <- patches\n\n # add borders to patch --------------------------------\n area <- vec_slice(area, keep)\n for (i in seq_along(patches)) {\n patches[[i]]$borders <- c(\n if (field(area, \"t\")[i] == 1L) \"top\" else NULL,\n if (field(area, \"l\")[i] == 1L) \"left\" else NULL,\n if (field(area, \"b\")[i] == .subset(dims, 1L)) {\n \"bottom\"\n } else {\n NULL\n },\n if (field(area, \"r\")[i] == .subset(dims, 2L)) {\n \"right\"\n } else {\n NULL\n }\n )\n }\n\n # we inherit parameters from the parent --------------------\n # by default, we won't collect any guide legends\n parent_guides <- guides\n guides <- .subset2(layout, \"guides\") %|w|% parent_guides\n\n # by default, we use ggplot2 default theme\n if (!is.null(prop(plot, \"theme\"))) theme <- theme + prop(plot, \"theme\")\n self$theme <- theme\n\n #######################################################\n # 1. patch_gtable: create the gtable for the patch, will set internal\n # `gt`\n # 2. `collect_guides`, can change the internal `gt`\n # 3. set_sizes:\n # - (To-Do) align_panel_spaces: can change the internal `gt`\n # - align_panel_sizes, can change the internal `gt`\n # - get_sizes, the widths and heights for the internal `gt`\n # 4. set_grobs: will call `align_border` and `split_gt`, return the\n # final gtable\n # setup gtable list ----------------------------------\n # Let each patch to determine whether to collect guides\n collected <- lapply(patches, function(patch) patch$set_guides(guides))\n collected_guides <- vector(\"list\", length(patches))\n\n # Always ensure that plots placed in a border collect their guides, if\n # any guides are to be collected in that border. This prevents overlap,\n # unless the guides will be collected by the parent layout.\n border_with_guides <- unique(unlist(collected, FALSE, FALSE))\n border_with_guides <- setdiff(border_with_guides, parent_guides)\n for (i in seq_along(patches)) {\n patch <- .subset2(patches, i)\n g <- union(\n .subset2(collected, i),\n intersect(border_with_guides, patch$borders)\n )\n patch$gt <- patch$patch_gtable(theme = theme, guides = g)\n collected_guides[i] <- list(patch$collect_guides(g))\n }\n\n # collect guides ---------------------------------------\n self$collected_guides <- collect_guides_list(collected_guides)\n\n # prepare the output ----------------------------------\n gt <- gtable(\n unit(rep(0L, TABLE_COLS * dims[2L]), \"null\"),\n unit(rep(0L, TABLE_ROWS * dims[1L]), \"null\")\n )\n\n # setup sizes for each row/column -----------------------\n gt <- self$set_sizes(\n area, dims, panel_widths, panel_heights,\n patches = patches, gt = gt\n )\n\n # add the panel position --------------------------------\n panel_pos <- list(\n t = TOP_BORDER + 1L,\n l = LEFT_BORDER + 1L,\n b = TABLE_ROWS * dims[1L] - BOTTOM_BORDER,\n r = TABLE_COLS * dims[2L] - RIGHT_BORDER\n )\n\n # add guides into the final gtable ----------------------\n if (top_level) {\n gt <- self$attach_guide_list(\n guide_list = self$collected_guides,\n theme = theme,\n panel_pos = panel_pos,\n gt = gt\n )\n }\n\n # setup grobs -------------------------------------------\n # For z in the gtable layout\n # 0L: layout background\n # 1L: background of the plot\n # 2L: plot table\n # 3L: foreground of the panel area\n # 4L: legends\n gt <- self$set_grobs(area, patches = patches, gt = gt)\n\n # add panel area ---------------------------------------\n gt <- gtable_add_grob(\n gt, list(zeroGrob()),\n t = .subset2(panel_pos, \"t\"),\n l = .subset2(panel_pos, \"l\"),\n b = .subset2(panel_pos, \"b\"),\n r = .subset2(panel_pos, \"r\"),\n z = 0L,\n name = \"panel-area\"\n )\n gt <- gtable_add_grob(\n gt,\n # foreground\n list(element_render(theme, \"panel.border\", fill = NA)),\n t = .subset2(panel_pos, \"t\"),\n l = .subset2(panel_pos, \"l\"),\n b = .subset2(panel_pos, \"b\"),\n r = .subset2(panel_pos, \"r\"),\n z = 3L,\n name = \"panel-foreground\"\n )\n\n # add background -----------------------------------\n if (!top_level && inherits(theme$plot.background, \"element\")) {\n gt <- gtable_add_grob(gt,\n element_render(theme, \"plot.background\"),\n t = 1L, l = 1L, b = -1L, r = -1L,\n name = \"background\", z = 0L\n )\n }\n\n # arrange the grobs\n idx <- order(.subset2(.subset2(gt, \"layout\"), \"z\"))\n gt$layout <- vec_slice(.subset2(gt, \"layout\"), idx)\n gt$grobs <- .subset(.subset2(gt, \"grobs\"), idx)\n gt\n },\n align_border = function(self, t = NULL, l = NULL, b = NULL, r = NULL,\n gt = self$gt, patches = self$patches) {\n if (is.null(t) && is.null(l) && is.null(b) && is.null(r)) {\n return(gt)\n }\n gt <- Patch$align_border(t = t, l = l, b = b, r = r, gt = gt)\n self$recurse_lapply(function(patch, grob, t, l, b, r) {\n # For each plot grob, we reuse it's method to set the border\n # sizes we only set the border sizes for plot in the border\n patch$align_border(t = t, l = l, b = b, r = r, gt = grob)\n }, t = t, l = l, b = b, r = r, gt = gt, patches = patches)\n },\n collect_guides = function(self, guides, gt = self$gt) {\n collected_guides <- self$collected_guides\n # for guides not collected by the top-level alignpatches, we attach the\n # guides\n self$gt <- self$attach_guide_list(\n collected_guides[\n vec_set_difference(names(collected_guides), guides)\n ],\n gt = gt\n )\n # return guides to be collected\n .subset(collected_guides, guides)\n },\n #' @importFrom grid is.unit unit\n set_sizes = function(self, area, dims,\n panel_widths, panel_heights,\n patches, gt = self$gt) {\n panel_widths <- rep(panel_widths, length.out = dims[2L])\n panel_heights <- rep(panel_heights, length.out = dims[1L])\n if (!is.unit(panel_widths)) panel_widths <- unit(panel_widths, \"null\")\n if (!is.unit(panel_heights)) {\n panel_heights <- unit(panel_heights, \"null\")\n }\n\n # For gtable with fixed aspect ratio -------------\n # if it cannot be fixed and aligned, the strip, axis and labs will be\n # attached into the panel\n # the plot to be fixed must in only one square of the area\n need_fix <- field(area, \"l\") == field(area, \"r\") &\n field(area, \"t\") == field(area, \"b\") &\n vapply(\n patches,\n function(patch) patch$respect(),\n logical(1L),\n USE.NAMES = FALSE\n )\n\n # here we respect the aspect ratio when necessary -----\n # if the width or height is NA, we will guess the panel widths or\n # heights based on the fixed aspect ratio\n guess_widths <- which(is.na(as.numeric(panel_widths)))\n guess_heights <- which(is.na(as.numeric(panel_heights)))\n cols <- field(area, \"l\")\n rows <- field(area, \"t\")\n patch_index <- order(\n # we first set the widths for the fixed plot with heights set by\n # user\n cols %in% guess_widths & !rows %in% guess_heights,\n # we then set the heights for the fixed plot with widths set by user\n !cols %in% guess_widths & rows %in% guess_heights,\n # we set widths and heights for remaning plots\n # based on the number of plots in each row/column in the descending\n # order\n c(table(rows[need_fix]))[as.character(rows)],\n c(table(cols[need_fix]))[as.character(cols)],\n decreasing = TRUE\n )\n respect_dims <- vector(\"list\", length(patches))\n\n # For plot cannot be fixed, we always attach strips, axes and labels\n # into the panel area\n for (i in patch_index) {\n row <- .subset(rows, i)\n col <- .subset(cols, i)\n # we always build a standard gtable layout from the gtable\n panel_sizes <- .subset2(patches, i)$align_panel_sizes(\n panel_width = panel_widths[col],\n panel_height = panel_heights[row]\n )\n panel_widths[col] <- .subset2(panel_sizes, \"width\")\n panel_heights[row] <- .subset2(panel_sizes, \"height\")\n if (.subset2(panel_sizes, \"respect\")) {\n respect_dims[[i]] <- matrix(c(\n (row - 1L) * TABLE_ROWS + TOP_BORDER + 1L,\n (col - 1L) * TABLE_COLS + LEFT_BORDER + 1L\n ), nrow = 1L)\n }\n }\n if (!is.null(respect_dims <- do.call(base::rbind, respect_dims))) {\n respect <- matrix(\n 0L, TABLE_ROWS * dims[1L],\n TABLE_COLS * dims[2L]\n )\n respect[respect_dims] <- 1L\n gt$respect <- respect\n }\n\n # we set the widths/heights with no fixed plots to be 1 null\n if (any(guess_widths <- is.na(as.numeric(panel_widths)))) {\n panel_widths[guess_widths] <- unit(1L, \"null\")\n }\n if (any(guess_heights <- is.na(as.numeric(panel_heights)))) {\n panel_heights[guess_heights] <- unit(1L, \"null\")\n }\n\n # setup sizes for non-panel rows/columns --------------\n sizes <- table_sizes(\n lapply(patches, function(patch) patch$get_sizes()),\n area, dims[2L], dims[1L]\n )\n widths <- .subset2(sizes, \"widths\")\n heights <- .subset2(sizes, \"heights\")\n\n # restore the panel sizes ----------------------------\n width_ind <- seq(LEFT_BORDER + 1L,\n by = TABLE_COLS, length.out = dims[2L]\n )\n height_ind <- seq(TOP_BORDER + 1L,\n by = TABLE_ROWS, length.out = dims[1L]\n )\n widths[width_ind] <- panel_widths\n heights[height_ind] <- panel_heights\n\n # setup the widths and heights -----------------------\n gt$widths <- widths\n gt$heights <- heights\n gt\n },\n\n #' @importFrom gtable gtable_add_grob\n set_grobs = function(self, area, patches, gt = self$gt) {\n widths <- .subset2(gt, \"widths\")\n heights <- .subset2(gt, \"heights\")\n for (i in seq_along(patches)) {\n loc <- vec_slice(area, i)\n # We must align the borders for the gtable grob with the\n # final plot area sizes\n l <- (field(loc, \"l\") - 1L) * TABLE_COLS + 1L\n l_widths <- widths[seq(l, l + LEFT_BORDER - 1L)]\n r <- field(loc, \"r\") * TABLE_COLS\n r_widths <- widths[seq(r - RIGHT_BORDER + 1L, r)]\n t <- (field(loc, \"t\") - 1L) * TABLE_ROWS + 1L\n t_heights <- heights[seq(t, t + TOP_BORDER - 1L)]\n b <- field(loc, \"b\") * TABLE_ROWS\n b_heights <- heights[seq(b - BOTTOM_BORDER + 1L, b)]\n patch <- .subset2(patches, i)\n\n grobs <- patch$split_gt(patch$align_border(\n t = t_heights, l = l_widths,\n b = b_heights, r = r_widths\n ))\n\n # then we add the plot ---------------------------------\n gt <- patch$add_plot(\n gt, .subset2(grobs, \"plot\"), t, l, b, r,\n name = paste(\"plot\", i, sep = \"-\")\n )\n\n # add background grob ----------------------------------\n if (!is.null(bg <- .subset2(grobs, \"bg\"))) {\n # we always add background in the beginning --------\n gt <- patch$add_background(\n gt, bg, t, l, b, r,\n name = paste(\"plot\", i, \"background\", sep = \"-\")\n )\n }\n\n # remove the grob from the patch, we wont' use it anymore\n patch$gt <- NULL\n }\n gt\n },\n attach_guide_list = function(self, guide_list, theme = self$theme,\n panel_pos = find_panel(gt),\n gt = self$gt) {\n if (length(guide_list)) {\n # https://github.com/tidyverse/ggplot2/blob/57ba97fa04dadc6fd73db1904e39a09d57a4fcbe/R/guides-.R#L512\n theme$legend.spacing <- theme$legend.spacing %||% unit(0.5, \"lines\")\n theme$legend.spacing.y <- calc_element(\"legend.spacing.y\", theme)\n theme$legend.spacing.x <- calc_element(\"legend.spacing.x\", theme)\n theme$legend.box.spacing <- calc_element(\n \"legend.box.spacing\", theme\n ) %||% unit(0.2, \"cm\")\n for (guide_pos in names(guide_list)) {\n gt <- self$attach_guides(\n guide_pos = guide_pos,\n guides = .subset2(guide_list, guide_pos),\n theme = theme, panel_pos = panel_pos,\n clip = \"off\", z = 4L, gt = gt\n )\n }\n }\n gt\n },\n #' @importFrom gtable gtable_width gtable_height\n #' @importFrom grid unit.c grobWidth grobHeight\n #' @importFrom ggplot2 find_panel zeroGrob\n attach_guides = function(self, guide_pos, guides, theme,\n panel_pos = find_panel(gt), ...,\n gt = self$gt) {\n guide_box <- assemble_guides(guides, guide_pos, theme = theme)\n name <- sprintf(\"guide-box-collected-%s\", guide_pos)\n if (guide_pos == \"inside\") {\n gt <- gtable_add_grob(\n x = gt,\n grobs = guide_box,\n t = panel_pos$t,\n l = panel_pos$l,\n b = panel_pos$b,\n r = panel_pos$r,\n name = name,\n ...\n )\n return(gt)\n }\n spacing <- .subset2(theme, \"legend.box.spacing\")\n if (guide_pos == \"left\") {\n if (is.gtable(guide_box)) {\n legend_width <- gtable_width(guide_box)\n widths <- unit.c(spacing, legend_width)\n } else {\n legend_width <- grobWidth(guide_box)\n widths <- unit(c(0, 0), \"mm\")\n }\n gt <- gtable_add_grob(\n x = gt,\n grobs = guide_box,\n t = panel_pos$t,\n l = panel_pos$l - 6L,\n b = panel_pos$b,\n name = name,\n ...\n )\n gt$widths[.subset2(panel_pos, \"l\") - 5:6] <- widths\n } else if (guide_pos == \"right\") {\n if (is.gtable(guide_box)) {\n legend_width <- gtable_width(guide_box)\n widths <- unit.c(spacing, legend_width)\n } else {\n legend_width <- grobWidth(guide_box)\n widths <- unit(c(0, 0), \"mm\")\n }\n gt <- gtable_add_grob(\n x = gt,\n grobs = guide_box,\n t = panel_pos$t,\n l = panel_pos$r + 6L,\n b = panel_pos$b,\n name = name,\n ...\n )\n gt$widths[.subset2(panel_pos, \"r\") + 5:6] <- widths\n } else if (guide_pos == \"bottom\") {\n location <- .subset2(theme, \"legend.location\") %||% \"panel\"\n place <- switch(location,\n panel = panel_pos,\n list(l = 1L, r = ncol(gt))\n )\n if (is.gtable(guide_box)) {\n legend_height <- gtable_height(guide_box)\n heights <- unit.c(spacing, legend_height)\n } else {\n legend_height <- grobHeight(guide_box)\n heights <- unit(c(0, 0), \"mm\")\n }\n gt <- gtable_add_grob(\n x = gt,\n grobs = guide_box,\n t = panel_pos$b + 6L,\n l = place$l,\n r = place$r,\n name = name,\n ...\n )\n gt$heights[.subset2(panel_pos, \"b\") + 5:6] <- heights\n } else if (guide_pos == \"top\") {\n location <- .subset2(theme, \"legend.location\") %||% \"panel\"\n place <- switch(location,\n panel = panel_pos,\n list(l = 1L, r = ncol(gt))\n )\n if (is.gtable(guide_box)) {\n legend_height <- gtable_height(guide_box)\n heights <- unit.c(spacing, legend_height)\n } else {\n legend_height <- grobHeight(guide_box)\n heights <- unit(c(0, 0), \"mm\")\n }\n gt <- gtable_add_grob(\n x = gt,\n grobs = guide_box,\n t = panel_pos$t - 6L,\n l = place$l,\n r = place$r,\n name = name,\n ...\n )\n gt$heights[.subset2(panel_pos, \"t\") - 5:6] <- heights\n }\n gt\n },\n\n #' @importFrom rlang is_empty\n free_border = function(self, borders, gt = self$gt,\n patches = self$patches) {\n gt <- self$recurse_lapply(\n function(patch, grob, t, l, b, r) {\n borders <- intersect(borders, c(t, l, b, r))\n if (is_empty(borders)) return(grob) # styler: off\n patch$free_border(borders = borders, gt = grob)\n },\n t = \"top\", l = \"left\", b = \"bottom\", r = \"right\",\n gt = gt, patches = patches\n )\n # for the collected guides, we should also liberate them\n guide_index <- sprintf(\"guide-box-collected-%s\", borders) %in%\n .subset2(.subset2(gt, \"layout\"), \"name\")\n if (any(guide_index)) {\n gt <- PatchGgplot$free_border(\n borders = borders[guide_index], gt = gt\n )\n }\n gt\n },\n align_free_border = function(self, borders,\n t = NULL, l = NULL, b = NULL, r = NULL,\n gt = self$gt, patches = self$patches) {\n gt <- self$recurse_lapply(\n function(patch, grob, t, l, b, r) {\n patch$align_free_border(\n borders = borders,\n t = t, l = l, b = b, r = r, gt = grob\n )\n },\n t = t, l = l, b = b, r = r,\n gt = gt, patches = patches\n )\n PatchGgplot$align_free_border(\n borders = borders,\n t = t, l = l, b = b, r = r, gt = gt\n )\n },\n\n #' @importFrom rlang is_empty\n free_lab = function(self, labs, gt = self$gt, patches = self$patches) {\n self$recurse_lapply(\n function(patch, grob, t, l, b, r) {\n labs <- intersect(labs, c(t, l, b, r))\n if (is_empty(labs)) return(grob) # styler: off\n patch$free_lab(labs = labs, gt = grob)\n },\n t = \"top\", l = \"left\", b = \"bottom\", r = \"right\",\n gt = gt, patches = patches\n )\n },\n # we apply function in each plot gtable in `gt`.\n #' @importFrom rlang is_empty\n recurse_lapply = function(self, .fn, t, l, b, r,\n gt = self$gt, patches = self$patches) {\n # if no plot provided, we'll do nothing\n if (is_empty(patches)) return(gt) # styler: off\n patch_index <- seq_along(patches)\n grobs <- .subset2(gt, \"grobs\")\n layout_index <- match(\n paste0(\"plot-\", patch_index),\n .subset2(.subset2(gt, \"layout\"), \"name\")\n )\n # For each grob, we reuse the method from the patch\n gt$grobs[layout_index] <- .mapply(function(layout_idx, patch_idx) {\n patch <- .subset2(patches, patch_idx)\n borders <- .subset2(patch, \"borders\")\n .fn(\n patch = patch,\n grob = .subset2(grobs, layout_idx),\n t = if (any(borders == \"top\")) t else NULL,\n l = if (any(borders == \"left\")) l else NULL,\n b = if (any(borders == \"bottom\")) b else NULL,\n r = if (any(borders == \"right\")) r else NULL\n )\n }, list(layout_idx = layout_index, patch_idx = patch_index), NULL)\n gt\n }\n)\n\n#' @importFrom grid convertHeight convertWidth unit\ntable_sizes <- function(sizes, area, ncol, nrow) {\n # `null` unit of the panel area will be converted into 0\n # we'll set the panel width and height afterward\n widths <- lapply(sizes, function(size) {\n convertWidth(.subset2(size, \"widths\"), \"mm\", valueOnly = TRUE)\n })\n widths <- vapply(seq_len(ncol * TABLE_COLS), function(i) {\n area_col <- (i - 1L) %/% TABLE_COLS + 1L\n col_loc <- i %% TABLE_COLS\n if (col_loc == 0L) col_loc <- TABLE_COLS\n area_side <- if (col_loc <= LEFT_BORDER + 1L) \"l\" else \"r\"\n idx <- field(area, area_side) == area_col\n if (any(idx)) {\n max(\n vapply(.subset(widths, idx), .subset, numeric(1L), col_loc),\n 0L\n )\n } else {\n 0L\n }\n }, numeric(1L), USE.NAMES = FALSE)\n heights <- lapply(sizes, function(size) {\n convertHeight(.subset2(size, \"heights\"), \"mm\", valueOnly = TRUE)\n })\n heights <- vapply(seq_len(nrow * TABLE_ROWS), function(i) {\n area_row <- recycle_each(i, TABLE_ROWS)\n row_loc <- recycle_whole(i, TABLE_ROWS)\n area_side <- if (row_loc <= TOP_BORDER + 1L) \"t\" else \"b\"\n idx <- field(area, area_side) == area_row\n if (any(idx)) {\n max(\n vapply(\n .subset(heights, idx), .subset, numeric(1L),\n row_loc,\n USE.NAMES = FALSE\n ),\n 0L\n )\n } else {\n 0L\n }\n }, numeric(1L), USE.NAMES = FALSE)\n list(widths = unit(widths, \"mm\"), heights = unit(heights, \"mm\"))\n}\n"], ["/ggalign/R/layout-chain-stack-cross.R", "#' Arrange plots crosswise horizontally or vertically\n#'\n#' @description\n#' `r lifecycle::badge('experimental')`\n#'\n#' The `stack_cross` function is derived from [`stack_discrete()`] and allows\n#' for different layout ordering indices within a single layout.\n#'\n#' Two aliases are provided for convenience:\n#' - `stack_crossv`: A special case of `stack_cross` that sets\n#' `direction = \"v\"` for vertical alignment.\n#' - `stack_crossh`: A special case of `stack_cross` that sets\n#' `direction = \"h\"` for horizontal alignment.\n#'\n#' @param data `r rd_layout_data()`, [`fortify_matrix()`] will be used to\n#' convert the data to a matrix.\n#' @param ... Additional arguments passed to [`fortify_matrix()`].\n#' @inheritParams stack_layout\n#' @seealso [`ggcross()`]\n#' @export\nstack_cross <- function(direction, data = NULL, ...,\n theme = NULL, sizes = NA) {\n UseMethod(\"stack_cross\", data)\n}\n\n#' @export\n#' @rdname stack_cross\nstack_crossv <- function(data = NULL, ...) {\n stack_cross(data = data, direction = \"v\", ...)\n}\n\n#' @export\n#' @rdname stack_cross\nstack_crossh <- function(data = NULL, ...) {\n stack_cross(data = data, direction = \"h\", ...)\n}\n\n#' @include layout-chain-stack-.R\nmethods::setClass(\n \"StackCross\",\n contains = \"StackLayout\",\n # A list of old design\n list(odesign = \"list\", cross_points = \"integer\", break_points = \"integer\"),\n prototype = list(\n odesign = list(),\n cross_points = integer(),\n break_points = integer()\n )\n)\n\n#' @export\nstack_cross.default <- function(direction, data = NULL, ...) {\n ans <- stack_discrete(data = data, direction = direction, ...)\n ans <- methods::as(ans, \"StackCross\")\n ans@name <- \"stack_cross\"\n ans\n}\n\n#' @importFrom grid unit.c\n#' @importFrom rlang is_empty is_string\nresolve_stack_layout.StackCross <- function(stack, schemes, theme,\n extra_design) {\n # check if we should initialize the layout observations\n layout_design <- stack@design\n if (is_discrete_design(layout_design) &&\n is.null(.subset2(layout_design, \"nobs\")) &&\n any(vapply(plot_list, is_cross_plot, logical(1L), USE.NAMES = FALSE))) {\n cli_abort(sprintf(\n \"You must initialize the layout observations to plot the %s\",\n object_name(stack)\n ))\n }\n plot_list <- stack@plot_list\n\n direction <- stack@direction\n position <- .subset2(stack@heatmap, \"position\")\n plot_list <- vec_chop(\n plot_list,\n sizes = diff(c(0L, stack@cross_points, length(plot_list)))\n )\n design_list <- c(stack@odesign, list(layout_design))\n\n # build the stack\n composer <- stack_composer(direction)\n\n # for `free_spaces`, if we have applied it in the whole stack layout we\n # shouln't use it for a single plot. Otherwise, the guide legends collected\n # by the layout will overlap with the axis of the plot in the layout.\n #\n # this occurs in the annotation stack (`position` is not `NULL`).\n stack_spaces <- .subset2(.subset2(schemes, \"scheme_align\"), \"free_spaces\")\n if (is_string(stack_spaces) && !is.null(position)) {\n released_spaces <- stack_spaces\n } else {\n released_spaces <- NULL\n }\n previous_design <- NULL\n for (i in seq_along(plot_list)) {\n plots <- .subset2(plot_list, i)\n\n # prepare design for current group\n design <- .subset2(design_list, i)\n design <- setup_design(design)\n\n if (is_empty(plots)) {\n previous_design <- design\n next\n }\n\n # we remove the plot without actual plot area\n keep <- vapply(plots, function(plot) {\n # we remove objects without plot area\n # Now, only `CraftBox` will contain `NULL`\n !is_craftbox(plot) || !is.null(plot@plot)\n }, logical(1L), USE.NAMES = FALSE)\n plots <- .subset(plots, keep)\n\n if (is_empty(plots)) {\n previous_design <- design\n next\n }\n\n # we reorder the plots based on the `order` slot\n plot_order <- vapply(plots, function(plot) {\n # always keep cross() in the start\n if (is_cross_plot(plot)) {\n 1L\n } else if (is_craftbox(plot)) {\n .subset2(plot@active, \"order\")\n } else {\n .subset2(plot@plot_active, \"order\")\n }\n }, integer(1L), USE.NAMES = FALSE)\n plots <- .subset(plots, make_order(plot_order))\n composer <- stack_composer_add(\n plots,\n stack = stack,\n composer,\n schemes = schemes,\n theme = theme,\n design = design,\n extra_design = extra_design,\n direction = direction,\n position = position,\n released_spaces = released_spaces,\n previous_design = previous_design\n )\n previous_design <- design\n }\n composer\n}\n"], ["/ggalign/R/link.R", "#' Define the links to connect a pair of observations\n#'\n#' @description\n#' This function allows users to define links between a pair of observations,\n#' facilitating the visualization of connections between related data points.\n#'\n#' @param .draw A function used to draw the links. The function must return a\n#' [`grob()`][grid::grob] object. If the function does not return a valid\n#' `grob`, no drawing will occur. The input data for the function should\n#' include a data frame with the coordinates of the pair of observations to\n#' be linked.\n#' @inheritParams .link_draw\n#' @seealso\n#' - [`link_line()`]\n#' - [`.link_draw()`]\n#' @importFrom rlang is_empty inject\n#' @importFrom grid gTree gList\n#' @export\nlink_draw <- function(.draw, ...) {\n if (!is.function(draw <- allow_lambda(.draw))) {\n cli_abort(\"{.arg .draw} must be a function\")\n }\n new_draw <- function(data) {\n ans <- lapply(data, draw)\n ans <- ans[vapply(ans, is.grob, logical(1L), USE.NAMES = FALSE)]\n if (!is_empty(ans)) inject(gList(!!!ans))\n }\n .link_draw(new_draw, ...)\n}\n\n#' @inherit link_draw title\n#'\n#' @description\n#' A base version of [`link_draw()`], optimized for performance. This function\n#' serves as the foundation for building other `link_*` functions that manage\n#' the drawing of links between pairs of observations.\n#'\n#' @param .draw A function used to draw the links. The function must return a\n#' [`grob()`][grid::grob] object. If the function does not return a valid\n#' `grob`, no drawing will occur. The input data for the function should be\n#' a list, where each item is a data frame containing the coordinates of\n#' the pair of observations.\n#' @inheritParams pair_links\n#' @seealso [`link_draw()`]\n#' @export\n.link_draw <- function(.draw, ...) {\n if (override_call(call <- caller_call())) {\n call <- current_call()\n }\n if (!is.function(draw <- allow_lambda(.draw))) {\n cli_abort(\"{.arg .draw} must be a function\", call = call)\n }\n links <- pair_links(...)\n structure(list(draw = draw, links = links), class = \"ggalign_link_draw\")\n}\n\n#' @export\nprint.ggalign_link_draw <- function(x, ...) {\n header <- sprintf(\"<%s>\", vec_ptype_full(x))\n cat(header, sep = \"\\n\")\n obj_print_data(.subset2(x, \"links\"))\n invisible(x)\n}\n\n#' Link the paired observations with a line\n#'\n#' @inheritParams .link_draw\n#' @param .element A [`element_line()`][ggplot2::element_line] object.\n#' Vectorized fields will be recycled to match the total number of groups, or\n#' you can wrap the element with [`I()`] to recycle to match the drawing\n#' groups. The drawing groups typically correspond to the product of the\n#' number of observations from both sides, as each pair of observations will\n#' be linked with a single line.\n#' @importFrom ggplot2 element_line\n#' @export\nlink_line <- function(..., .element = NULL) {\n assert_s3_class(.element, \"element_line\", allow_null = TRUE)\n default <- calc_element(\"ggalign.line\", complete_theme(theme_get()))\n if (is.null(.element)) {\n .element <- default\n } else {\n .element <- ggplot2::merge_element(.element, default)\n }\n ans <- .link_draw(.draw = function(data) {\n data <- lapply(data, function(d) {\n # if the link is only in one side, we do nothing\n if (vec_unique_count(.subset2(d, \".hand\")) < 2L) {\n return(NULL)\n }\n both <- .subset2(vec_split(d, .subset2(d, \".hand\")), \"val\")\n data <- cross_join(.subset2(both, 1L), .subset2(both, 2L))\n data_frame0(\n x = vec_interleave(\n (data$x.x + data$xend.x) / 2L,\n (data$x.y + data$xend.y) / 2L\n ),\n y = vec_interleave(\n (data$y.x + data$yend.x) / 2L,\n (data$y.y + data$yend.y) / 2L\n )\n )\n })\n if (inherits(.element, \"AsIs\")) {\n .element <- element_rep_len(.element,\n length.out = sum(list_sizes(data)) / 2L\n )\n } else {\n .element <- element_rep_len(.element, length.out = length(data))\n .element <- element_vec_rep_each(.element,\n times = list_sizes(data) / 2L\n )\n }\n data <- vec_rbind(!!!data)\n if (vec_size(data)) {\n element_grob(\n .element,\n x = data$x, y = data$y,\n id.lengths = vec_rep(2L, vec_size(data) / 2L),\n default.units = \"native\"\n )\n }\n }, ...)\n add_class(ans, \"ggalign_link_line\")\n}\n\n#' Link the paired observations with a quadrilateral\n#'\n#' @inheritParams .link_draw\n#' @inheritParams mark_tetragon\n#' @export\nlink_tetragon <- function(..., .element = NULL) {\n assert_s3_class(.element, \"element_polygon\", allow_null = TRUE)\n default <- calc_element(\"ggalign.polygon\", complete_theme(theme_get()))\n if (is.null(.element)) {\n .element <- default\n } else {\n .element <- ggplot2::merge_element(.element, default)\n }\n .link_draw(.draw = function(data) {\n data <- lapply(data, function(d) {\n # if the link is only in one side, we do nothing\n if (vec_unique_count(.subset2(d, \".hand\")) < 2L) {\n return(NULL)\n }\n both <- .subset2(vec_split(d, .subset2(d, \".hand\")), \"val\")\n both <- lapply(both, function(link) {\n # find the consecutive groups\n index <- .subset2(link, \"link_index\")\n oindex <- order(index)\n group <- cumsum(c(0L, diff(index[oindex])) != 1L)\n\n # restore the order\n group <- group[order(oindex)]\n\n # split link into groups\n .subset2(vec_split(link, group), \"val\")\n })\n both <- vec_expand_grid(\n hand1 = .subset2(both, 1L),\n hand2 = .subset2(both, 2L)\n )\n ans <- .mapply(function(hand1, hand2) {\n data_frame0(\n x = vec_c(\n min(hand1$x), max(hand1$xend),\n max(hand2$xend), min(hand2$x)\n ),\n y = vec_c(\n min(hand1$y), max(hand1$yend),\n max(hand2$yend), min(hand2$y)\n )\n )\n }, both, NULL)\n vec_rbind(!!!ans)\n })\n if (inherits(.element, \"AsIs\")) {\n .element <- element_rep_len(.element,\n length.out = sum(list_sizes(data)) / 4L\n )\n } else {\n .element <- element_rep_len(.element, length.out = length(data))\n .element <- element_vec_rep_each(.element,\n times = list_sizes(data) / 4L\n )\n }\n data <- vec_rbind(!!!data)\n if (vec_size(data)) {\n element_grob(\n .element,\n x = data$x, y = data$y,\n id.lengths = vec_rep(4L, vec_size(data) / 4L),\n default.units = \"native\"\n )\n }\n }, ...)\n}\n\n# preDraw:\n# - makeContext\n# - pushvpgp\n# - preDrawDetails: by default, do noting\n# makeContent:\n# drawDetails:\n# postDraw:\n# - postDrawDetails: by default, do noting\n# - popgrobvp\n#' @importFrom grid makeContent convertHeight convertWidth gList setChildren\n#' @export\nmakeContent.ggalignLinkTree <- function(x) {\n # Grab viewport information\n width <- convertWidth(unit(1, \"npc\"), \"mm\", valueOnly = TRUE)\n height <- convertHeight(unit(1, \"npc\"), \"mm\", valueOnly = TRUE)\n\n # Grab grob metadata\n full_data1 <- .subset2(x, \"full_data1\")\n full_data2 <- .subset2(x, \"full_data2\")\n direction <- .subset2(x, \"direction\")\n link_index_list <- .subset2(x, \"link_index\")\n data_index_list <- .subset2(x, \"data_index\")\n obs_size <- .subset2(x, \"obs_size\")\n\n # prepare output for current for loop\n coords <- vector(\"list\", 2L)\n names(coords) <- c(\"hand1\", \"hand2\")\n for (link in names(coords)) {\n link_index <- lapply(link_index_list, .subset2, link)\n data_index <- lapply(data_index_list, .subset2, link)\n # early exit and step into next cycle if no link\n if (all(vapply(link_index, is.null, logical(1L), USE.NAMES = FALSE))) {\n coords[link] <- list(link_index)\n next\n }\n full_breaks <- switch(link,\n hand1 = full_data1,\n hand2 = full_data2\n )\n\n spacing <- .subset2(x, switch(link,\n hand1 = \"spacing1\",\n hand2 = \"spacing2\"\n ))\n\n # each value represent an `observation`, for panel space, we use `NA`\n # obs arranged from left to top, and from bottom to top\n points <- unlist(vec_interleave(full_breaks, list(NA)), FALSE, FALSE)\n # remove the last panel space, shouldn't exist\n points <- points[-length(points)]\n sizes <- numeric(length(points))\n n_spacing <- length(full_breaks) - 1L\n\n # then, we define the link grobs\n if (is_horizontal(direction)) { # the link should be in left or right\n spacing <- convertHeight(spacing, \"mm\", valueOnly = TRUE)\n spacing <- scales::rescale(spacing, c(0, 1), from = c(0, height))\n sizes[is.na(points)] <- spacing\n obs_height <- (1 - spacing * n_spacing) / sum(!is.na(points))\n sizes[!is.na(points)] <- obs_height # nobs\n yend <- cumsum(sizes)\n link_x <- switch(link,\n hand1 = 0,\n hand2 = 1\n )\n # by default, the height for each observation is `1`,\n # if we define obs size, we just re-scale it\n removed <- (1 - obs_size) * obs_height\n link_coord <- data_frame0(\n x = link_x, xend = link_x,\n y = yend - sizes + removed / 2L,\n yend = yend - removed / 2L\n )\n link_coord <- vec_slice(link_coord, !is.na(points))\n } else { # the link should be in top or bottom\n spacing <- convertWidth(spacing, \"mm\", valueOnly = TRUE)\n spacing <- scales::rescale(spacing, c(0, 1), from = c(0, width))\n sizes[is.na(points)] <- spacing\n obs_width <- (1 - spacing * n_spacing) / sum(!is.na(points))\n sizes[!is.na(points)] <- obs_width\n xend <- cumsum(sizes)\n link_y <- switch(link,\n hand1 = 1,\n hand2 = 0\n )\n # by default, the width for each observation is `1`,\n # if we define obs size, we just re-scale it\n removed <- (1 - obs_size) * obs_width\n link_coord <- data_frame0(\n x = xend - sizes + removed / 2L,\n xend = xend - removed / 2L,\n y = link_y, yend = link_y\n )\n link_coord <- vec_slice(link_coord, !is.na(points))\n }\n hand <- switch(link,\n hand1 = switch_direction(direction, \"left\", \"top\"),\n hand2 = switch_direction(direction, \"right\", \"bottom\")\n )\n nms <- names(link_index)\n link_panels <- vec_rep_each(names(full_breaks), list_sizes(full_breaks))\n coords[[link]] <- lapply(seq_along(link_index), function(i) {\n l_index <- .subset2(link_index, i)\n if (is.null(l_index)) return(NULL) # styler: off\n d_index <- .subset2(data_index, i)\n link <- vec_slice(link_coord, l_index)\n link$link_id <- nms[i]\n link$link_panel <- reorder(\n vec_slice(link_panels, l_index), l_index,\n order = FALSE\n )\n link$link_index <- l_index\n link$.hand <- hand\n link$.index <- d_index\n link\n })\n }\n\n # hand1 - hand2\n data <- .mapply(vec_rbind, coords, NULL)\n draw <- .subset2(x, \"draw\")\n if (is.grob(grob <- draw(data))) { # wrap single grob to a gList\n grob <- gList(grob)\n }\n if (is.gList(grob)) {\n setChildren(x, grob)\n } else {\n x\n }\n}\n"], ["/ggalign/R/ggplot-geom-subrect.R", "#' Subdivide Rectangles\n#'\n#' @description\n#' These geoms subdivide rectangles with shared borders into a grid. Both geoms\n#' achieve the same result but differ in how the rectangles are parameterized:\n#' - **`geom_subrect()`**: Defines rectangles using their four corners (`xmin`,\n#' `xmax`, `ymin`, `ymax`).\n#' - **`geom_subtile()`**: Defines rectangles using the center (`x`, `y`) and\n#' dimensions (`width`, `height`).\n#'\n#' @param byrow A single boolean value indicates whether we should arrange the\n#' divided rectangles in the row-major order.\n#' @param nrow,ncol A single positive integer specifying the number of rows or\n#' columns in the layout of the subdivided cell. By default, the layout\n#' dimensions are determined automatically using logic similar to\n#' [`facet_wrap()`][ggplot2::facet_wrap].\n#' @param direction `r lifecycle::badge(\"deprecated\")` A string specifying the\n#' arrangement direction:\n#' - `\"h\"`(`horizontal`): Creates a single row (one-row layout).\n#' - `\"v\"`(`vertical`): Creates a single column (one-column layout).\n#' @inheritParams ggplot2::geom_rect\n#' @inheritParams ggplot2::geom_segment\n#' @aesthetics GeomSubrect\n#' @examples\n#' # arranges by row\n#' ggplot(data.frame(value = letters[seq_len(5)])) +\n#' geom_subtile(aes(x = 1, y = 1, fill = value), byrow = TRUE)\n#'\n#' # arranges by column\n#' ggplot(data.frame(value = letters[seq_len(9)])) +\n#' geom_subtile(aes(x = 1, y = 1, fill = value))\n#'\n#' # one-row\n#' ggplot(data.frame(value = letters[seq_len(4)])) +\n#' geom_subtile(aes(x = 1, y = 1, fill = value), nrow = 1)\n#'\n#' # one-column\n#' ggplot(data.frame(value = letters[seq_len(4)])) +\n#' geom_subtile(aes(x = 1, y = 1, fill = value), ncol = 1)\n#'\n#' @importFrom rlang list2\n#' @export\ngeom_subrect <- function(mapping = NULL, data = NULL,\n stat = \"identity\", position = \"identity\",\n ...,\n byrow = FALSE, nrow = NULL, ncol = NULL,\n lineend = \"butt\", linejoin = \"mitre\",\n na.rm = FALSE, show.legend = NA, inherit.aes = TRUE,\n direction = deprecated()) {\n assert_bool(byrow)\n assert_number_whole(nrow, min = 1, allow_null = TRUE)\n assert_number_whole(ncol, min = 1, allow_null = TRUE)\n if (lifecycle::is_present(direction)) {\n lifecycle::deprecate_warn(\n \"1.0.2\",\n \"geom_subtile(direction = )\",\n details = \"Please use the `nrow`/`ncol` argument instead.\"\n )\n if (is_horizontal(direction)) {\n nrow <- 1L\n ncol <- NULL\n } else {\n nrow <- NULL\n ncol <- 1L\n }\n }\n ggplot2::layer(\n data = data,\n mapping = mapping,\n stat = stat,\n geom = GeomSubrect,\n position = position,\n show.legend = show.legend,\n inherit.aes = inherit.aes,\n params = list2(\n byrow = byrow,\n nrow = nrow,\n ncol = ncol,\n lineend = lineend,\n linejoin = linejoin,\n na.rm = na.rm,\n ...\n )\n )\n}\n\n#' @importFrom ggplot2 ggproto ggproto_parent wrap_dims\nGeomSubrect <- ggproto(\n \"GeomSubrect\",\n ggplot2::GeomRect,\n extra_params = c(ggplot2::GeomRect$extra_params, \"byrow\", \"nrow\", \"ncol\"),\n setup_data = function(self, data, params) {\n data <- ggproto_parent(ggplot2::GeomRect, self)$setup_data(data, params)\n indices <- vec_group_loc(data[c(\"xmin\", \"xmax\", \"ymin\", \"ymax\")])\n data_list <- vec_chop(data, indices = .subset2(indices, \"loc\"))\n max_n_tiles <- max(list_sizes(data_list))\n if (max_n_tiles == 1L) return(data) # styler: off\n cli_inform(paste(\n \"{.fn {snake_class(self)}} subdivide tile into a maximal\",\n \"of {max_n_tiles} rectangles\"\n ))\n nrow <- .subset2(params, \"nrow\")\n ncol <- .subset2(params, \"ncol\")\n vec_rbind(!!!lapply(data_list, function(data) {\n n <- vec_size(data)\n if (n == 1L) return(data) # styler: off\n dims <- wrap_dims(n, nrow = nrow, ncol = ncol)\n n_rows <- dims[1L]\n n_cols <- dims[2L]\n one_row <- vec_slice(data, 1L)\n width <- (one_row$xmax - one_row$xmin) / n_cols\n height <- (one_row$ymax - one_row$ymin) / n_rows\n\n if (.subset2(params, \"byrow\")) {\n # we arrange the rectangles from from left to\n # right, then from top to bottom\n data$xmin <- data$xmin +\n vec_rep(width * (seq_len(n_cols) - 1L), n_rows)[\n seq_len(n)\n ]\n data$xmax <- data$xmax -\n vec_rep(width * rev(seq_len(n_cols) - 1L), n_rows)[\n seq_len(n)\n ]\n\n data$ymin <- data$ymin +\n vec_rep_each(height * rev(seq_len(n_rows) - 1L), n_cols)[\n seq_len(n)\n ]\n data$ymax <- data$ymax -\n vec_rep_each(height * (seq_len(n_rows) - 1L), n_cols)[\n seq_len(n)\n ]\n } else {\n # we arrange the rectangles from top to bottom,\n # then from left to right\n data$xmin <- data$xmin +\n vec_rep_each(width * (seq_len(n_cols) - 1L), n_rows)[\n seq_len(n)\n ]\n data$xmax <- data$xmax -\n vec_rep_each(width * rev(seq_len(n_cols) - 1L), n_rows)[\n seq_len(n)\n ]\n\n data$ymin <- data$ymin +\n vec_rep(height * rev(seq_len(n_rows) - 1L), n_cols)[\n seq_len(n)\n ]\n data$ymax <- data$ymax -\n vec_rep(height * (seq_len(n_rows) - 1L), n_cols)[\n seq_len(n)\n ]\n }\n\n data\n }))\n }\n)\n\n#' @aesthetics GeomSubtile\n#' @importFrom rlang list2\n#' @export\n#' @rdname geom_subrect\ngeom_subtile <- function(mapping = NULL, data = NULL,\n stat = \"identity\", position = \"identity\",\n ...,\n byrow = TRUE, nrow = NULL, ncol = NULL,\n lineend = \"butt\", linejoin = \"mitre\",\n na.rm = FALSE, show.legend = NA, inherit.aes = TRUE,\n direction = deprecated()) {\n assert_bool(byrow)\n assert_number_whole(nrow, min = 1, allow_null = TRUE)\n assert_number_whole(ncol, min = 1, allow_null = TRUE)\n if (lifecycle::is_present(direction)) {\n lifecycle::deprecate_warn(\n \"1.0.2\",\n \"geom_subtile(direction = )\",\n details = \"Please use the `nrow`/`ncol` argument instead.\"\n )\n if (is_horizontal(direction)) {\n nrow <- 1L\n ncol <- NULL\n } else {\n nrow <- NULL\n ncol <- 1L\n }\n }\n ggplot2::layer(\n data = data,\n mapping = mapping,\n stat = stat,\n geom = GeomSubtile,\n position = position,\n show.legend = show.legend,\n inherit.aes = inherit.aes,\n params = list2(\n byrow = byrow,\n nrow = nrow,\n ncol = ncol,\n lineend = lineend,\n linejoin = linejoin,\n na.rm = na.rm,\n ...\n )\n )\n}\n\n#' @importFrom ggplot2 ggproto ggproto_parent\nGeomSubtile <- ggproto(\n \"GeomSubtile\",\n ggplot2::GeomTile,\n extra_params = c(ggplot2::GeomRect$extra_params, \"byrow\", \"nrow\", \"ncol\"),\n setup_data = function(self, data, params) {\n data <- ggproto_parent(ggplot2::GeomTile, self)$setup_data(data, params)\n ggproto_parent(GeomSubrect, self)$setup_data(data, params)\n }\n)\n"], ["/ggalign/R/layout-quad-switch.R", "#' Determine the Active Context of Quad-Layout\n#'\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' - `quad_active`: Sets the active context to the `r rd_quad()` itself.\n#' - `quad_anno`: Sets the active context to the specified annotation stack\n#' based on the `position` argument.\n#' - `anno_top`: A special case of `quad_anno` with `position = \"top\"`.\n#' - `anno_left`: A special case of `quad_anno` with `position = \"left\"`.\n#' - `anno_bottom`: A special case of `quad_anno` with `position = \"bottom\"`.\n#' - `anno_right`: A special case of `quad_anno` with `position = \"right\"`.\n#'\n#' @inheritParams quad_layout\n#' @return An object that can be added to `r rd_quad()`.\n#' @export\n#' @rdname quad_active\nquad_active <- function(width = NULL, height = NULL) {\n if (!is.null(width)) width <- check_size(width)\n if (!is.null(height)) height <- check_size(height)\n structure(\n list(width = width, height = height),\n class = c(\"quad_active\", \"quad_switch\")\n )\n}\n\n#' @details\n#' By default, `quad_anno()` attempts to initialize the annotation stack layout\n#' using data from `r rd_quad()`. However, in situations where you want to use\n#' different data for the annotation stack, you can set `initialize = FALSE`\n#' and then provide a custom `stack_layout()`.\n#'\n#' @param position `r rd_quad_position(\"activated\")`.\n#' @param size A numeric value or an [`unit`][grid::unit] object to set the\n#' total `height`/`width` of the annotation stack.\n#' - If `position` is `\"top\"` or `\"bottom\"`, `size` sets the total height of\n#' the annotation.\n#' - If `position` is `\"left\"` or `\"right\"`, `size` sets the total width of the\n#' annotation.\n#' @param free_guides Override the `guides` collection behavior specified in the\n#' `r rd_quad()` for the annotation stack.\n#' @param initialize A boolean indicating whether the annotation stack should be\n#' initialized if it is not already. By default, the annotation stack layout\n#' will attempt to initialize when the data is compatible. If set to `TRUE`, and\n#' the data in `r rd_quad()` is incompatible with the annotation stack, no\n#' data will be used in the stack.\n#' @param what What should get activated in the annotation stack?\n#' `r rd_chain_what()`.\n#' @seealso [`quad_switch()`]\n#' @export\n#' @rdname quad_active\nquad_anno <- function(position, size = NULL, free_guides = waiver(),\n initialize = NULL, what = waiver()) {\n if (is.null(position)) {\n cli_abort(c(\n paste(\n \"{.arg position} must be a single string of\",\n \"{oxford_or(.TLBR)}, not `NULL`\"\n ),\n i = \"Do you want to set the active context to the `quad_layout()` with {.fn quad_active}?\"\n ))\n }\n position <- match.arg(position, .TLBR)\n quad_switch_anno(\n size = size, free_guides = free_guides,\n initialize = initialize, what = what,\n position = position\n )\n}\n\n#' @export\n#' @rdname quad_active\nanno_top <- function(size = NULL, free_guides = waiver(), initialize = NULL,\n what = waiver()) {\n quad_switch_anno(\n size = size, free_guides = free_guides,\n initialize = initialize, what = what,\n position = \"top\"\n )\n}\n\n#' @export\n#' @rdname quad_active\nanno_left <- function(size = NULL, free_guides = waiver(), initialize = NULL,\n what = waiver()) {\n quad_switch_anno(\n size = size, free_guides = free_guides,\n initialize = initialize, what = what,\n position = \"left\"\n )\n}\n\n#' @export\n#' @rdname quad_active\nanno_bottom <- function(size = NULL, free_guides = waiver(), initialize = NULL,\n what = waiver()) {\n quad_switch_anno(\n size = size, free_guides = free_guides,\n initialize = initialize, what = what,\n position = \"bottom\"\n )\n}\n\n#' @export\n#' @rdname quad_active\nanno_right <- function(size = NULL, free_guides = waiver(), initialize = NULL,\n what = waiver()) {\n quad_switch_anno(\n size = size, free_guides = free_guides,\n initialize = initialize, what = what,\n position = \"right\"\n )\n}\n\nquad_switch_anno <- function(position, size, free_guides, initialize, what,\n call = caller_call()) {\n if (!is.null(size)) size <- check_size(size, call = call)\n assert_layout_position(free_guides, call = call)\n if (!is.waive(what)) what <- check_stack_context(what, call = call)\n assert_bool(initialize, allow_null = TRUE)\n structure(\n list(\n position = position, size = size,\n free_guides = free_guides, what = what,\n initialize = initialize\n ),\n class = c(\"quad_anno\", \"quad_switch\")\n )\n}\n\n#' Initialize Quad-Layout Annotation\n#'\n#' @description\n#' `r lifecycle::badge(\"deprecated\")`\n#'\n#' This function was deprecated, you can add `stack_layout()` directly.\n#'\n#' @export\n#' @keywords internal\nquad_init <- function(position, data = waiver(), ...) {\n lifecycle::deprecate_stop(\"0.0.6\", \"quad_init()\", \"stack_layout()\")\n}\n\n#' @inherit quad_active title return\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' `quad_switch()` integrates [`quad_active()`] and [`quad_anno()`] into one\n#' function for ease of use. This function allows you to quickly change the\n#' active context of the [`quad_layout()`] and its annotations.\n#'\n#' `hmanno` is an alias for `quad_switch`, with additional arguments for\n#' backward compatibility\n#'\n#' @param position `r rd_quad_position(\"activated\")`. If `NULL`, it sets the\n#' active context to the `r rd_quad()` itself.\n#' @inheritParams rlang::args_dots_empty\n#' @inheritParams quad_active\n#' @examples\n#' ggheatmap(matrix(rnorm(81), nrow = 9)) +\n#' anno_top() +\n#' align_dendro()\n#' @importFrom ggplot2 waiver\n#' @seealso [`quad_active()`]/[`quad_anno()`]\n#' @export\nquad_switch <- function(position = NULL, size = NULL,\n width = NULL, height = NULL, free_guides = waiver(),\n initialize = NULL, what = waiver()) {\n if (is.null(position)) {\n quad_active(width = width, height = height)\n } else {\n position <- match.arg(position, .TLBR)\n quad_switch_anno(\n size = size,\n free_guides = free_guides, what = what,\n initialize = initialize,\n position = position\n )\n }\n}\n\n#' @inheritParams heatmap_layout\n#' @export\n#' @rdname quad_switch\nhmanno <- quad_switch\n"], ["/ggalign/R/layout-.R", "# Will ensure serialisation includes a link to the ggalign namespace\n# Copied from patchwork\nnamespace_link <- function() NULL\n\n# https://stackoverflow.com/questions/65817557/s3-methods-extending-ggplot2-gg-function\n# Here we use S4 object to override the double dispatch of `+.gg` method\n# TO-DO: use S7\n#' A `Layout` object\n#'\n#' A `Layout` object defines how to place the plots.\n#'\n#' @keywords internal\n# add suffix \"Proto\" to avoid conflict with ggplot2\nmethods::setClass(\"LayoutProto\",\n list(\n active = \"ANY\", # current active plot\n schemes = \"list\", # used to provide global parameters for all plots\n # control the layout, `theme` will also be used by `ggsave`\n titles = \"list\",\n annotation = \"list\", # To-Do add `pacth_titles` for layout\n theme = \"ANY\",\n `_namespace` = \"ANY\"\n ),\n prototype = list(\n active = NULL, titles = list(),\n annotation = list(), theme = NULL,\n `_namespace` = namespace_link\n )\n)\n\n#' @export\nprint.LayoutProto <- print.alignpatches\n\n#' @importFrom grid grid.draw\n#' @exportS3Method\ngrid.draw.LayoutProto <- grid.draw.alignpatches\n\n#' @export\nalignpatch.LayoutProto <- function(x) alignpatch(ggalign_build(x))\n\n#' Print Layout object\n#'\n#' @param object A `r rd_layout()`.\n#' @return The input invisiblely.\n#' @importFrom methods show\n#' @export\n#' @keywords internal\nmethods::setMethod(\"show\", \"LayoutProto\", function(object) {\n print(object)\n})\n\n#' Subset a `Layout` object\n#'\n#' Used by [`ggplot_build`][ggplot2::ggplot_build] and\n#' [`ggsave`][ggplot2::ggsave]\n#'\n#' @param x A `Layout` object\n#' @param name A string of slot name in `Layout` object.\n#' @return The slot value.\n#' @importFrom methods slot\n#' @export\n#' @keywords internal\nmethods::setMethod(\"$\", \"LayoutProto\", function(x, name) {\n slot(x, name)\n})\n\n###########################################################\ndefault_layout <- function(layout) { # setup default value for the layout\n layout@theme <- complete_theme(default_theme() + layout@theme)\n\n # we by default, collect all guides\n layout@schemes$scheme_align[\"guides\"] <- list(\n .subset2(.subset2(layout@schemes, \"scheme_align\"), \"guides\") %|w|% \"tlbr\"\n )\n\n # we by default, use `default_theme()`\n layout@schemes$scheme_theme <- update_scheme(\n .subset2(layout@schemes, \"scheme_theme\"),\n new_scheme_theme(complete_theme(default_theme()))\n )\n layout\n}\n\nis_linear <- function(layout) UseMethod(\"is_linear\")\n\n#' @export\nis_linear.StackLayout <- function(layout) TRUE\n\n#' @export\nis_linear.CircleLayout <- function(layout) FALSE\n\n###########################################################\ninherit_parent_layout_schemes <- function(layout, schemes) {\n if (is.null(schemes)) {\n return(layout@schemes)\n }\n inherit_schemes(layout@schemes, schemes)\n}\n\ninherit_parent_layout_theme <- function(layout, theme, spacing = NULL) {\n if (is.null(theme)) return(layout@theme) # styler: off\n # parent theme, set the global panel spacing,\n # so that every panel aligns well\n if (is.null(layout@theme)) return(theme) # styler: off\n ans <- theme + layout@theme\n if (is.null(spacing)) return(ans) # styler: off\n switch(spacing,\n x = ans + theme(\n panel.spacing.x = calc_element(\"panel.spacing.x\", theme)\n ),\n y = ans + theme(\n panel.spacing.y = calc_element(\"panel.spacing.y\", theme)\n )\n )\n}\n\n############################################################\n#' Get the statistics from the layout\n#'\n#' @param x A `r rd_layout()`.\n#' @inheritParams rlang::args_dots_used\n#' @return The statistics\n#' @export\nggalign_stat <- function(x, ...) {\n UseMethod(\"ggalign_stat\")\n}\n\n#' @param position A string of `r oxford_or(.TLBR)`.\n#' @export\n#' @rdname ggalign_stat\nggalign_stat.QuadLayout <- function(x, position, ...) {\n ggalign_stat(x = slot(x, position), ...)\n}\n\n#' @param what A single number or string of the plot elements in the stack\n#' layout.\n#' @export\n#' @rdname ggalign_stat\nggalign_stat.StackLayout <- function(x, what, ...) {\n plot_list <- x@plot_list\n index <- vec_as_location2(\n what,\n n = length(plot_list),\n names = names(plot_list),\n missing = \"error\"\n )\n ggalign_stat(x = .subset2(plot_list, index), ...)\n}\n\n#' @export\nggalign_stat.CraftBox <- function(x, ...) {\n ggalign_stat(x@craftsman, ...)\n}\n\n#' @export\nggalign_stat.CraftAlign <- function(x, ...) {\n rlang::check_dots_empty()\n .subset2(x, \"statistics\")\n}\n\n#' @export\nggalign_stat.default <- function(x, ...) {\n cli_abort(sprintf(\"no statistics found for %s\", object_name(x)))\n}\n\n#############################################################\n#' Reports whether `x` is layout object\n#'\n#' @param x An object to test.\n#' @return A single boolean value.\n#' @examples\n#' is_layout(ggheatmap(1:10))\n#'\n#' @importFrom methods is\n#' @export\nis_layout <- function(x) is(x, \"LayoutProto\")\n\n#' @examples\n#' # for quad_layout()\n#' is_quad_layout(quad_alignb(1:10))\n#' is_quad_layout(quad_alignh(1:10))\n#' is_quad_layout(quad_alignv(1:10))\n#' is_quad_layout(quad_free(mtcars))\n#'\n#' @export\n#' @rdname is_layout\nis_quad_layout <- function(x) is(x, \"QuadLayout\")\n\n#' @examples\n#' # for stack_layout()\n#' is_stack_layout(stack_discrete(\"h\", 1:10))\n#' is_stack_layout(stack_continuous(\"h\", 1:10))\n#'\n#' @export\n#' @rdname is_layout\nis_stack_layout <- function(x) is(x, \"StackLayout\")\n\n#' @export\n#' @rdname is_layout\nis_stack_cross <- function(x) is(x, \"StackCross\")\n\n#' @export\n#' @rdname is_layout\nis_circle_layout <- function(x) is(x, \"CircleLayout\")\n\n#' @examples\n#' # for heatmap_layout()\n#' is_heatmap_layout(ggheatmap(1:10))\n#' @export\n#' @rdname is_layout\nis_heatmap_layout <- function(x) is(x, \"HeatmapLayout\")\n\n#' @examples\n#' is_ggheatmap(ggheatmap(1:10))\n#' @export\n#' @rdname is_layout\nis_ggheatmap <- is_heatmap_layout\n\nis_cross_layout <- function(x) is_stack_cross(x)\n"], ["/ggalign/R/ggplot-geom-draw.R", "#' Layer with Grid or Function\n#'\n#' Draw a ggplot2 layer using a grob or a function.\n#'\n#' @param draw Either a [grob][grid::grob] object or a function (can be\n#' purrr-style) that accepts at least one argument (a data frame of\n#' transformed coordinates) and returns a [grob][grid::grob].\n#'\n#' @param type A single string of `r oxford_or(c(\"group\", \"panel\"))`, `\"group\"`\n#' draws geoms with `draw_group`, which displays multiple observations as one\n#' geometric object, and `\"panel\"` draws geoms with `draw_panel`, displaying\n#' individual graphical objects for each observation (row). Default:\n#' `\"group\"`.\n#'\n#' @inheritParams ggplot2::layer\n#' @inheritParams ggplot2::geom_point\n#' @details If you want to combine the functionality of multiple geoms, it can\n#' typically be achieved by preparing the data for each geom inside the\n#' `draw_*()` call and sending it off to the different geoms, collecting the\n#' output in a [`grid::gList`] (a list of grobs) for `draw_group()` or a\n#' [`grid::gTree`] (a grob containing multiple child grobs) for\n#' `draw_panel()`.\n#' @seealso \n#' @examples\n#' text <- grid::textGrob(\n#' \"ggdraw\",\n#' x = c(0, 0, 0.5, 1, 1),\n#' y = c(0, 1, 0.5, 0, 1),\n#' hjust = c(0, 0, 0.5, 1, 1),\n#' vjust = c(0, 1, 0.5, 0, 1)\n#' )\n#' ggplot(data.frame(x = 1, y = 2)) +\n#' geom_draw(text)\n#' @importFrom rlang list2 arg_match0\n#' @importFrom ggplot2 ggproto aes\n#' @export\ngeom_draw <- function(draw, mapping = NULL, data = NULL,\n type = \"group\", stat = \"identity\",\n position = \"identity\", ...,\n na.rm = FALSE, show.legend = FALSE, inherit.aes = TRUE) {\n type <- arg_match0(type, c(\"group\", \"panel\"))\n if (!is.grob(draw) && !is.gList(draw)) draw <- rlang::as_function(draw)\n dots <- list2(...)\n ggplot2::layer(\n data = data,\n mapping = mapping,\n stat = stat,\n geom = switch(type,\n panel = ggproto(\n \"GeomDraw\",\n ggplot2::Geom,\n default_aes = GeomGshape$default_aes,\n setup_data = draw_setup_data,\n draw_panel = draw_geom_draw,\n draw_key = ggplot2::draw_key_blank\n ),\n group = ggproto(\n \"GeomDraw\",\n ggplot2::Geom,\n default_aes = GeomGshape$default_aes,\n setup_data = draw_setup_data,\n draw_group = draw_geom_draw,\n draw_key = ggplot2::draw_key_blank\n )\n ),\n position = position,\n show.legend = show.legend,\n inherit.aes = inherit.aes,\n params = c(\n list(na.rm = na.rm, draw = draw, .__draw_dots__ = dots), dots\n )\n )\n}\n\n# GeomTile will respect width and height\ndraw_setup_data <- function(self, data, params) {\n data$x <- data$x %||% 0.5\n data$y <- data$y %||% 0.5\n ggplot2::GeomTile$setup_data(data, params)\n}\n\ndraw_geom_draw <- function(data, panel_params, coord, draw, .__draw_dots__) {\n if (is.function(draw)) {\n data <- coord$transform(data, panel_params)\n # restore colour\n if (!is.null(data$colour) && is.null(data$color)) {\n data$color <- data$colour\n }\n if (!is.null(data$color) && is.null(data$colour)) {\n data$colour <- data$color\n }\n\n # restore width and height\n if (!is.null(data$xmin) && !is.null(data$xmax)) {\n data$width <- data$xmax - data$xmin\n }\n if (!is.null(data$ymin) && !is.null(data$ymax)) {\n data$height <- data$ymax - data$ymin\n }\n }\n make_draw_grob(draw, data, .__draw_dots__)\n}\n\n#' @return A [grob][grid::grob] object.\n#' @importFrom rlang inject\n#' @importFrom methods formalArgs\n#' @importFrom ggplot2 zeroGrob\n#' @keywords internal\n#' @noRd\nmake_draw_grob <- function(draw, data, dots) {\n if (is.function(draw)) {\n args <- formalArgs(draw)\n if (any(args == \"...\")) {\n draw <- inject(draw(!!!data, !!!dots))\n } else {\n draw <- inject(draw(\n !!!.subset(data, intersect(names(data), args)),\n !!!.subset(dots, intersect(\n setdiff(names(dots), names(data)), args\n ))\n ))\n }\n }\n ensure_grob(draw, zeroGrob())\n}\n"], ["/ggalign/R/alignpatch-area.R", "# We are removing the patchwork dependency by defining our own version of\n# patchwork::area, as some desired features won't be merged (see this\n# https://github.com/thomasp85/patchwork/issues/379). Therefore, ggalign will\n# retain `alignpatch-*` scripts.\n\n#' Define the plotting areas in `align_plots`\n#'\n#' @inherit patchwork::area\n#' @details\n#' The grid that the areas are specified in reference to enumerate rows from top\n#' to bottom, and coloumns from left to right. This means that `t` and `l`\n#' should always be less or equal to `b` and `r` respectively. Instead of\n#' specifying area placement with a combination of `area()` calls, it is\n#' possible to instead pass in a single string\n#'\n#' ```\n#' areas <- c(area(1, 1, 2, 1),\n#' area(2, 3, 3, 3))\n#' ```\n#'\n#' is equivalent to\n#'\n#' ```\n#' areas < -\"A##\n#' A#B\n#' ##B\"\n#' ```\n#' @return A `ggalign_area` object.\n#' @examples\n#' p1 <- ggplot(mtcars) +\n#' geom_point(aes(mpg, disp))\n#' p2 <- ggplot(mtcars) +\n#' geom_boxplot(aes(gear, disp, group = gear))\n#' p3 <- ggplot(mtcars) +\n#' geom_bar(aes(gear)) +\n#' facet_wrap(~cyl)\n#'\n#' layout <- c(\n#' area(1, 1),\n#' area(1, 3, 3),\n#' area(3, 1, 3, 2)\n#' )\n#'\n#' # Show the layout to make sure it looks as it should\n#' plot(layout)\n#'\n#' # Apply it to a alignpatches\n#' align_plots(p1, p2, p3, design = layout)\n#' @export\narea <- function(t, l, b = t, r = l) {\n if (missing(t) || missing(l)) {\n one_area <- list(\n t = integer(0L),\n l = integer(0L),\n b = integer(0L),\n r = integer(0L)\n )\n } else {\n one_area <- df_list(\n t = vec_cast(t, integer()),\n l = vec_cast(l, integer()),\n b = vec_cast(b, integer()),\n r = vec_cast(r, integer())\n )\n if (any(.subset2(one_area, \"t\") > .subset2(one_area, \"b\"))) {\n cli_abort(\"{.arg t} must be less than {.arg b}\")\n }\n if (any(.subset2(one_area, \"l\") > .subset2(one_area, \"r\"))) {\n cli_abort(\"{.arg l} must be less than {.arg r}\")\n }\n }\n new_areas(one_area)\n}\n\n# Define a custom S3 class `ggalign_area`, without using S7 directly\n# Patchwork expects traditional S3 classes, and S7 classes are not fully\n# interoperable with patchwork layouts.\nS3_area <- S7::new_S3_class(\"ggalign_area\")\n\nnew_areas <- function(x) new_rcrd(x, class = c(\"ggalign_area\", \"patch_area\"))\n\ncreate_area <- function(ncol, nrow, byrow) {\n mat <- matrix(seq_len(ncol * nrow),\n nrow = nrow, ncol = ncol, byrow = byrow\n )\n ind <- as.vector(mat)\n ind <- match(seq_along(ind), ind)\n area(t = row(mat)[ind], l = col(mat)[ind])\n}\n\n#' @export\nobj_print_data.ggalign_area <- function(x, ...) {\n x <- vec_data(x)\n if (vec_size(x) > 0) {\n x <- vec_set_names(x, paste0(vec_seq_along(x), \": \"))\n print(x = x, ..., quote = FALSE)\n } else {\n cat(\" \", names(x), \"\\n\", sep = \" \")\n }\n}\n\n#' @export\nobj_print_footer.ggalign_area <- function(x, ...) {\n if (vec_size(x) == 0) {\n ncols <- 0\n nrows <- 0\n } else {\n ncols <- max(field(x, \"r\"))\n nrows <- max(field(x, \"b\"))\n }\n cat(\"\\n\\n\")\n}\n\n#' @export\nvec_ptype_abbr.ggalign_area <- function(x, ...) \"areas\"\n\ntrim_area <- function(area) {\n area <- vec_data(area)\n w <- min(.subset2(area, \"l\"), .subset2(area, \"r\"))\n h <- min(.subset2(area, \"t\"), .subset2(area, \"b\"))\n area$l <- .subset2(area, \"l\") - w + 1L\n area$r <- .subset2(area, \"r\") - w + 1L\n area$t <- .subset2(area, \"t\") - h + 1L\n area$b <- .subset2(area, \"b\") - h + 1L\n new_areas(area)\n}\n\nas_areas <- function(x) UseMethod(\"as_areas\")\n\n#' @export\nas_areas.default <- function(x) {\n cli_abort(\"Cannot convert {.obj_type_friendly {x}} into a design area\")\n}\n\n#' @export\nas_areas.NULL <- function(x) NULL\n\n#' @export\nas_areas.ggalign_area <- function(x) x\n\n#' @export\nas_areas.character <- function(x) {\n call <- current_call() # used for message only\n # split into rows\n x <- .subset2(strsplit(x, split = \"\\n\"), 1L)\n x <- lapply(x, trimws)\n if (identical(x[[1L]], \"\")) x[[1L]] <- NULL\n if (identical(x[[length(x)]], \"\")) x[[length(x)]] <- NULL\n x <- lapply(x, function(x) .subset2(strsplit(x, split = \"\"), 1L))\n ncols <- list_sizes(x)\n ncol <- .subset(ncols, 1L)\n if (any(ncols != ncol)) {\n cli_abort(\"character layout must be rectangular\", call = call)\n }\n row <- rep(seq_along(x), each = ncol)\n col <- rep(seq_len(ncol), length(x))\n x <- unlist(x, use.names = FALSE)\n # here, area will be reordered by the levels of `x`\n area_list <- imap(split(seq_along(x), x), function(i, name) {\n if (identical(name, \"#\")) {\n return(area())\n }\n area_rows <- range(row[i])\n area_cols <- range(col[i])\n t <- .subset(area_rows, 1L)\n l <- .subset(area_cols, 1L)\n b <- .subset(area_rows, 2L)\n r <- .subset(area_cols, 2L)\n if (!all(x[row >= t & row <= b & col >= l & col <= r] ==\n x[.subset(i, 1L)])) {\n cli_abort(\"Patch areas must be rectangular\", call = call)\n }\n new_areas(list(t = t, l = l, b = b, r = r))\n })\n vec_c(!!!vec_set_names(area_list, NULL))\n}\n\n# For area from patchwork\n#' @export\nas_areas.patch_area <- function(x) add_class(x, \"ggalign_area\")\n\n#' @importFrom grid unit\n#' @importFrom ggplot2 aes margin theme ggplot\n#' @importFrom utils packageVersion\n#' @export\nplot.ggalign_area <- function(x, ...) {\n data <- vec_data(x)\n data$l <- data$l - 0.45\n data$r <- data$r + 0.45\n data$t <- data$t - 0.45\n data$b <- data$b + 0.45\n data$name <- as.factor(vec_seq_along(x))\n b_fun <- function(lim) {\n if (lim[1] < lim[2]) {\n lim <- seq(floor(lim[1]), ceiling(lim[2]), by = 1)\n } else {\n lim <- seq(ceiling(lim[1]), floor(lim[2]), by = -1)\n }\n lim[-c(1, length(lim))]\n }\n ggplot(data) +\n ggplot2::geom_rect(aes(\n xmin = .data$l, xmax = .data$r,\n ymin = .data$t, ymax = .data$b, fill = .data$name\n ), alpha = 0.3) +\n ggplot2::scale_y_reverse(breaks = b_fun, expand = c(0, 0.04)) +\n ggplot2::scale_x_continuous(\n breaks = b_fun, expand = c(0, 0.04), position = \"top\"\n ) +\n ggplot2::labs(fill = \"Patch\") +\n ggplot2::theme_void() +\n theme(\n panel.grid.minor = if (packageVersion(\"ggplot2\") >= \"3.4.0\") {\n ggplot2::element_line(linewidth = 0.5, colour = \"grey\")\n } else {\n ggplot2::element_line(size = 0.5, colour = \"grey\")\n },\n axis.text = ggplot2::element_text(),\n axis.ticks.length = unit(3, \"mm\"),\n plot.margin = margin(10, 10, 10, 10)\n )\n}\n"], ["/ggalign/R/pair-links.R", "#' Helper function to create pairs of observation groups\n#'\n#' @description\n#' [`ggmark()`] and [`cross_link()`] allow users to add links between\n#' observations. These functions help define the linked observations. The\n#' selected pairs will either be linked together, or each group in the pair will\n#' be linked separately to the same plot area.\n#'\n#' - `pair_links`: Helper function to create pairs of observation groups.\n#' - `range_link`: Helper function to create a range of observations.\n#'\n#' @param ... <[dyn-dots][rlang::dyn-dots]> A list of formulas, where each side\n#' of the formula should be an `integer` or `character` index of the original\n#' data, or a `range_link()` object defining the linked observations. Use\n#' `NULL` to indicate no link on that side. You can also combine these by\n#' wrapping them into a single `list()`. If only the left-hand side of the\n#' formula exists, you can input it directly. For integer indices, wrap them\n#' with [`I()`] to use the ordering from the layout. You can also use\n#' [`waiver()`][ggplot2::waiver()] to inherit values from the other group.\n#' @param .handle_missing A string of `r oxford_or(c(\"error\", \"remove\"))`\n#' indicates the action for handling missing observations.\n#' @param .reorder A string of `r oxford_or(c(\"hand1\", \"hand2\"))` indicating\n#' whether to reorder the input links to follow the specified layout ordering.\n#' @examples\n#' x <- pair_links(\n#' # group on the left hand only\n#' c(\"a\", \"b\"),\n#' # normally, integer index will be interpreted as the index of the\n#' # origianl data\n#' 1:2,\n#' # wrapped with `I()` indicate` the integer index is ordering of the\n#' # layout\n#' I(1:2),\n#' range_link(1, 6),\n#' range_link(\"a\", \"b\"),\n#' # group on the right hand only\n#' ~ 1:2,\n#' ~ c(\"a\", \"b\"),\n#' ~ range_link(1, 6),\n#' # group on the both side\n#' range_link(1, 6) ~ c(\"a\", \"b\"),\n#' # waiver() indicates the right hand is the same of the left hand\n#' range_link(1, 6) ~ waiver(),\n#' # the same for the left hand\n#' waiver() ~ 1:2,\n#' ~NULL # an empty link\n#' )\n#' x\n#'\n#' # we can modify it as usual list\n#' x[[1]] <- NULL # remove the first link\n#' x$a <- ~LETTERS\n#' x\n#'\n#' # modify with a list\n#' x[1:2] <- list(~ c(\"a\", \"b\"), ~ range_link(\"a\", \"b\"))\n#' x\n#' @export\npair_links <- function(..., .handle_missing = \"error\", .reorder = NULL) {\n .handle_missing <- arg_match0(.handle_missing, c(\"error\", \"remove\"))\n if (!is.null(.reorder)) {\n .reorder <- arg_match0(.reorder, c(\"hand1\", \"hand2\"))\n }\n pairs <- rlang::dots_list(..., .ignore_empty = \"all\", .named = NULL)\n new_pair_links(\n lapply(pairs, as_pair_link, x_arg = \"...\", call = current_call()),\n handle_missing = .handle_missing, reorder = .reorder\n )\n}\n\nnew_pair_links <- function(x = list(), ..., class = character()) {\n new_vctr(x, ..., class = c(class, \"ggalign_pair_links\"))\n}\n\n#' @export\nobj_print_header.ggalign_pair_links <- function(x, ...) {\n cat(\"<\", vec_ptype_full(x), \">\", \"\\n\", sep = \"\")\n cat(\n sprintf(\n \"A total of %d pair%s of link groups\",\n vec_size(x), if (vec_size(x) > 1L) \"s\" else \"\"\n ),\n \"\\n\",\n sep = \"\"\n )\n invisible(x)\n}\n\n#' @export\nobj_print_data.ggalign_pair_links <- function(x, ...) {\n if (vec_size(x) > 0L) {\n hand1 <- vapply(x, function(hand) {\n deparse_link(hand, ..., hand = \"hand1\")\n }, character(1L), USE.NAMES = FALSE)\n hand2 <- vapply(x, function(hand) {\n deparse_link(hand, ..., hand = \"hand2\")\n }, character(1L), USE.NAMES = FALSE)\n nms <- c(\"\", paste0(names_or_index(x), \": \"))\n nms <- format(nms, justify = \"right\")\n empty <- character(vec_size(hand2))\n empty[hand1 == \"\" & hand2 == \"\"] <- \" \"\n empty <- format(c(\"\", empty), justify = \"left\")\n hand1 <- format(c(\"hand1\", hand1), justify = \"right\")\n hand2 <- format(c(\"hand2\", hand2), justify = \"left\")\n cat(\"\\n\")\n cat(paste0(\" \", nms, hand1, \" ~ \", hand2, empty), sep = \"\\n\")\n cat(\"\\n\")\n }\n invisible(x)\n}\n\n#' @export\nobj_print_footer.ggalign_pair_links <- function(x, ...) {\n NextMethod()\n # `lengths`: will call `length.ggalign_pair_link()` method\n n <- sum(lengths(x, use.names = FALSE))\n cat(\n sprintf(\n \"A total of %d link group%s\", n,\n if (n > 1L) \"s\" else \"\"\n ),\n \"\\n\",\n sep = \"\"\n )\n invisible(x)\n}\n\n#' @export\n`[<-.ggalign_pair_links` <- function(x, i, value) {\n value <- lapply(value, as_pair_link, x_arg = \"value\", call = current_call())\n NextMethod()\n}\n\n#' @export\n`[[<-.ggalign_pair_links` <- function(x, i, value) {\n # let `NULL` to remove the link\n if (!is.null(value)) value <- as_pair_link(value)\n NextMethod()\n}\n\n#' @export\n`$<-.ggalign_pair_links` <- function(x, i, value) {\n # let `NULL` to remove the link\n if (!is.null(value)) value <- as_pair_link(value)\n NextMethod()\n}\n\n#' @export\nvec_ptype2.ggalign_pair_links.list <- function(x, y, ...) {\n x\n}\n\n#' @export\nvec_ptype2.list.ggalign_pair_links <- function(x, y, ...) {\n y\n}\n\n#' @export\nvec_cast.ggalign_pair_links.list <- function(x, to, ...,\n x_arg = caller_arg(x),\n to_arg = \"\",\n call = caller_env()) {\n new_pair_links(lapply(x, as_pair_link, x_arg = x_arg, call = call))\n}\n\n#########################################################\n#' @param point1,point2 A single integer or character index, defining the lower\n#' and higher bounds of the range. For integer indices, wrap them with [`I()`]\n#' to indicate the ordered index by the layout.\n#' @export\n#' @rdname pair_links\nrange_link <- function(point1, point2) {\n if (!is_scalar(point1) ||\n (!is.character(point1) && !is.numeric(point1))) {\n cli_abort(\"{.arg point1} must be a single numeric or character index\")\n }\n if (!is_scalar(point2) ||\n (!is.character(point2) && !is.numeric(point2))) {\n cli_abort(\"{.arg point2} must be a single numeric or character index\")\n }\n point1 <- as_obs_link(point1)\n point2 <- as_obs_link(point2)\n structure(list(point1 = point1, point2 = point2),\n class = \"ggalign_range_link\"\n )\n}\n\nis_range_link <- function(x) inherits(x, \"ggalign_range_link\")\n\n########################################################\nnew_pair_link <- function(hand1 = NULL, hand2 = NULL,\n ..., class = character()) {\n structure(\n .Data = list(hand1 = hand1, hand2 = hand2),\n ...,\n class = c(class, \"ggalign_pair_link\")\n )\n}\n\n#' @export\nvec_proxy.ggalign_pair_link <- function(x, ...) x\n\n#' @export\nprint.ggalign_pair_link <- function(x, ...) obj_print(x, ...)\n\n#' @export\nobj_print_header.ggalign_pair_link <- function(x, ...) {\n cat(sprintf(\"<%s>\", vec_ptype_full(x)), \"\\n\", sep = \"\")\n invisible(x)\n}\n\n#' @export\nobj_print_data.ggalign_pair_link <- function(x, ...) {\n if (length(x) > 0L) {\n cat(c(\n sprintf(\" hand1: %s\", deparse_link(.subset2(x, \"hand1\"), ...)),\n sprintf(\" hand2: %s\", deparse_link(.subset2(x, \"hand2\"), ...))\n ), sep = \"\\n\")\n }\n invisible(x)\n}\n\n#' @param x A `ggalign_pair_link` object.\n#' @noRd\n#' @export\nlength.ggalign_pair_link <- function(x) {\n sum(!vapply(x, is.null, logical(1L), USE.NAMES = FALSE))\n}\n\n##################################################\n#' @export\nvec_ptype2.ggalign_pair_link.ggalign_pair_link <- function(x, y, ...) {\n x\n}\n\n#' @export\nvec_ptype2.ggalign_pair_link.NULL <- function(x, y, ...) {\n x\n}\n\n#' @export\nvec_ptype2.NULL.ggalign_pair_link <- function(x, y, ...) {\n y\n}\n\n#' @export\nvec_ptype2.ggalign_pair_link.numeric <- function(x, y, ...) {\n x\n}\n\n#' @export\nvec_ptype2.numeric.ggalign_pair_link <- function(x, y, ...) {\n y\n}\n\n#' @export\nvec_ptype2.ggalign_pair_link.integer <- function(x, y, ...) {\n x\n}\n\n#' @export\nvec_ptype2.integer.ggalign_pair_link <- function(x, y, ...) {\n y\n}\n\n#' @export\nvec_ptype2.ggalign_pair_link.double <- function(x, y, ...) {\n x\n}\n\n#' @export\nvec_ptype2.double.ggalign_pair_link <- function(x, y, ...) {\n y\n}\n\n#' @export\nvec_ptype2.ggalign_pair_link.character <- function(x, y, ...) {\n x\n}\n\n#' @export\nvec_ptype2.character.ggalign_pair_link <- function(x, y, ...) {\n y\n}\n\n#' @export\nvec_ptype2.ggalign_pair_link.formula <- function(x, y, ...) {\n x\n}\n\n#' @export\nvec_ptype2.formula.ggalign_pair_link <- function(x, y, ...) {\n y\n}\n\n#' @export\nvec_ptype2.ggalign_pair_link.waiver <- function(x, y, ...) {\n x\n}\n\n#' @export\nvec_ptype2.waiver.ggalign_pair_link <- function(x, y, ...) {\n y\n}\n\n#' @export\nvec_ptype2.ggalign_pair_link.ggalign_range_link <- function(x, y, ...) {\n x\n}\n\n#' @export\nvec_ptype2.ggalign_range_link.ggalign_pair_link <- function(x, y, ...) {\n y\n}\n\n#' @export\nvec_ptype2.ggalign_pair_link.AsIs <- function(x, y, ...) {\n vec_ptype2(x, remove_class(y, \"AsIs\"), ...)\n}\n\n#' @export\nvec_ptype2.AsIs.ggalign_pair_link <- function(x, y, ...) {\n vec_ptype2(remove_class(x, \"AsIs\"), y, ...)\n}\n\n#' @export\nvec_ptype2.ggalign_pair_link.list <- function(x, y, ...) {\n x\n}\n\n#' @export\nvec_ptype2.list.ggalign_pair_link <- function(x, y, ...) {\n y\n}\n\n#############################################################\n#' @export\nvec_cast.ggalign_pair_link.numeric <- function(x, to, ...,\n x_arg = caller_arg(x),\n to_arg = \"\",\n call = caller_env()) {\n new_pair_link(as_obs_link(x, arg = x_arg, call = call))\n}\n\n#' @export\nvec_cast.ggalign_pair_link.double <- vec_cast.ggalign_pair_link.numeric\n\n#' @export\nvec_cast.ggalign_pair_link.integer <- vec_cast.ggalign_pair_link.numeric\n\n#' @export\nvec_cast.ggalign_pair_link.character <- vec_cast.ggalign_pair_link.numeric\n\n#' @export\nvec_cast.ggalign_pair_link.ggalign_range_link <-\n vec_cast.ggalign_pair_link.integer\n\n#' @export\nvec_cast.ggalign_pair_link.list <- vec_cast.ggalign_pair_link.numeric\n\n#' @export\nvec_cast.ggalign_pair_link.AsIs <- function(x, to, ...,\n x_arg = caller_arg(x),\n to_arg = \"\",\n call = caller_env()) {\n I(vec_cast(\n remove_class(x, \"AsIs\"),\n to = to, ...,\n x_arg = x_arg, call = call\n ))\n}\n\n#' @export\nvec_cast.ggalign_pair_link.formula <- function(x, to, ...,\n x_arg = caller_arg(x),\n to_arg = \"\",\n call = caller_env()) {\n hand1 <- rlang::eval_tidy(rlang::f_lhs(x), env = rlang::f_env(x))\n hand1 <- as_obs_link(hand1, arg = x_arg, call = call)\n hand2 <- rlang::eval_tidy(rlang::f_rhs(x), env = rlang::f_env(x))\n hand2 <- as_obs_link(hand2, arg = x_arg, call = call)\n new_pair_link(hand1, hand2)\n}\n\nas_pair_link <- function(x, ...) {\n if (is.null(x)) { # vec_cast() cannot convert `NULL`\n new_pair_link()\n } else {\n vec_cast(x, to = new_pair_link(), ...)\n }\n}\n\n########################################################\nas_obs_link <- function(x, ..., arg = caller_arg(x), call = caller_env()) {\n UseMethod(\"as_obs_link\")\n}\n\n#' @export\nas_obs_link.NULL <- function(x, ...) x\n\n#' @export\nas_obs_link.AsIs <- function(x, ...) {\n I(as_obs_link(remove_class(x, \"AsIs\"), ...))\n}\n\n#' @export\nas_obs_link.numeric <- function(x, ..., arg = caller_arg(x),\n call = caller_env()) {\n vec_cast(x, integer(), x_arg = arg, call = call)\n}\n\n#' @export\nas_obs_link.integer <- as_obs_link.NULL\n\n#' @export\nas_obs_link.double <- as_obs_link.numeric\n\n#' @export\nas_obs_link.character <- function(x, ..., arg = caller_arg(x),\n call = caller_env()) {\n if (any(x == \"\")) {\n cli_abort(\"empty string is not allowed\", call = call)\n }\n x\n}\n\n#' @export\nas_obs_link.waiver <- as_obs_link.NULL\n\n#' @export\nas_obs_link.list <- function(x, ..., arg = caller_arg(x),\n call = caller_env()) {\n x <- x[!vapply(x, is.null, logical(1L), USE.NAMES = FALSE)]\n if (is_empty(x)) return(NULL) # styler: off\n lapply(x, as_obs_link, arg = arg, call = call)\n}\n\n#' @export\nas_obs_link.ggalign_range_link <- as_obs_link.NULL\n\n#' @export\nas_obs_link.default <- function(x, ..., arg = caller_arg(x),\n call = caller_env()) {\n stop_incompatible_cast(\n x, new_pair_link(),\n x_arg = arg, to_arg = \"\",\n call = call\n )\n}\n\n#' @export\nprint.ggalign_range_link <- function(x, ...) {\n cat(deparse_link(x))\n invisible(x)\n}\n\n###########################################################\n#' @return A single string\n#' @noRd\ndeparse_link <- function(x, ...) deparse_link2(x, ...) %||% \"\"\n\n#' @return A single string or `NULL`\n#' @noRd\ndeparse_link2 <- function(x, ...) UseMethod(\"deparse_link2\")\n\n# Basic object\n#' @export\ndeparse_link2.integer <- function(x, trunc = 3L, head = trunc - 1L,\n tail = 1L, ...) {\n l <- length(x)\n ans <- paste(\n deparse(x, control = c(\"keepNA\", \"niceNames\", \"showAttributes\")),\n collapse = \" \"\n )\n if (l > trunc && startsWith(ans, \"c\")) {\n ans <- sprintf(\"c(%s)\", paste(c(\n x[seq_len(head)], \"...\", x[seq.int(l - tail + 1L, l)]\n ), collapse = \", \"))\n }\n ans\n}\n\n#' @export\ndeparse_link2.character <- function(x, trunc = 3L, head = trunc - 1L,\n tail = 1L, ...) {\n l <- length(x)\n if (l <= trunc) {\n ans <- paste(deparse(x), collapse = \" \")\n } else {\n ans <- sprintf(\"c(%s)\", paste(c(\n x[seq_len(head)], \"...\", x[seq.int(l - tail + 1L, l)]\n ), collapse = \", \"))\n }\n ans\n}\n\n#' @export\ndeparse_link2.waiver <- function(x, ...) \"waiver()\"\n\n#' @export\ndeparse_link2.NULL <- function(x, ...) NULL\n\n# To allow `I()` to be used to the whole formula, we must define the method for\n# this, though `ggalign_pair_link` shouldn't be considered as an observation\n#' @export\ndeparse_link2.ggalign_pair_link <- function(x, ..., hand) {\n deparse_link2(.subset2(x, hand), ...)\n}\n\n#' @export\ndeparse_link2.AsIs <- function(x, ...) {\n ans <- deparse_link2(remove_class(x, \"AsIs\"), ...)\n if (!is.null(ans)) ans <- sprintf(\"I(%s)\", ans)\n ans\n}\n\n# Recurse version\n#' @export\ndeparse_link2.ggalign_range_link <- function(x, ...) {\n sprintf(\n \"range_link(%s, %s)\",\n deparse_link(.subset2(x, \"point1\"), ...),\n deparse_link(.subset2(x, \"point2\"), ...)\n )\n}\n\n#' @export\ndeparse_link2.list <- function(x, trunc = 3L, head = trunc - 1L,\n tail = 1L, ...) {\n l <- length(x)\n if (l <= trunc) {\n ans <- vapply(x, deparse_link, character(1L), ...,\n trunc = trunc, head = head, tail = tail,\n USE.NAMES = FALSE\n )\n } else {\n ans <- c(\n vapply(x[seq_len(head)],\n deparse_link, character(1L), ...,\n trunc = trunc, head = head, tail = tail,\n USE.NAMES = FALSE\n ),\n \"...\",\n vapply(x[seq.int(l - tail + 1L, l)],\n deparse_link, character(1L), ...,\n trunc = trunc, head = head, tail = tail,\n USE.NAMES = FALSE\n )\n )\n }\n sprintf(\"list(%s)\", paste(ans, collapse = \", \"))\n}\n\n###################################################\nmake_links_data <- function(links, design1, design2,\n labels1, labels2) {\n link_index_list <- lapply(\n links, make_pair_link_index,\n design1 = design1, design2 = design2,\n labels1 = labels1, labels2 = labels2,\n handle_missing = attr(links, \"handle_missing\")\n )\n names(link_index_list) <- names_or_index(links)\n if (!is.null(reorder <- attr(links, \"reorder\"))) {\n index <- vapply(link_index_list, function(link_index) {\n if (is.null(link_index) ||\n is.null(index <- .subset2(link_index, reorder))) {\n NA_integer_\n } else {\n vec_slice(index, 1L)\n }\n }, integer(1L), USE.NAMES = FALSE)\n link_index_list <- link_index_list[order(index)]\n }\n link_index_list\n}\n\nmake_pair_link_index <- function(pair_link, design1, design2,\n labels1, labels2, handle_missing) {\n input1 <- .subset2(pair_link, 1L)\n input2 <- .subset2(pair_link, 2L)\n\n # make the data\n hand1 <- make_link_index(input1,\n design = design1, labels = labels1,\n other = input2, data_index = !inherits(pair_link, \"AsIs\"),\n handle_missing = handle_missing\n )\n hand2 <- make_link_index(input2,\n design = design2, labels = labels2,\n other = input1, data_index = !inherits(pair_link, \"AsIs\"),\n handle_missing = handle_missing\n )\n if (is.null(hand1) && is.null(hand2)) {\n return(NULL)\n }\n list(hand1 = hand1, hand2 = hand2)\n}\n\nmake_link_index <- function(link, design, labels, other, data_index,\n handle_missing, arg = caller_arg(link),\n call = caller_call()) {\n link <- link_to_location(\n link,\n n = .subset2(design, \"nobs\"),\n labels = labels,\n index = .subset2(design, \"index\"),\n other = other,\n data_index = data_index,\n handle_missing = handle_missing,\n arg = arg, call = call\n )\n if (is_empty(link)) {\n return(NULL)\n }\n # always use integer, otherwise, will cause error when drawing\n # due to loss of precision, I don't know why, it should be integer already?\n vec_unique(vec_cast(link, integer()))\n}\n\nlink_to_location <- function(x, ...) UseMethod(\"link_to_location\")\n\n#' @export\nlink_to_location.AsIs <- function(x, ..., data_index) {\n link_to_location(remove_class(x, \"AsIs\"), ..., data_index = FALSE)\n}\n\n#' @export\nlink_to_location.character <- function(x, ..., n, labels, index, handle_missing,\n arg = caller_arg(x),\n call = caller_call()) {\n if (identical(handle_missing, \"remove\") && !is.null(labels)) {\n x <- x[x %in% labels]\n }\n ans <- vec_as_location(x, n = n, names = labels, arg = arg, call = call)\n match(ans, index) # character always match the original data\n}\n\n#' @export\nlink_to_location.integer <- function(x, ..., n, index, data_index,\n handle_missing, arg = caller_arg(x),\n call = caller_call()) {\n ans <- num_as_location(x,\n n = n,\n arg = arg, call = call,\n negative = \"error\",\n zero = \"error\",\n oob = handle_missing\n )\n # integer index by default match the original data\n if (isTRUE(data_index)) match(ans, index) else ans\n}\n\n#' @export\nlink_to_location.ggalign_range_link <- function(x, ..., arg = caller_arg(x),\n call = caller_call()) {\n point1 <- link_to_location(\n .subset2(x, \"point1\"),\n ...,\n arg = \"point1\",\n call = quote(range_link())\n )\n point2 <- link_to_location(\n .subset2(x, \"point2\"),\n ...,\n arg = \"point2\",\n call = quote(range_link())\n )\n point1:point2\n}\n\n#' @export\nlink_to_location.list <- function(x, ...) {\n unlist(lapply(x, link_to_location, ...), FALSE, FALSE)\n}\n\n#' @export\nlink_to_location.waiver <- function(x, ..., other) {\n link_to_location(other %|w|% NULL, ...)\n}\n\n#' @export\nlink_to_location.NULL <- function(x, ...) NULL\n"], ["/ggalign/R/layout-chain-stack-build.R", "#' @export\nggalign_build.StackLayout <- function(x) {\n x <- default_layout(x)\n (stack_build(x) %||% align_plots(theme = x@theme)) +\n layout_title(\n title = .subset2(x@titles, \"title\"),\n subtitle = .subset2(x@titles, \"subtitle\"),\n caption = .subset2(x@titles, \"caption\")\n )\n}\n\n#' @param schemes,theme Parameters from parent layout\n#' @param extra_design layout parameters of the axis vertically with the stack.\n#' @noRd\nstack_build <- function(stack, schemes = NULL, theme = NULL,\n extra_design = NULL) {\n if (is_empty(stack@plot_list)) {\n return(NULL)\n }\n direction <- stack@direction\n position <- .subset2(stack@heatmap, \"position\")\n schemes <- inherit_parent_layout_schemes(stack, schemes)\n\n if (is_horizontal(direction)) {\n spacing <- \"y\"\n # for horizontal stack, we by default remove top and bottom spaces\n # if (!is.null(position)) {\n # schemes$scheme_align[\"free_spaces\"] <- list(\n # .subset2(schemes$scheme_align, \"free_spaces\") %|w|% \"tb\"\n # )\n # }\n } else {\n spacing <- \"x\"\n # for vertical stack, we by default remove left and right spaces\n # if (!is.null(position)) {\n # schemes$scheme_align[\"free_spaces\"] <- list(\n # .subset2(schemes$scheme_align, \"free_spaces\") %|w|% \"lr\"\n # )\n # }\n }\n theme <- inherit_parent_layout_theme(stack, theme, spacing = spacing)\n composer <- resolve_stack_layout(stack, schemes, theme, extra_design)\n if (is_empty(plots <- .subset2(composer, \"plots\"))) {\n return(NULL)\n }\n\n # arrange plots\n if (is.null(position)) { # for stack layout\n # sizes should be of length 3\n sizes <- stack@sizes\n # recycle the sizes when necessary\n if (length(sizes) == 1L) sizes <- rep(sizes, length.out = 3L)\n sizes <- sizes[\n c(\n .subset2(composer, \"left_or_top\"),\n TRUE,\n .subset2(composer, \"right_or_bottom\")\n )\n ]\n } else { # for the heatmap annotation\n sizes <- NA\n }\n plot <- align_plots(\n !!!plots,\n design = area(\n .subset2(composer, \"t\"),\n .subset2(composer, \"l\"),\n .subset2(composer, \"b\"),\n .subset2(composer, \"r\")\n ),\n widths = switch_direction(\n direction,\n do.call(unit.c, .subset2(composer, \"sizes\")),\n sizes\n ),\n heights = switch_direction(\n direction,\n sizes,\n do.call(unit.c, .subset2(composer, \"sizes\"))\n ),\n guides = .subset2(.subset2(schemes, \"scheme_align\"), \"guides\"),\n theme = stack@theme\n )\n\n # for annotation, we should always make it next to the main body\n if (is.null(position)) {\n return(plot)\n }\n plot <- free_vp(\n plot,\n x = switch(position,\n left = 1L,\n right = 0L,\n 0.5\n ),\n y = switch(position,\n top = 0L,\n bottom = 1L,\n 0.5\n ),\n just = switch(position,\n top = \"bottom\",\n left = \"right\",\n bottom = \"top\",\n right = \"left\"\n )\n )\n\n # whether we should override the `guides` collection for the whole\n # annotation stack\n free_guides <- .subset2(stack@heatmap, \"free_guides\")\n if (!is.waive(free_guides)) plot <- free_guide(plot, free_guides)\n # we also apply the `free_spaces` for the whole annotation stack\n free_spaces <- .subset2(\n .subset2(schemes, \"scheme_align\"), \"free_spaces\"\n ) %|w|% NULL\n if (!is.null(free_spaces)) {\n plot <- free_space(free_border(plot, free_spaces), free_spaces)\n }\n plot\n}\n\n#' @param schemes,theme Parameters for current stack, which have inherited\n#' parameters from the parent.\n#' @noRd\nresolve_stack_layout <- function(stack, schemes, theme, extra_design) {\n UseMethod(\"resolve_stack_layout\")\n}\n\n#' @export\nresolve_stack_layout.StackLayout <- function(stack, schemes, theme,\n extra_design) {\n plot_list <- stack@plot_list\n direction <- stack@direction\n position <- .subset2(stack@heatmap, \"position\")\n\n # we remove the plot without actual plot area\n keep <- vapply(plot_list, function(plot) {\n # we remove objects without plot area\n # Now, only `CraftBox` will contain `NULL`\n !is_craftbox(plot) || !is.null(plot@plot)\n }, logical(1L), USE.NAMES = FALSE)\n plot_list <- .subset(plot_list, keep)\n if (is_empty(plot_list)) return(NULL) # styler: off\n\n # we reorder the plots based on the `order` slot\n plot_order <- vapply(plot_list, function(plot) {\n if (is_layout(plot)) {\n .subset2(plot@plot_active, \"order\")\n } else {\n .subset2(plot@active, \"order\")\n }\n }, integer(1L), USE.NAMES = FALSE)\n plot_list <- .subset(plot_list, make_order(plot_order))\n\n # build the stack\n composer <- stack_composer(direction)\n\n # for `free_spaces`, if we have applied it in the whole stack layout\n # we shouln't use it for a single plot. Otherwise, the guide legends\n # collected by the layout will overlap with the axis of the plot in the\n # layout.\n #\n # this occurs in the annotation stack (`position` is not `NULL`).\n #\n # here is the example:\n # p1 <- ggplot(mtcars) +\n # geom_point(aes(mpg, disp))\n # p2 <- ggplot(mtcars) +\n # geom_boxplot(aes(gear, disp, group = gear, fill = gear))\n # p3 <- ggplot(mtcars) +\n # geom_bar(aes(gear)) +\n # facet_wrap(~cyl)\n # align_plots(\n # free_space(free_border(\n # align_plots(\n # # we shouldn't add free_space for the internal plot\n # free_space(\n # free_border(\n # p1 + scale_y_continuous(\n # expand = expansion(),\n # labels = ~ paste(\"very very long labels\", .x)\n # ),\n # \"l\"\n # ),\n # \"l\"\n # ),\n # p2 + theme(legend.position = \"left\"),\n # guides = \"l\"\n # ),\n # \"l\"\n # ), \"l\"),\n # p3 + theme(plot.margin = margin(l = 5, unit = \"cm\")),\n # ncol = 1\n # )\n stack_spaces <- .subset2(.subset2(schemes, \"scheme_align\"), \"free_spaces\")\n if (is_string(stack_spaces) && !is.null(position)) {\n released_spaces <- stack_spaces\n } else {\n released_spaces <- NULL\n }\n\n design <- setup_design(stack@design)\n stack_composer_add(\n plot_list,\n stack = stack,\n composer,\n schemes = schemes,\n theme = theme,\n design = design,\n extra_design = extra_design,\n direction = direction,\n position = position,\n released_spaces = released_spaces,\n previous_design = NULL\n )\n}\n\nmake_order <- function(order) {\n l <- length(order)\n index <- seq_len(l)\n\n # for order not set by user, we use heuristic algorithm to define the order\n need_action <- is.na(order)\n if (all(need_action)) { # shorthand for the usual way, we don't set any\n return(index)\n } else if (all(!need_action)) { # we won't need do something special\n return(order(order))\n }\n\n # 1. for outliers, we always put them in the two tail\n # 2. for order has been set and is not the outliers,\n # we always follow the order\n # 3. non-outliers were always regarded as the integer index\n used <- as.integer(order[!need_action & order >= 1L & order <= l])\n\n # we flatten user index to continuous integer sequence\n sequence <- vec_unrep(used) # key is the sequence start\n start <- .subset2(sequence, \"key\")\n end <- pmin(\n start + .subset2(sequence, \"times\") - 1L,\n vec_c(start[-1L] - 1L, l) # the next start - 1L\n )\n used <- .mapply(function(s, e) s:e, list(s = start, e = end), NULL)\n\n # following index can be used\n unused <- vec_set_difference(index, unlist(used, FALSE, FALSE))\n\n # we assign the candidate index to the order user not set.\n order[need_action] <- unused[seq_len(sum(need_action))]\n\n # make_order(c(NA, 1, NA)): c(2, 1, 3)\n # make_order(c(NA, 1, 3)): c(2, 1, 3)\n # make_order(c(NA, 1, 3, 1)): c(2, 4, 3, 1)\n order(order)\n}\n"], ["/ggalign/R/layout-heatmap-.R", "#' Create a heatmap\n#'\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' `heatmap_layout` is a specialized version of [`quad_discrete()`], which\n#' simplifies the creation of heatmap plots by integrating essential elements\n#' for a standard heatmap layout, ensuring that the appropriate data mapping and\n#' visualization layers are automatically applied. `ggheatmap` is an alias for\n#' `heatmap_layout`.\n#'\n#' @param data `r rd_layout_data()`. By default, it will try to inherit from\n#' parent layout. [`fortify_matrix()`] will be used to convert data to a\n#' matrix.\n#' @param ... Additional arguments passed to [`fortify_matrix()`].\n#' @inheritParams quad_layout\n#' @param filling A single string of `r oxford_or(c(\"raster\", \"tile\"))` to\n#' indicate the filling style. By default, `waiver()` is used, which means that\n#' if the input matrix has more than 20,000 cells (`nrow * ncol > 20000`),\n#' [`geom_raster()`][ggplot2::geom_raster] will be used for performance\n#' efficiency; for smaller matrices, [`geom_tile()`][ggplot2::geom_tile] will be\n#' used. To customize the filling style, set this to `NULL`.\n#'\n#' For backward compatibility, a single boolean value is acceptable: `TRUE`\n#' means `waiver()`, and `FALSE` means `NULL`.\n#'\n#' By default, the classic heatmap color scheme\n#' [`scale_fill_gradient2(low = \"blue\", high = \"red\")`][ggplot2::scale_fill_gradient2]\n#' is utilized for continuous values.\n#'\n#' You can use the options\n#' `r code_quote(sprintf(\"%s.heatmap_continuous_fill\", pkg_nm()))` or\n#' `r code_quote(sprintf(\"%s.heatmap_discrete_fill\", pkg_nm()))` to modify the\n#' default heatmap body filling color scale. See\n#' [`scale_fill_continuous()`][ggplot2::scale_fill_continuous] or\n#' [`scale_fill_discrete()`][ggplot2::scale_fill_discrete] for details on\n#' option settings.\n#'\n#' @section ggplot2 specification:\n#' The data input will be converted to a matrix using [`fortify_matrix()`], and\n#' the data in the underlying main plot will contain the following columns:\n#'\n#' - `.panel_x` and `.panel_y`: the column and row panel groups.\n#'\n#' - `.x` and `.y`: an integer index of `x` and `y` coordinates\n#'\n#' - `.discrete_x` and `.discrete_y`: a factor of the data labels (only\n#' applicable when `.row_names` and `.column_names` exists).\n#'\n#' - `.row_names` and `.column_names`: A character of the row and column names\n#' of the original matrix (only applicable when names exist).\n#'\n#' - `.row_index` and `.column_index`: the row and column index of the original\n#' matrix.\n#'\n#' - `value`: the actual matrix value.\n#'\n#' @return A `HeatmapLayout` object.\n#' @examples\n#' ggheatmap(1:10)\n#' ggheatmap(letters)\n#' ggheatmap(matrix(rnorm(81), nrow = 9L))\n#' @importFrom ggplot2 aes\n#' @export\nheatmap_layout <- function(data = NULL, mapping = aes(),\n ...,\n width = NA, height = NA, filling = waiver(),\n theme = NULL, active = NULL) {\n UseMethod(\"heatmap_layout\")\n}\n\n#' @usage NULL\n#' @export\n#' @rdname heatmap_layout\nggheatmap <- heatmap_layout\n\n#' @importFrom ggplot2 aes\n#' @importFrom rlang arg_match0\n#' @export\nheatmap_layout.default <- function(data = NULL, mapping = aes(),\n ...,\n width = NA, height = NA, filling = waiver(),\n theme = NULL, active = NULL) {\n # A single boolean value for compatible with `version <= 0.0.4`\n if (isTRUE(filling)) {\n filling <- waiver()\n } else if (isFALSE(filling)) {\n filling <- NULL\n } else if (!is.waive(filling) && !is.null(filling)) {\n filling <- arg_match0(filling, c(\"tile\", \"raster\"))\n }\n data <- data %|w|% NULL\n # we need a matrix to melted into long formated data frame\n data <- fortify_matrix(data = data, ...)\n ans <- new_quad_layout(\n name = \"ggheatmap\",\n data = data,\n mapping = mapping,\n theme = theme, active = active,\n width = width, height = height,\n class = \"HeatmapLayout\"\n )\n # add default mapping\n ans@plot <- ggadd_default(ans@plot, mapping = aes(.data$.x, .data$.y)) +\n ggplot2::labs(x = NULL, y = NULL)\n ans@filling <- filling\n ans\n}\n\n# used to create the heatmap layout\n#' @keywords internal\n#' @include layout-quad-.R\nmethods::setClass(\n \"HeatmapLayout\",\n contains = \"QuadLayout\",\n list(filling = \"ANY\") # parameters for heatmap body\n)\n"], ["/ggalign/R/alignpatch-free-align.R", "#' Free from alignment\n#'\n#' [align_plots] will try to align plot panels, and every elements of the plot,\n#' following functions romove these restrictions:\n#' - `free_align`: if we want to compose plots without alignment of some panel\n#' axes (panel won't be aligned). we can wrap the plot with `free_align`.\n#' - `free_border`: attaches borders (e.g., axis titles, tick marks) directly to\n#' the plot panel. This keeps them visually close to the panel during\n#' alignment.\n#' - `free_lab()`: Similar to `free_border()`, but only attaches axis titles\n#' and tick labels, not full borders. It’s mainly included for completeness;\n#' in most cases, combining `free_border()` and `free_space()` is sufficient.\n#' - `free_space`: Removing the ggplot element sizes when aligning.\n#' - `free_vp`: Customize the [viewport][grid::viewport] when aligning.\n#' - `free_guide`: If we want to override the behaviour of the overall guides\n#' behaviour, we can wrap the plot with `free_guide`.\n#'\n#' @param plot A [ggplot][ggplot2::ggplot] or [alignpatches][align_plots]\n#' object.\n#' @param axes Which axes shouldn't be aligned? A string containing\n#' one or more of `r oxford_and(.tlbr)`.\n#' @return\n#' - `free_align`: A modified version of `plot` with a `free_align` class.\n#' @examples\n#' # directly copied from `patchwork`\n#' # Sometimes you have a plot that defies good composition alginment, e.g. due\n#' # to long axis labels\n#' p1 <- ggplot(mtcars) +\n#' geom_bar(aes(y = factor(gear), fill = factor(gear))) +\n#' scale_y_discrete(\n#' \"\",\n#' labels = c(\n#' \"3 gears are often enough\",\n#' \"But, you know, 4 is a nice number\",\n#' \"I would def go with 5 gears in a modern car\"\n#' )\n#' )\n#'\n#' # When combined with other plots it ends up looking bad\n#' p2 <- ggplot(mtcars) +\n#' geom_point(aes(mpg, disp))\n#'\n#' align_plots(p1, p2, ncol = 1L)\n#'\n#' # We can fix this be using `free_align`\n#' align_plots(free_align(p1), p2, ncol = 1L)\n#'\n#' # If we still want the panels to be aligned to the right, we can choose to\n#' # free only the left side\n#' align_plots(free_align(p1, axes = \"l\"), p2, ncol = 1L)\n#'\n#' # We could use `free_lab` to fix the layout in a different way\n#' align_plots(p1, free_lab(p2), ncol = 1L)\n#'\n#' # `free_border` is similar with `free_lab`, they have a distinction in terms\n#' # of placement on either the top or bottom side of the panel. Specifically,\n#' # the top side contains the `title` and `subtitle`, while the bottom side\n#' # contains the `caption`. free_lab() does not attach these elements in the\n#' # panel area.\n#' p3 <- ggplot(mtcars) +\n#' geom_point(aes(hp, wt, colour = mpg)) +\n#' ggtitle(\"Plot 3\")\n#' p_axis_top <- ggplot(mtcars) +\n#' geom_point(aes(mpg, disp)) +\n#' ggtitle(\"Plot axis in top\") +\n#' scale_x_continuous(position = \"top\")\n#' align_plots(p_axis_top, free_lab(p3))\n#' align_plots(p_axis_top, free_border(p3))\n#'\n#' # Another issue is that long labels can occupy much spaces\n#' align_plots(NULL, p1, p2, p2)\n#'\n#' # This can be fixed with `free_space`\n#' align_plots(NULL, free_space(p1, \"l\"), p2, p2)\n#'\n#' @export\n#' @rdname free\nfree_align <- function(plot, axes = \"tlbr\") {\n UseMethod(\"free_align\")\n}\n\n# free_guides: set_guides\n# free_lab: collect_guides\n# free_border: collect_guides and align_border\n# free_space: get_sizes\n# free_align: get_sizes and align_border\n# free_vp: align_border\n\n#' @export\nfree_align.ggplot <- function(plot, axes = \"tlbr\") {\n assert_position(axes)\n attr(plot, \"free_axes\") <- axes\n add_class(plot, \"free_align\")\n}\n\n#' @export\nfree_align.alignpatches <- free_align.ggplot\n\n#' @importFrom rlang is_empty\n#' @export\nfree_align.free_lab <- function(plot, axes = \"tlbr\") {\n assert_position(axes)\n # if axes are free, it's not necessary to free the labs\n free_labs <- setdiff_position(attr(plot, \"free_labs\"), axes)\n if (nzchar(free_labs)) {\n attr(plot, \"free_labs\") <- free_labs\n } else {\n attr(plot, \"free_labs\") <- NULL\n plot <- remove_class(plot, \"free_lab\")\n }\n NextMethod()\n}\n\n#' @importFrom rlang is_empty\n#' @export\nfree_align.free_space <- function(plot, axes = \"tlbr\") {\n assert_position(axes)\n free_spaces <- setdiff_position(attr(plot, \"free_spaces\"), axes)\n if (nzchar(free_spaces)) {\n attr(plot, \"free_spaces\") <- free_spaces\n } else {\n attr(plot, \"free_spaces\") <- NULL\n plot <- remove_class(plot, \"free_space\")\n }\n NextMethod()\n}\n\n#' @importFrom rlang is_empty\n#' @export\nfree_align.free_border <- function(plot, axes = \"tlbr\") {\n assert_position(axes)\n free_borders <- setdiff_position(attr(plot, \"free_borders\"), axes)\n if (nzchar(free_borders)) {\n attr(plot, \"free_borders\") <- free_borders\n } else {\n attr(plot, \"free_borders\") <- NULL\n plot <- remove_class(plot, \"free_border\")\n }\n NextMethod()\n}\n\n#' @export\nfree_align.free_align <- function(plot, axes = \"tlbr\") {\n assert_position(axes)\n attr(plot, \"free_axes\") <- union_position(attr(plot, \"free_axes\"), axes)\n plot\n}\n\n#' @export\nfree_align.default <- function(plot, axes = \"tlbr\") {\n cli_abort(\"Cannot use with {.obj_type_friendly {plot}}\")\n}\n\n#' @importFrom ggplot2 ggproto ggproto_parent\n#' @export\nalignpatch.free_align <- function(x) {\n Parent <- NextMethod()\n ggproto(\n \"PatchFreeAlign\", Parent,\n free_axes = split_position(attr(x, \"free_axes\")),\n get_sizes = function(self, free = NULL, gt = self$gt) {\n ggproto_parent(Parent, self)$get_sizes(\n union(free, self$free_axes),\n gt = gt\n )\n },\n align_border = function(self, t = NULL, l = NULL, b = NULL, r = NULL,\n gt = self$gt) {\n for (axis in self$free_axes) {\n assign(x = axis, value = NULL, envir = environment())\n }\n ggproto_parent(Parent, self)$align_border(\n t = t, l = l, b = b, r = r, gt = gt\n )\n }\n )\n}\n"], ["/ggalign/R/ggplot-facet-sector.R", "#' Polar coordinates with Facet support\n#'\n#' Draw each panel in a sector of the polar coordinate system. If\n#' `facet_sector()` is used in a ggplot, the coordinate system must be created\n#' with [`coord_circle()`] or [`coord_radial()`][ggplot2::coord_radial].\n#'\n#' @inheritParams ggplot2::facet_wrap\n#' @param sector_spacing The size of spacing between different panel. A numeric\n#' of the radians or a [`rel()`][ggplot2::rel] object.\n#' @param radial `r lifecycle::badge(\"deprecated\")` Please add the coordinate\n#' system directly to the ggplot instead.\n#' @param spacing_theta `r lifecycle::badge(\"deprecated\")` Please use\n#' `sector_spacing` instead.\n#' @examples\n#' ggplot(mtcars, aes(disp, mpg)) +\n#' geom_point() +\n#' facet_sector(vars(cyl)) +\n#' coord_circle(\n#' start = -0.4 * pi, end = 0.4 * pi, inner.radius = 0.3,\n#' outer.radius = 0.8, expand = TRUE\n#' )\n#' @importFrom ggplot2 ggproto\n#' @export\nfacet_sector <- function(facets, sector_spacing = pi / 180, drop = TRUE,\n radial = deprecated(), spacing_theta = deprecated()) {\n if (packageVersion(\"ggplot2\") > \"3.5.2\") {\n facets <- ggfun(\"compact_facets\")(facets)\n } else {\n facets <- ggfun(\"wrap_as_facets_list\")(facets)\n }\n if (inherits(sector_spacing, \"CoordRadial\") ||\n lifecycle::is_present(radial)) {\n lifecycle::deprecate_stop(\n \"1.0.2\",\n \"facet_sector(radial = )\",\n details = \"Please add the coordinate to the ggplot instead\"\n )\n }\n if (lifecycle::is_present(spacing_theta)) {\n lifecycle::deprecate_warn(\n \"1.0.2\",\n \"facet_sector(spacing_theta = )\",\n \"facet_sector(sector_spacing = )\"\n )\n sector_spacing <- spacing_theta\n }\n\n # @param strip.position By default, the labels are displayed on the\n # `\"outer\"` of the plot. Allowed values are `r oxford_or(c(\"outer\",\n # \"inner\"))`\n # strip.position <- arg_match0(strip.position, c(\"outer\", \"inner\"))\n # strip.position <- switch(strip.position,\n # outer = \"top\",\n # inner = \"bottom\"\n # )\n # labeller <- ggfun(\"fix_labeller\")(labeller)\n assert_bool(drop)\n\n # TO-DO: remove this line and update to\n # the next version of ggplot2 (> 3.5.2)\n if (packageVersion(\"ggplot2\") > \"3.5.2\") {\n dir <- \"lt\"\n } else {\n dir <- \"h\"\n }\n ggproto(\n NULL,\n FacetSector,\n sector_spacing = sector_spacing,\n params = list(\n facets = facets,\n free = list(x = TRUE, y = FALSE),\n strip.position = \"top\",\n drop = drop, ncol = NULL, nrow = 1L,\n space_free = list(x = TRUE, y = FALSE),\n labeller = ggplot2::label_value, dir = dir,\n draw_axes = list(x = TRUE, y = FALSE),\n axis_labels = list(x = TRUE, y = FALSE),\n as.table = TRUE\n )\n )\n}\n\n#' @importFrom ggplot2 ggplot_add\n#' @export\nggplot_add.FacetSector <- function(object, plot, object_name, ...) {\n plot <- NextMethod()\n if (!inherits(plot, \"ggalign_facet_sector_plot\")) {\n plot <- add_class(plot, \"ggalign_facet_sector_plot\")\n }\n plot\n}\n\n#' @importFrom ggplot2 ggplot_build ggproto ggproto_parent\n#' @export\nggplot_build.ggalign_facet_sector_plot <- function(plot, ...) {\n if (inherits(plot$facet, \"FacetSector\")) {\n if (!inherits(plot$coordinates, \"CoordRadial\")) {\n if (!isTRUE(plot$coordinates$default)) {\n cli_abort(c(\n paste(\n \"Cannot use {.fn {snake_class(plot$coordinates)}}\",\n \"coordinate with {.fn facet_sector}\"\n ),\n i = \"Please use {.fn coord_circle}/{.fn coord_radial} instead\"\n ))\n }\n plot$coordinates <- coord_circle()\n }\n ParentLayout <- plot$layout\n plot$layout <- ggproto(\n \"FacetSectorLayout\", ParentLayout,\n setup_panel_params = function(self) {\n ggproto_parent(ParentLayout, self)$setup_panel_params()\n if (is.null(ggplot2::Facet$setup_panel_params) &&\n !is.null(self$facet$setup_panel_params)) {\n self$panel_params <- self$facet$setup_panel_params(\n self$panel_params, self$coord\n )\n }\n invisible()\n }\n )\n }\n NextMethod()\n}\n\n#' @importFrom rlang inject\n#' @importFrom grid gTree editGrob viewport\n#' @importFrom ggplot2 ggproto ggproto_parent\nFacetSector <- ggproto(\n \"FacetSector\", ggplot2::FacetWrap,\n setup_panel_params = function(self, panel_params, coord, ...) {\n # total theta for panel area and panel spacing\n arc_theta <- abs(diff(coord$arc))\n sector_spacing <- self$sector_spacing\n if (inherits(sector_spacing, \"rel\")) {\n sector_spacing <- sector_spacing * arc_theta\n }\n panel_weights <- vapply(panel_params, function(panel_param) {\n abs(diff(.subset2(panel_param, \"theta.range\")))\n }, numeric(1L), USE.NAMES = FALSE)\n\n # total theta for panel area\n panel_theta <- arc_theta -\n # substract the number of spacing between panels\n sector_spacing *\n # for the whole circle, arc_theta == 2 * pi\n # there should be as many panels as the number of panel spacing\n if (abs(arc_theta - 2 * pi) < .Machine$double.eps^0.5) {\n length(panel_weights)\n } else {\n length(panel_weights) - 1L\n }\n if (panel_theta <= 0L) {\n cli_abort(\"No panel area, try to reduce {.arg sector_spacing}\")\n }\n\n # re-distribute the arc for each panel\n panel_point <- vec_interleave(\n panel_theta * panel_weights / sum(panel_weights),\n rep_len(sector_spacing, length(panel_weights))\n )\n panel_point <- cumsum(c(coord$arc[1L], utils::head(panel_point, -1L)))\n for (i in seq_along(panel_params)) {\n panel_param <- .subset2(panel_params, i)\n panel_param$arc <- panel_point[i * 2L - 1:0]\n panel_param$bbox <- ggfun(\"polar_bbox\")(\n panel_param$arc, margin = c(0, 0, 0, 0),\n inner_radius = coord$inner_radius\n )\n panel_params[[i]] <- panel_param\n }\n panel_params\n },\n draw_panels = function(self, panels, layout, x_scales, y_scales, ranges,\n coord, data, theme, params) {\n # merge different sector into one panel\n bbox <- ggfun(\"polar_bbox\")(\n coord$arc, margin = c(0, 0, 0, 0),\n inner_radius = coord$inner_radius\n )\n for (i in seq_along(panels)) {\n panel_param <- .subset2(ranges, i)\n vp <- list(\n x = scales::rescale(panel_param$bbox$x, from = bbox$x),\n y = scales::rescale(panel_param$bbox$y, from = bbox$y)\n )\n panels[[i]] <- editGrob(\n .subset2(panels, i),\n vp = viewport(\n x = vp$x[1L], y = vp$y[1L],\n width = abs(diff(vp$x)),\n height = abs(diff(vp$y)),\n just = c(0, 0),\n clip = \"off\",\n default.units = \"native\"\n )\n )\n }\n panels <- gTree(children = inject(gList(!!!panels)))\n ranges <- lapply(ranges, function(panel_param) {\n panel_param$arc <- coord$arc\n panel_param$bbox <- bbox\n panel_param\n })\n ggplot2::FacetNull$draw_panels(\n panels = list(panels),\n layout = layout, x_scales = x_scales, y_scales = y_scales,\n ranges = ranges, coord = coord, data = data,\n theme = theme, params = params\n )\n }\n)\n"], ["/ggalign/R/scheme-align.R", "#' Align Specifications in the Layout\n#'\n#' @description\n#' `r lifecycle::badge('experimental')`\n#'\n#' The `scheme_align()` function defines the align Specifications for plots.\n#'\n#' @param guides A string with one or more of `r oxford_and(c(.tlbr, \"i\"))`\n#' indicating which side of guide legends should be collected. Defaults to\n#' [`waiver()`][ggplot2::waiver()], which inherits from the parent layout. If no\n#' parent layout, all guides will be collected. If `NULL`, no guides will be\n#' collected.\n#'\n#' @param free_spaces A string with one or more of `r oxford_and(.tlbr)`\n#' indicating which border spaces should be removed. Defaults to\n#' [`waiver()`][ggplot2::waiver()], which inherits from the parent layout. If no\n#' parent, the default is `NULL`, meaning no spaces are removed.\n#'\n#' Usually you want to apply this with the whole layout, instead of individual\n#' plots.\n#'\n#' @param free_labs A string with one or more of `r oxford_and(.tlbr)`\n#' indicating which axis titles should be free from alignment. Defaults to\n#' [`waiver()`][ggplot2::waiver()], which inherits from the parent layout. If no\n#' parent layout, no axis titles will be aligned. If `NULL`, all axis titles\n#' will be aligned.\n#'\n#' @return A `scheme_align` object.\n#' @examples\n#' set.seed(123)\n#' mat <- matrix(rnorm(72), nrow = 8)\n#' # used in the layout, define the default action for all plots in the layout\n#' ggheatmap(mat) -\n#' scheme_align(guides = NULL) +\n#' anno_right() +\n#' align_dendro(aes(color = branch), k = 3)\n#'\n#' # You can also add it for a single plot\n#' ggheatmap(mat) -\n#' # for all plots in the layout, we default won't collect any guide legends\n#' scheme_align(guides = NULL) +\n#' # for the heatmap body, we collect guide legends in the right\n#' # note, the guide legends will be collected to the right side of the\n#' # layout which will overlap the legends in the right annotation\n#' scheme_align(guides = \"r\") +\n#' anno_right() +\n#' align_dendro(aes(color = branch), k = 3)\n#'\n#' # to avoid overlapping, we can also collect the guide legends in the\n#' # right annotation\n#' ggheatmap(mat) -\n#' scheme_align(guides = NULL) +\n#' scheme_align(guides = \"r\") +\n#' anno_right() +\n#' align_dendro(aes(color = branch), k = 3) +\n#' scheme_align(guides = \"r\")\n#' @export\nscheme_align <- function(guides = NA, free_spaces = NA, free_labs = NA) {\n if (!identical(guides, NA)) assert_layout_guides(guides)\n if (!identical(free_spaces, NA)) assert_layout_position(free_spaces)\n if (!identical(free_labs, NA)) assert_layout_position(free_labs)\n new_scheme_align(\n free_spaces = free_spaces,\n free_labs = free_labs,\n guides = guides\n )\n}\n\nnew_scheme_align <- function(guides = waiver(), free_spaces = waiver(),\n free_labs = waiver()) {\n new_scheme(\n name = \"scheme_align\",\n list(free_spaces = free_spaces, free_labs = free_labs, guides = guides),\n class = \"scheme_align\"\n )\n}\n\n#' @importFrom utils modifyList\n#' @export\nupdate_scheme.scheme_align <- function(new, old, object_name) {\n modifyList(old,\n new[!vapply(new, identical, logical(1L), y = NA, USE.NAMES = FALSE)],\n keep.null = TRUE\n )\n}\n\n#' @export\ninherit_scheme.scheme_align <- function(scheme, pscheme) {\n # `align_plots` control how to inherit `guides` from the layout\n # we don't need to inherit it here\n scheme[\"free_spaces\"] <- list(.subset2(scheme, \"free_spaces\") %|w|%\n .subset2(pscheme, \"free_spaces\"))\n scheme[\"free_labs\"] <- list(.subset2(scheme, \"free_labs\") %|w|%\n .subset2(pscheme, \"free_labs\"))\n scheme\n}\n\n#' @param theme Additional default theme elements to be added for the plot\n#' @noRd\nplot_add_scheme.scheme_align <- function(plot, scheme) {\n if (!is.waive(free_guides <- .subset2(scheme, \"guides\"))) {\n plot <- free_guide(plot, free_guides)\n }\n # by default, we'll attach all labs to the axis\n if (!is.null(free_labs <- .subset2(scheme, \"free_labs\") %|w|% \"tlbr\")) {\n plot <- free_lab(plot, free_labs)\n }\n # by default, we won't remove any spaces\n if (!is.null(free_spaces <- .subset2(scheme, \"free_spaces\") %|w|% NULL)) {\n plot <- free_space(free_border(plot, free_spaces), free_spaces)\n }\n plot\n}\n"], ["/ggalign/R/alignpatch-.R", "# here is copied from patchwork\n# we modified the `patchwork` package for following reasons:\n# 1. collect guides for each side (should be merged into patchwork, not allowed\n# to be merged: https://github.com/thomasp85/patchwork/issues/379).\n# 2. `free_*()` functions: see https://github.com/thomasp85/patchwork/issues/379\n# - `free_align()`: added\n# - `free_border()`: not added\n# - `free_lab()`: added\n# - `free_space()`: added\n# - `free_vp()`: not added\n# 3. Added titles around the plot top, left, bottom, and right\n# (`patch_titles()`)\nTABLE_ROWS <- 18L + 2L\nTABLE_COLS <- 15L + 2L\n\nTOP_BORDER <- 9L + 1L\nLEFT_BORDER <- 7L + 1L\nBOTTOM_BORDER <- 8L + 1L\nRIGHT_BORDER <- 7L + 1L\n\n# top-bottom\n# 1: margin\n# 2: tag\n# 3: title\n# 4: subtitle\n# 5: guide-box-top\n# 6: legend.box.spacing\n# feature: insert patch title\n# 7: xlab-t\n# strip.placement = \"inside\"/\"outside\"\n# 8: axis-t/strip-t\n# 9: strip-t/axis-t\n# 10: panel\n# 11: strip-b\n# 12: axis-b\n# 13: xlab-b\n# feature: insert patch title\n# 14: legend.box.spacing\n# 15: guide-box-bottom\n# 16: caption\n# 17: tag\n# 18: margin\n\n# left-right\n#\n# 1: margin\n# 2: tag\n# 3: guide-box-left\n# 4: legend.box.spacing\n# feature: insert patch title\n# 5: ylab-l\n# 6: axis-l\n# 8: panel\n# 10: axis-r\n# 11: ylab-r\n# feature: insert patch title\n# 12: legend.box.spacing\n# 13: guide-box-right\n# 14: tag\n# 15: margin\n\n.TLBR <- c(\"top\", \"left\", \"bottom\", \"right\")\n.tlbr <- c(\"t\", \"l\", \"b\", \"r\")\n\n# position is a single string contains `.tlbr`\nsetdiff_position <- function(x, y) gsub(sprintf(\"[%s]\", y), \"\", x)\nunion_position <- function(x, y) paste0(x, gsub(sprintf(\"[%s]\", x), \"\", y))\nsplit_position <- function(x) {\n vec_unique(.subset2(strsplit(x, \"\", fixed = TRUE), 1L))\n}\n\n# pos is an atomic character\nsetup_pos <- function(x) unname(complete_pos(split_position(x)))\n\nsetup_guides <- function(x) {\n .subset(\n c(t = \"top\", l = \"left\", b = \"bottom\", r = \"right\", i = \"inside\"),\n split_position(x)\n )\n}\n\ncomplete_pos <- function(x) {\n .subset(c(t = \"top\", l = \"left\", b = \"bottom\", r = \"right\"), x)\n}\n\nopposite_pos <- function(pos) {\n switch(pos,\n top = \"bottom\",\n bottom = \"top\",\n left = \"right\",\n right = \"left\"\n )\n}\n\n#' @importFrom ggplot2 zeroGrob\n#' @importFrom gtable gtable gtable_add_grob\n#' @importFrom grid unit\nmake_patch_table <- function() {\n widths <- unit(rep(0L, TABLE_COLS), \"mm\")\n widths[LEFT_BORDER + 1L] <- unit(1L, \"null\")\n heights <- unit(rep(0L, TABLE_ROWS), \"mm\")\n heights[TOP_BORDER + 1L] <- unit(1L, \"null\")\n ans <- gtable(widths, heights)\n gtable_add_grob(ans,\n list(zeroGrob()), TOP_BORDER + 1L, LEFT_BORDER + 1L,\n z = -Inf, name = \"panel-area\"\n )\n}\n\n#' Generate a plot grob.\n#'\n#' @param x An object to be converted into a [grob][grid::grob].\n#' @return A [`grob()`][grid::grob] object.\n#' @examples\n#' ggalignGrob(ggplot())\n#' @export\nggalignGrob <- function(x) {\n ggalign_gtable(ggalign_build(x))\n}\n\n# Now, we only define `ggalign_gtable` method for `alignpatches` and `ggplot`\n# `ggalign_build` must return these objects\nggalign_build <- function(x) UseMethod(\"ggalign_build\")\n\nggalign_gtable <- function(x) UseMethod(\"ggalign_gtable\")\n\n#' @export\nggalign_gtable.gtable <- function(x) x\n\n#' Prepare plots to be aligned with `align_plots`\n#'\n#' @param x A plot object to be prepared for alignment.\n#' @details\n#' `ggalign` has implement `alignpatch` method for following objects:\n#' - [`ggplot`][ggplot2::ggplot]\n#' - [`alignpatches`][align_plots]\n#' - [`wrapped_plot`][ggwrap]\n#' - [`patch`][patchwork::patchGrob]\n#' - [`wrapped_patch`][patchwork::wrap_elements]\n#' - [`spacer`][patchwork::plot_spacer]\n#'\n#' @return A `Patch` object.\n#' @examples\n#' alignpatch(ggplot())\n#' @seealso [`align_plots()`]\n#' @export\n#' @keywords internal\nalignpatch <- function(x) UseMethod(\"alignpatch\")\n\n#' @export\nalignpatch.default <- function(x) {\n cli_abort(\"Cannot align {.obj_type_friendly {x}}\")\n}\n\n#' @export\nalignpatch.NULL <- function(x) NULL\n\npatch_no_method <- function(plot, method) {\n cli_abort(\"no {.fn {method}} method for {.obj_type_friendly {plot}}\")\n}\n\n#' @importFrom ggplot2 ggproto\n#' @importFrom grid unit.c\nPatch <- ggproto(\n \"Patch\", NULL,\n # following fields will be added by `alignpatch()`\n plot = NULL,\n # following fields will be added in `alignpatches$patch_gtable()`\n # borders = NULL, gt = NULL,\n\n #' @param guides `guides` argument from the parent alignpatches\n #' @return Which side of guide legends should be collected by the parent\n #' `alignpatches` object?\n #' @noRd\n set_guides = function(self, guides) {\n patch_no_method(self$plot, \"set_guides\")\n },\n patch_gtable = function(self, theme, guides, plot = self$plot) {\n patch_no_method(self$plot, \"patch_gtable\")\n },\n collect_guides = function(self, guides, gt = self$gt) {\n if (is.null(guides)) return(list()) # styler: off\n layout <- .subset2(gt, \"layout\")\n grobs <- .subset2(gt, \"grobs\")\n guides_ind <- grep(\"guide-box\", .subset2(layout, \"name\"))\n guides_loc <- vec_slice(layout, guides_ind)\n collected_guides <- vector(\"list\", length(guides))\n names(collected_guides) <- guides\n panel_loc <- find_panel(gt)\n remove_grobs <- NULL\n for (guide_pos in guides) {\n guide_ind <- switch(guide_pos,\n top = .subset2(guides_loc, \"b\") < .subset2(panel_loc, \"t\"),\n left = .subset2(guides_loc, \"r\") < .subset2(panel_loc, \"l\"),\n bottom = .subset2(guides_loc, \"t\") > .subset2(panel_loc, \"b\"),\n right = .subset2(guides_loc, \"l\") > .subset2(panel_loc, \"r\"),\n inside = .subset2(guides_loc, \"t\") >= .subset2(panel_loc, \"t\") &\n .subset2(guides_loc, \"b\") <= .subset2(panel_loc, \"b\") &\n .subset2(guides_loc, \"l\") >= .subset2(panel_loc, \"l\") &\n .subset2(guides_loc, \"r\") <= .subset2(panel_loc, \"r\")\n )\n if (!any(guide_ind)) next\n guide_loc <- vec_slice(guides_loc, guide_ind)\n guide_ind <- .subset(guides_ind, guide_ind)\n remove_grobs <- c(guide_ind, remove_grobs)\n collected_guides[[guide_pos]] <- .subset2(grobs, guide_ind)\n\n # remove the guide spaces from the original gtable\n # for inside guide, no need to remove the spaces\n if (guide_pos == \"inside\") next\n\n space_pos <- switch(guide_pos,\n top = ,\n left = 1L,\n bottom = ,\n right = -1L\n )\n if (guide_pos %in% c(\"right\", \"left\")) {\n gt$widths[c(guide_loc$l, guide_loc$l + space_pos)] <- unit(\n c(0L, 0L), \"mm\"\n )\n } else if (guide_pos %in% c(\"bottom\", \"top\")) {\n gt$heights[c(guide_loc$t, guide_loc$t + space_pos)] <- unit(\n c(0L, 0L), \"mm\"\n )\n }\n }\n if (length(remove_grobs)) {\n gt <- subset_gt(gt, -remove_grobs, trim = FALSE)\n }\n self$gt <- gt\n collected_guides\n },\n respect = function(self, gt = self$gt) isTRUE(.subset2(gt, \"respect\")),\n align_panel_sizes = function(self, panel_width, panel_height,\n gt = self$gt) {\n list(width = panel_width, height = panel_height, respect = FALSE)\n },\n get_sizes = function(self, free = NULL, gt = self$gt) {\n ans <- .subset2(gt, \"heights\")\n if (any(free == \"t\")) {\n top <- unit(rep_len(0, TOP_BORDER), \"mm\")\n } else {\n top <- ans[seq_len(TOP_BORDER)]\n }\n if (any(free == \"b\")) {\n bottom <- unit(rep_len(0, BOTTOM_BORDER), \"mm\")\n } else {\n bottom <- ans[seq(length(ans) - BOTTOM_BORDER + 1L, length(ans))]\n }\n ans <- .subset2(gt, \"widths\")\n if (any(free == \"l\")) {\n left <- unit(rep_len(0, LEFT_BORDER), \"mm\")\n } else {\n left <- ans[seq_len(LEFT_BORDER)]\n }\n if (any(free == \"r\")) {\n right <- unit(rep_len(0, RIGHT_BORDER), \"mm\")\n } else {\n right <- ans[seq(length(ans) - RIGHT_BORDER + 1L, length(ans))]\n }\n list(\n widths = unit.c(left, unit(0, \"mm\"), right),\n heights = unit.c(top, unit(0, \"mm\"), bottom)\n )\n },\n align_border = function(self, t = NULL, l = NULL, b = NULL, r = NULL,\n gt = self$gt) {\n if (!is.null(t)) gt$heights[seq_along(t)] <- t\n if (!is.null(l)) gt$widths[seq_along(l)] <- l\n if (!is.null(b)) {\n n_row <- nrow(gt)\n gt$heights[seq(n_row - length(b) + 1L, n_row)] <- b\n }\n if (!is.null(r)) {\n n_col <- ncol(gt)\n gt$widths[seq(n_col - length(r) + 1L, n_col)] <- r\n }\n gt\n },\n split_gt = function(self, gt = self$gt) {\n isbg <- .subset2(.subset2(gt, \"layout\"), \"name\") == \"background\"\n if (any(isbg)) {\n bg <- .subset(.subset2(gt, \"grobs\"), isbg) # a list of background\n plot <- subset_gt(gt, !isbg, trim = FALSE)\n } else {\n bg <- NULL\n plot <- gt\n }\n list(bg = bg, plot = plot)\n },\n add_plot = function(self, gt, plot, t, l, b, r, name, z = 2L) {\n gtable_add_grob(\n gt,\n grobs = plot,\n t = t, l = l, b = b, r = r,\n name = name, z = z\n )\n },\n add_background = function(self, gt, bg, t, l, b, r, name, z = 1L) {\n gtable_add_grob(\n gt,\n grobs = bg,\n t = t, l = l, b = b, r = r,\n name = name, z = z\n )\n },\n free_border = function(self, borders, gt = self$gt) {\n patch_no_method(self$plot, \"free_border\")\n },\n align_free_border = function(self, borders,\n t = NULL, l = NULL, b = NULL, r = NULL,\n gt = self$gt) {\n patch_no_method(self$plot, \"align_free_border\")\n },\n free_lab = function(self, labs, gt = self$gt) {\n patch_no_method(self$plot, \"free_lab\")\n }\n)\n"], ["/ggalign/R/layout-quad-build.R", "#' @importFrom grid unit.c\n#' @export\nggalign_build.QuadLayout <- function(x) {\n x <- default_layout(x)\n patches <- quad_build(x)\n plots <- .subset2(patches, \"plots\")\n sizes <- .subset2(patches, \"sizes\")\n design <- list(\n top = area(1, 2),\n left = area(2, 1),\n main = area(2, 2),\n bottom = area(3, 2),\n right = area(2, 3)\n )\n sizes <- imap(list(\n height = c(\"top\", \"main\", \"bottom\"),\n width = c(\"left\", \"main\", \"right\")\n ), function(x, name) {\n out <- .subset(sizes, x)\n out$main <- .subset2(.subset2(out, \"main\"), name)\n out <- .subset(\n out,\n !vapply(.subset(plots, x), is.null, logical(1L), USE.NAMES = FALSE)\n )\n do.call(unit.c, out)\n })\n keep <- !vapply(plots, is.null, logical(1L), USE.NAMES = FALSE)\n design <- trim_area(vec_c(!!!vec_set_names(vec_slice(design, keep), NULL)))\n titles <- x@titles\n align_plots(\n !!!.subset(plots, keep),\n design = design,\n heights = .subset2(sizes, \"height\"),\n widths = .subset2(sizes, \"width\"),\n guides = .subset2(.subset2(x@schemes, \"scheme_align\"), \"guides\"),\n theme = x@theme\n ) + layout_title(\n title = .subset2(titles, \"title\"),\n subtitle = .subset2(titles, \"subtitle\"),\n caption = .subset2(titles, \"caption\")\n )\n}\n\nquad_build <- function(quad, schemes = NULL, theme = NULL,\n direction = NULL) {\n UseMethod(\"quad_build\")\n}\n\n#######################################################################\n#' @param schemes,theme Parameters from parent layout\n#' @importFrom ggplot2 aes\n#' @importFrom rlang is_empty\n#' @importFrom grid unit is.unit unit.c\n#' @export\n#' @noRd\nquad_build.QuadLayout <- function(quad, schemes = NULL, theme = NULL,\n direction = NULL) {\n data <- quad@data\n row_design <- setup_design(quad@horizontal)\n column_design <- setup_design(quad@vertical)\n if (is.function(data)) {\n cli_abort(c(\n \"{.arg data} cannot be a {.cls function}\",\n i = sprintf(\n \"Did you want to add %s to a {.fn stack_layout}?\",\n object_name(quad)\n )\n ))\n }\n if (is_discrete_design(row_design) &&\n is.null(.subset2(row_design, \"nobs\"))) {\n cli_abort(sprintf(\n \"you must initialize %s before drawing the main plot\",\n object_name(quad),\n ))\n }\n if (is_discrete_design(column_design) &&\n is.null(.subset2(column_design, \"nobs\"))) {\n cli_abort(sprintf(\n \"you must initialize %s before drawing the main plot\",\n object_name(quad),\n ))\n }\n schemes <- inherit_parent_layout_schemes(quad, schemes)\n if (is.null(direction)) {\n spacing <- NULL\n } else if (is_horizontal(direction)) {\n spacing <- \"y\"\n } else {\n spacing <- \"x\"\n }\n theme <- inherit_parent_layout_theme(quad, theme, spacing = spacing)\n\n # prepare action for vertical and horizontal stack layout\n vertical_align <- horizontal_align <- the_align <-\n .subset2(schemes, \"scheme_align\")\n if (!is.null(layout_labs <- .subset2(the_align, \"free_labs\")) &&\n !is.waive(layout_labs)) {\n # prepare labs for child stack layout\n horizontal_align$free_labs <- gsub(\"[lr]\", \"\", layout_labs)\n vertical_align$free_labs <- gsub(\"[tb]\", \"\", layout_labs)\n if (!nzchar(horizontal_align$free_labs)) {\n horizontal_align[\"free_labs\"] <- list(NULL)\n }\n if (!nzchar(vertical_align$free_labs)) {\n vertical_align[\"free_labs\"] <- list(NULL)\n }\n }\n\n # inherit from the parent stack layout\n if (!is.null(layout_spaces <- .subset2(the_align, \"free_spaces\")) &&\n !is.waive(layout_spaces)) {\n horizontal_align$free_spaces <- gsub(\"[lr]\", \"\", layout_spaces)\n vertical_align$free_spaces <- gsub(\"[tb]\", \"\", layout_spaces)\n if (!nzchar(horizontal_align$free_spaces)) {\n horizontal_align[\"free_spaces\"] <- list(NULL)\n }\n if (!nzchar(vertical_align$free_spaces)) {\n vertical_align[\"free_spaces\"] <- list(NULL)\n }\n }\n\n # plot annotations ----------------------------\n stack_list <- lapply(.TLBR, function(position) {\n if (is_empty(stack <- slot(quad, position))) {\n return(list(plot = NULL, size = NULL))\n }\n pschemes <- schemes\n # inherit from horizontal align or vertical align\n if (is_horizontal(to_direction(position))) {\n extra_design <- column_design\n pschemes$scheme_align <- horizontal_align\n } else {\n extra_design <- row_design\n pschemes$scheme_align <- vertical_align\n }\n plot <- stack_build(\n stack,\n schemes = pschemes,\n theme = theme,\n extra_design = extra_design\n )\n if (is.null(plot)) {\n size <- NULL\n } else {\n size <- stack@sizes\n }\n list(plot = plot, size = size)\n })\n names(stack_list) <- .TLBR\n stack_list <- list_transpose(stack_list)\n plots <- .subset2(stack_list, 1L) # the annotation plot itself\n sizes <- .subset2(stack_list, 2L) # annotation size\n\n # read the plot ---------------------------------------\n p <- quad@plot\n\n # setup the facet -----------------------------------\n do_row_facet <- is_discrete_design(row_design) &&\n nlevels(.subset2(row_design, \"panel\")) > 1L\n do_column_facet <- is_discrete_design(column_design) &&\n nlevels(.subset2(column_design, \"panel\")) > 1L\n\n if (do_row_facet && do_column_facet) {\n default_facet <- ggplot2::facet_grid(\n rows = ggplot2::vars(.data$.panel_y),\n cols = ggplot2::vars(.data$.panel_x),\n scales = \"free\", space = \"free\",\n drop = FALSE, as.table = FALSE\n )\n free_row <- FALSE\n free_column <- FALSE\n } else if (do_row_facet) {\n default_facet <- ggplot2::facet_grid(\n rows = ggplot2::vars(.data$.panel_y),\n scales = \"free_y\", space = \"free\",\n drop = FALSE, as.table = FALSE\n )\n free_row <- FALSE\n free_column <- is_continuous_design(column_design)\n } else if (do_column_facet) {\n default_facet <- ggplot2::facet_grid(\n cols = ggplot2::vars(.data$.panel_x),\n scales = \"free_x\", space = \"free\",\n drop = FALSE, as.table = FALSE\n )\n free_row <- is_continuous_design(row_design)\n free_column <- FALSE\n } else {\n default_facet <- facet_quad(object_name(quad))\n free_row <- is_continuous_design(row_design)\n free_column <- is_continuous_design(column_design)\n }\n\n # set the facets and coord ---------------------------\n # we don't align observations for `quad_free()`\n # add default data ----------------------------------\n p <- gguse_data(p, quad_build_data(data, row_design, column_design))\n p <- gguse_linear_coord(p, object_name(quad))\n p <- ggmelt_facet(p, default_facet,\n free_row = free_row, free_column = free_column\n )\n p <- p +\n ggalign_design(\n x = column_design, y = row_design,\n xlabels = .subset(\n colnames(data),\n .subset2(column_design, \"index\")\n ),\n ylabels = .subset(\n vec_names(data),\n .subset2(row_design, \"index\")\n )\n )\n\n # add action ----------------------------------------\n p <- plot_add_schemes(p, inherit_schemes(quad@body_schemes, schemes))\n if (do_row_facet) {\n p <- p + theme(panel.spacing.y = calc_element(\"panel.spacing.y\", theme))\n }\n if (do_column_facet) {\n p <- p + theme(panel.spacing.x = calc_element(\"panel.spacing.x\", theme))\n }\n p <- p + theme_recycle()\n\n # collect all plots and sizes ----------------------\n plots <- append(plots, list(main = p), 2L)\n sizes <- append(\n sizes,\n list(main = list(width = quad@width, height = quad@height)),\n 3L\n )\n list(plots = plots, sizes = sizes)\n}\n\n#' @importFrom stats reorder\nquad_build_data <- function(data, row_design, column_design) {\n if (is.null(data) ||\n (is_continuous_design(row_design) &&\n is_continuous_design(column_design))) {\n return(data)\n }\n if (is_discrete_design(row_design)) {\n row_panel <- .subset2(row_design, \"panel\")\n row_index <- .subset2(row_design, \"index\")\n row_data <- data_frame0(\n .panel_y = row_panel,\n .index_y = row_index,\n .y = seq_along(row_index)\n )\n }\n if (is_discrete_design(column_design)) {\n column_panel <- .subset2(column_design, \"panel\")\n column_index <- .subset2(column_design, \"index\")\n column_data <- data_frame0(\n .panel_x = column_panel,\n .index_x = column_index,\n .x = seq_along(column_index)\n )\n }\n if (is_discrete_design(row_design) && is_discrete_design(column_design)) {\n panel_data <- cross_join(row_data, column_data)\n by.x <- c(\".column_index\", \".row_index\")\n by.y <- c(\".index_x\", \".index_y\")\n } else if (is_discrete_design(column_design)) {\n panel_data <- column_data\n by.x <- \".column_index\"\n by.y <- \".index_x\"\n } else {\n panel_data <- row_data\n by.x <- \".row_index\"\n by.y <- \".index_y\"\n }\n ans <- fortify_data_frame.matrix(data)\n ans <- full_join(ans, panel_data, by.x = by.x, by.y = by.y)\n if (!is.null(.subset2(ans, \".row_names\")) &&\n is_discrete_design(row_design)) {\n ans$.discrete_y <- reorder(\n .subset2(ans, \".row_names\"),\n .subset2(ans, \".y\"),\n order = FALSE\n )\n }\n if (!is.null(.subset2(ans, \".column_names\")) &&\n is_discrete_design(column_design)) {\n ans$.discrete_x <- reorder(\n .subset2(ans, \".column_names\"),\n .subset2(ans, \".x\"),\n order = FALSE\n )\n }\n ggalign_data_restore(ans, data)\n}\n"], ["/ggalign/R/alignpatch-wrap.R", "#' Wrap Arbitrary Graphics to ggplot\n#'\n#' The `ggwrap()` function allows non-ggplot2 elements to be converted into a\n#' compliant representation for use with [`align_plots()`]. This is useful for\n#' adding any graphics that can be converted into a [`grob`][grid::grob] with\n#' the [`patch()`] method.\n#'\n#' @param plot Any graphic that can be converted into a [`grob`][grid::grob]\n#' using [`patch()`].\n#' @param ... Additional arguments passed to the [`patch()`] method.\n#' @param align A string specifying the area to place the plot: `\"full\"` for the\n#' full area, `\"plot\"` for the full plotting area (including the axis label), or\n#' `\"panel\"` for only the actual area where data is drawn.\n#' @param clip A single boolean value indicating whether the grob should be\n#' clipped if they expand outside their designated area.\n#' @param on_top A single boolean value indicates whether the graphic plot\n#' should be put frontmost. Note: the graphic plot will always put above the\n#' background.\n#' @param vp A [`viewport`][grid::viewport] object, you can use this to define\n#' the plot area.\n#' @return A `wrapped_plot` object that can be directly placed into\n#' [`align_plots()`].\n#' @inherit patch seealso\n#' @examples\n#' library(grid)\n#' ggwrap(rectGrob(gp = gpar(fill = \"goldenrod\")), align = \"full\") +\n#' inset(rectGrob(gp = gpar(fill = \"steelblue\")), align = \"panel\") +\n#' inset(textGrob(\"Here are some text\", gp = gpar(color = \"black\")),\n#' align = \"panel\"\n#' )\n#' p1 <- ggplot(mtcars) +\n#' geom_point(aes(mpg, disp)) +\n#' ggtitle(\"Plot 1\")\n#' align_plots(p1, ggwrap(\n#' ~ plot(mtcars$mpg, mtcars$disp),\n#' mar = c(0, 2, 0, 0), bg = NA\n#' ))\n#'\n#' @importFrom ggplot2 theme element_blank ggplot\n#' @importFrom grid is.grob\n#' @export\nggwrap <- function(plot, ..., align = \"panel\", on_top = FALSE,\n clip = TRUE, vp = NULL) {\n patch <- ggplot() +\n theme(\n plot.background = element_blank(),\n panel.background = element_blank()\n )\n inset <- make_inset(\n plot = plot, ..., align = align, on_top = on_top,\n clip = clip, vp = vp\n )\n make_wrap(patch, inset)\n}\n\nmake_wrap <- function(patch, inset) UseMethod(\"make_wrap\")\n\nmake_wrapped_plot <- function(patch, inset) {\n if (.subset2(inset, \"on_top\")) {\n patch$ggalign_wrapped_insets_above <- c(\n patch$ggalign_wrapped_insets_above, list(inset)\n )\n } else {\n patch$ggalign_wrapped_insets_under <- c(\n patch$ggalign_wrapped_insets_under, list(inset)\n )\n }\n add_class(patch, \"wrapped_plot\")\n}\n\n#' @export\nmake_wrap.ggplot <- function(patch, inset) {\n patch <- add_class(patch, \"patch_ggplot\")\n make_wrap(patch, inset)\n}\n\n#' @export\nmake_wrap.patch_ggplot <- make_wrapped_plot\n\n#' @export\nmake_wrap.alignpatches <- make_wrapped_plot\n\n#################################################\n#' @importFrom ggplot2 ggproto ggproto_parent\n#' @export\nalignpatch.wrapped_plot <- function(x) {\n Parent <- NextMethod()\n ggproto(\n \"PatchWrapped\", Parent,\n ggalign_wrapped_insets_under = x$ggalign_wrapped_insets_under,\n ggalign_wrapped_insets_above = x$ggalign_wrapped_insets_above,\n patch_gtable = function(self, theme, guides, plot = Parent$plot) {\n ans <- ggproto_parent(Parent, self)$patch_gtable(\n theme = theme, guides = guides, plot = plot\n )\n ans <- add_wrapped_insets(\n ans, self$ggalign_wrapped_insets_under, FALSE\n )\n add_wrapped_insets(ans, self$ggalign_wrapped_insets_above, TRUE)\n }\n )\n}\n\n# For wrapped plot -------------------\n#' @export\nalignpatch.grob <- function(x) alignpatch(ggwrap(x))\n\n#' @export\nalignpatch.gList <- alignpatch.grob\n\n#' @export\nalignpatch.formula <- alignpatch.grob\n\n#' @export\nalignpatch.function <- alignpatch.grob\n\n#' @export\nalignpatch.recordedplot <- alignpatch.grob\n\n#' @export\nalignpatch.trellis <- alignpatch.grob\n\n#' @export\nalignpatch.Heatmap <- function(x) alignpatch(ggwrap(x, align = \"full\"))\n\n#' @export\nalignpatch.HeatmapList <- alignpatch.Heatmap\n\n#' @export\nalignpatch.HeatmapAnnotation <- alignpatch.Heatmap\n\n#' @export\nalignpatch.pheatmap <- function(x) alignpatch(ggwrap(x, align = \"full\"))\n\n################################################## 3\nadd_wrapped_insets <- function(gt, insets, on_top) {\n if (is.null(insets)) return(gt) # styler: off\n for (i in seq_along(insets)) {\n gt <- add_wrapped_inset(gt, .subset2(insets, i), on_top, i)\n }\n gt\n}\n\n#' @importFrom gtable gtable is.gtable gtable_add_grob\nadd_wrapped_inset <- function(gt, inset, on_top, i) {\n align <- .subset2(inset, \"align\")\n clip <- .subset2(inset, \"clip\")\n layout <- .subset2(gt, \"layout\")\n grob <- .subset2(inset, \"grob\")\n if (on_top) {\n z <- Inf\n } else {\n background <- .subset2(layout, \"name\") == \"background\"\n z <- .subset2(layout, \"z\")[background] + 1L\n gt$layout$z[layout$z >= z] <- layout$z[layout$z >= z] + 1L\n }\n\n # add the grob to the gtable\n if (align == \"full\") {\n gt <- gtable_add_grob(gt,\n list(grob), 1L, 1L, nrow(gt), ncol(gt),\n clip = clip, name = sprintf(\"wrap-full-%d\", i), z = z\n )\n } else {\n panel_loc <- find_panel(gt)\n gt <- switch(align,\n plot = gtable_add_grob(gt,\n list(grob),\n .subset2(panel_loc, \"t\") - 3L,\n .subset2(panel_loc, \"l\") - 3L,\n .subset2(panel_loc, \"b\") + 3L,\n .subset2(panel_loc, \"r\") + 3L,\n clip = clip, name = sprintf(\"wrap-plot-%d\", i), z = z\n ),\n panel = gtable_add_grob(gt,\n list(grob),\n .subset2(panel_loc, \"t\"),\n .subset2(panel_loc, \"l\"),\n .subset2(panel_loc, \"b\"),\n .subset2(panel_loc, \"r\"),\n clip = clip, name = sprintf(\"wrap-panel-%d\", i), z = z\n )\n )\n }\n gt\n}\n"], ["/ggalign/R/layout-chain-circle-build.R", "#' @export\nggalign_build.CircleLayout <- function(x) {\n x <- default_layout(x)\n circle_build(x)\n}\n\n#' @importFrom utils packageVersion\n#' @importFrom ggplot2 find_panel calc_element ggproto ggplotGrob theme\n#' @importFrom gtable gtable_add_grob gtable_add_padding is.gtable\n#' @importFrom grid unit viewport editGrob\n#' @importFrom rlang is_empty arg_match0\ncircle_build <- function(circle, schemes = NULL, theme = NULL) {\n schemes <- inherit_parent_layout_schemes(circle, schemes)\n theme <- inherit_parent_layout_theme(circle, theme)\n # for empty plot\n base <- ggplot() +\n theme +\n ggplot2::labs(\n title = .subset2(circle@titles, \"title\"),\n subtitle = .subset2(circle@titles, \"subtitle\"),\n caption = .subset2(circle@titles, \"caption\")\n )\n if (is_empty(plot_list <- circle@plot_list)) {\n return(ggplotGrob(base))\n }\n\n # we remove the plot without actual plot area\n keep <- vapply(plot_list, function(plot) {\n !is.null(plot@plot)\n }, logical(1L), USE.NAMES = FALSE)\n plot_list <- .subset(plot_list, keep)\n if (is_empty(plot_list)) return(ggplotGrob(base)) # styler: off\n\n # we reorder the plots based on the `order` slot\n plot_order <- vapply(plot_list, function(plot) {\n .subset2(plot@active, \"order\")\n }, integer(1L), USE.NAMES = FALSE)\n plot_list <- .subset(plot_list, make_order(plot_order))\n\n # plot coordinate\n if (is.null(input_radial <- circle@radial)) {\n radial <- coord_circle(theta = \"x\", r.axis.inside = TRUE)\n } else {\n radial <- ggproto(NULL, input_radial, theta = \"x\", r_axis_inside = TRUE)\n }\n\n sizes <- vapply(plot_list, function(plot) {\n # for circular layout, we only support relative size\n if (is.na(size <- as.numeric(plot@size))) {\n size <- 1\n }\n size\n }, numeric(1L), USE.NAMES = FALSE)\n\n # For each plot track, relative to the total radius (1):\n # 1. total radius: 1\n # 2. total radius for the plot area (for each plot track): 1 - inner_radius\n if (inherits(radial, \"CoordCircle\")) {\n inner_radius <- radial$inner_radius[1L] / 0.5\n outer_radius <- radial$inner_radius[2L] / 0.5\n } else {\n # For `CoordRadial`\n # `0.4` is coord_radial used for scale size in ggplot2 to add extra\n # spaces for axis labels\n # https://github.com/tidyverse/ggplot2/issues/6284\n inner_radius <- radial$inner_radius[1L] / 0.4\n outer_radius <- radial$inner_radius[2L] / 0.4\n }\n plot_track <- sizes / sum(sizes) * (outer_radius - inner_radius)\n\n # For each plot, the plot size is calculated by adding the space for the\n # inner radius of each track.\n N <- length(plot_list)\n index <- seq_len(N)\n direction <- circle@direction\n if (identical(direction, \"outward\")) {\n plot_sizes <- inner_radius + cumsum(plot_track)\n } else {\n plot_sizes <- outer_radius -\n cumsum(c(0, utils::head(plot_track, -1L)))\n # The plots are always build outward, so the order is reversed.\n index <- rev(index)\n }\n\n # For each plot, the inner radius is calculated as the difference between\n # the plot size and its track size.\n plot_inner <- plot_sizes - plot_track\n guides <- vector(\"list\", N)\n plot_table <- NULL\n design <- setup_design(circle@design)\n for (i in index) {\n plot_size <- plot_sizes[[i]]\n plot <- .subset2(plot_list, i)\n craftsman <- plot@craftsman # `Craftsman` object\n plot_schemes <- inherit_schemes(plot@schemes, schemes)\n # the actual plot\n plot <- plot@plot\n\n # we always use `null` facet\n # we won't respect `free_facet` and `free_coord`\n plot_coord <- gguse_circle_coord(\n plot,\n coord = radial,\n # https://github.com/tidyverse/ggplot2/issues/6284\n # Use `0.5` to remove the extra spaces for axis label\n inner_radius = c(\n plot_inner[[i]] / plot_size,\n # for the outmost plot, we respect the outer radius defined by\n # the users, for others, we alway use 1 to remove any spacing\n # between two tracks\n if (i == N) outer_radius else 1\n ) * 0.5,\n layout_name = craftsman$layout_name\n )\n if (!craftsman$free_facet) {\n if (is_discrete_design(design)) {\n if (nlevels(.subset2(design, \"panel\")) > 1L) {\n plot <- plot + facet_sector(\n ggplot2::vars(.data$.panel),\n sector_spacing = circle@sector_spacing %||% (pi / 180),\n drop = FALSE\n )\n } else {\n plot <- ggmelt_facet(plot, ggplot2::facet_null())\n }\n } else {\n if (inherits(plot$facet, \"FacetSector\")) {\n plot <- ggfacet_modify(plot,\n sector_spacing = circle@sector_spacing %||% (pi / 180),\n drop = FALSE\n )\n } else {\n plot <- ggmelt_facet(plot, ggplot2::facet_null())\n }\n }\n }\n plot$coordinates <- plot_coord\n\n # set limits and default scales\n if (!craftsman$free_limits) {\n plot <- plot + ggalign_design(\n x = design,\n xlabels = .subset(craftsman$labels, .subset2(design, \"index\"))\n )\n }\n\n # let `Craftsman` add other components\n plot <- craftsman$build_plot(plot, design = design)\n plot <- craftsman$finish_plot(\n plot,\n schemes = plot_schemes, theme = theme\n )\n plot <- plot + ggplot2::labs(x = NULL, y = NULL) +\n theme(panel.border = element_blank())\n plot <- chain_decorate(circle, plot)\n\n # copied from `ggplot2:::ggplot_gtable`\n data <- ggplot2::ggplot_build(plot)\n plot <- data$plot\n plot_layout <- data$layout\n data <- data$data\n plot_theme <- complete_theme(plot$theme)\n\n geom_grobs <- ggfun(\"by_layer\")(\n function(l, d) l$draw_geom(d, plot_layout),\n plot$layers, data,\n \"converting geom to grob\"\n )\n gt <- plot_layout$render(geom_grobs, data, plot_theme, plot$labels)\n\n # for each inner gtable, we insert it to the panel area of the\n # outter gtable\n #\n # For bbox, `ggplot2::polar_bbox` always take (0.5, 0.5) as origin\n bbox <- ggfun(\"polar_bbox\")(\n plot_layout$coord$arc, margin = c(0, 0, 0, 0),\n inner_radius = plot_layout$coord$inner_radius\n )\n origin <- c(\n scales::rescale(0.5, from = bbox$x),\n scales::rescale(0.5, from = bbox$y)\n )\n spacing <- calc_element(\"panel.spacing.r\", plot_theme)\n\n if (is.null(plot_table)) {\n plot_table <- gt\n } else {\n # define the panel size of the inner track\n rescale_factor <- last_plot_size / plot_size\n\n # the spacer between two plots\n if (identical(direction, \"outward\")) {\n spacer <- last_spacing\n } else {\n spacer <- spacing\n }\n if (inherits(spacer, \"element_blank\") || is.null(spacer)) {\n spacer <- unit(0, \"mm\")\n }\n plot_table <- editGrob(plot_table, vp = viewport(\n width = unit(rescale_factor, \"npc\") - spacer,\n height = unit(rescale_factor, \"npc\") - spacer,\n x = origin[1L], y = origin[2L], just = just,\n default.units = \"native\", clip = \"off\"\n ))\n\n # add the inner track to the panel area of the outter track\n panel_loc <- find_panel(gt)\n plot_table <- gtable_add_grob(\n gt, plot_table,\n t = .subset2(panel_loc, \"t\"),\n l = .subset2(panel_loc, \"l\"),\n b = .subset2(panel_loc, \"b\"),\n r = .subset2(panel_loc, \"r\"),\n name = \"inner-track\"\n )\n }\n\n # build legends\n guides[i] <- list(plot$guides$assemble(plot_theme))\n\n # assign value for next loop\n just <- origin\n last_plot_size <- plot_size # the last plot panel size\n last_spacing <- spacing\n }\n\n # attach the guide legends\n guides <- collect_guides_list(guides, zeroGrob())\n theme$legend.spacing <- theme$legend.spacing %||% unit(0.5, \"lines\")\n theme$legend.spacing.y <- calc_element(\"legend.spacing.y\", theme)\n theme$legend.spacing.x <- calc_element(\"legend.spacing.x\", theme)\n theme$legend.box.spacing <- calc_element(\n \"legend.box.spacing\", theme\n ) %||% unit(0.2, \"cm\")\n legend_box <- .mapply(\n function(guides, guide_pos) assemble_guides(guides, guide_pos, theme),\n list(guides = guides, guide_pos = names(guides)),\n NULL\n )\n names(legend_box) <- names(guides)\n plot_table <- ggfun(\"table_add_legends\")(plot_table, legend_box, theme)\n\n # Title\n title <- element_render(\n theme, \"plot.title\", .subset2(circle@titles, \"title\"),\n margin_y = TRUE, margin_x = TRUE\n )\n title_height <- grobHeight(title)\n\n # Subtitle\n subtitle <- element_render(\n theme, \"plot.subtitle\", .subset2(circle@titles, \"subtitle\"),\n margin_y = TRUE, margin_x = TRUE\n )\n subtitle_height <- grobHeight(subtitle)\n\n # whole plot annotation\n caption <- element_render(\n theme, \"plot.caption\", .subset2(circle@titles, \"caption\"),\n margin_y = TRUE, margin_x = TRUE\n )\n caption_height <- grobHeight(caption)\n\n # positioning of title and subtitle is governed by plot.title.position\n # positioning of caption is governed by plot.caption.position\n # \"panel\" means align to the panel(s)\n # \"plot\" means align to the entire plot (except margins and tag)\n title_pos <- arg_match0(\n theme$plot.title.position %||% \"panel\",\n c(\"panel\", \"plot\"),\n arg_nm = \"plot.title.position\",\n error_call = quote(theme())\n )\n\n caption_pos <- arg_match0(\n theme$plot.caption.position %||% \"panel\",\n values = c(\"panel\", \"plot\"),\n arg_nm = \"plot.caption.position\",\n error_call = quote(theme())\n )\n\n pans <- plot_table$layout[\n grepl(\"^panel\", plot_table$layout$name), ,\n drop = FALSE\n ]\n if (title_pos == \"panel\") {\n title_l <- min(pans$l)\n title_r <- max(pans$r)\n } else {\n title_l <- 1\n title_r <- ncol(plot_table)\n }\n if (caption_pos == \"panel\") {\n caption_l <- min(pans$l)\n caption_r <- max(pans$r)\n } else {\n caption_l <- 1\n caption_r <- ncol(plot_table)\n }\n\n plot_table <- gtable_add_rows(plot_table, subtitle_height, pos = 0)\n plot_table <- gtable_add_grob(plot_table, subtitle,\n name = \"subtitle\",\n t = 1, b = 1, l = title_l, r = title_r, clip = \"off\"\n )\n\n plot_table <- gtable_add_rows(plot_table, title_height, pos = 0)\n plot_table <- gtable_add_grob(plot_table, title,\n name = \"title\",\n t = 1, b = 1, l = title_l, r = title_r, clip = \"off\"\n )\n\n plot_table <- gtable_add_rows(plot_table, caption_height, pos = -1)\n plot_table <- gtable_add_grob(plot_table, caption,\n name = \"caption\",\n t = -1, b = -1, l = caption_l, r = caption_r, clip = \"off\"\n )\n plot_table <- ggfun(\"table_add_tag\")(plot_table, NULL, theme)\n\n # Margins\n plot_margin <- calc_element(\"plot.margin\", theme) %||% margin()\n plot_table <- gtable_add_padding(plot_table, plot_margin)\n\n if (inherits(theme$plot.background, \"element\")) {\n plot_table <- gtable_add_grob(plot_table,\n element_render(theme, \"plot.background\"),\n t = 1, l = 1, b = -1, r = -1, name = \"background\", z = -Inf\n )\n plot_table$layout <- plot_table$layout[\n c(nrow(plot_table$layout), 1:(nrow(plot_table$layout) - 1)),\n ]\n plot_table$grobs <- plot_table$grobs[\n c(nrow(plot_table$layout), 1:(nrow(plot_table$layout) - 1))\n ]\n }\n\n # add alt-text as attribute\n # attr(plot_table, \"alt-label\") <- plot$labels$alt\n strip_pos <- find_strip_pos(plot_table)\n\n # always add strips columns and/or rows\n plot_table <- add_strips(plot_table, strip_pos)\n setup_patch_titles(plot_table, patch_titles = list(\n top = NULL, left = NULL, bottom = NULL, right = NULL\n ), theme = theme)\n}\n"], ["/ggalign/R/layout-chain-stack-switch.R", "#########################################################\n#' Determine the active context of stack layout\n#'\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' `stack_active` is an alias for `stack_switch()`, which sets `what = NULL` by\n#' default.\n#'\n#' @inheritParams rlang::args_dots_empty\n#' @inheritParams quad_switch\n#' @inheritParams stack_discrete\n#' @param what What should get activated for the stack layout?\n#' `r rd_chain_what()`, this is useful when the active context is a\n#' [`quad_layout()`] object, where any `align_*()` will be added to the\n#' [`quad_layout()`]. By removing the active context, we can add `align_*()`\n#' into the [`stack_layout()`].\n#' @return A `stack_switch` object which can be added to [stack_layout()].\n#' @examples\n#' stack_discrete(\"h\", matrix(1:9, nrow = 3L)) +\n#' ggheatmap() +\n#' # ggheamtap will set the active context, directing following addition\n#' # into the heatmap plot area. To remove the heatmap active context,\n#' # we can use `stack_active()` which will direct subsequent addition into\n#' # the stack\n#' stack_active() +\n#' # here we add a dendrogram to the stack.\n#' align_dendro()\n#' @export\nstack_switch <- function(sizes = NULL, what = waiver(), ...) {\n rlang::check_dots_empty()\n if (!is.waive(what)) what <- check_stack_context(what)\n if (!is.null(sizes)) sizes <- check_stack_sizes(sizes)\n structure(list(what = what, sizes = sizes), class = \"stack_switch\")\n}\n\n#' @export\n#' @rdname stack_switch\nstack_active <- function(sizes = NULL, ...) {\n rlang::check_dots_empty()\n stack_switch(sizes, what = NULL)\n}\n"], ["/ggalign/R/layout-quad-add.R", "#' @keywords internal\nquad_layout_add <- function(object, quad, object_name) {\n UseMethod(\"quad_layout_add\")\n}\n\n#############################################################\n#' @export\nquad_layout_add.layout_title <- function(object, quad, object_name) {\n quad@titles <- update_non_waive(quad@titles, object)\n quad\n}\n\n##############################################################\n# Preventing from adding following elements\n#' @export\nquad_layout_add.matrix <- function(object, quad, object_name) {\n cli_abort(sprintf(\"Can't change data of %s\", object_name(quad)))\n}\n\n#' @export\nquad_layout_add.data.frame <- quad_layout_add.matrix\n\n#############################################################\n# Add elements for the main body or the annotation\n#' @importFrom methods slot slot<-\n#' @export\nquad_layout_add.default <- function(object, quad, object_name) {\n if (is.null(position <- quad@active)) {\n quad <- quad_body_add(object, quad, object_name)\n } else if (is.null(stack <- slot(quad, position))) {\n cli_abort(c(\n sprintf(\"Cannot add {.var {object_name}} to %s\", object_name(quad)),\n i = \"the {.field {position}} annotation stack is not initialized\",\n i = \"Try to use {.code quad_anno(initialize = TRUE)} or you can add a {.code stack_layout()} manually\"\n ))\n } else {\n slot(quad, position) <- chain_layout_add(object, stack, object_name)\n }\n quad\n}\n\n#' @export\nquad_layout_add.list <- function(object, quad, object_name) {\n for (o in object) quad <- quad_layout_add(o, quad, object_name)\n quad\n}\n\n#' @export\nquad_layout_add.NULL <- function(object, quad, object_name) {\n quad\n}\n\n#' @export\nquad_layout_add.ggalign_with_quad <- function(object, quad, object_name) {\n old <- quad@active\n contexts <- quad_operated_context(object, old, \"+\") %||%\n list(NULL) # we wrap `NULL` to a list for `for loop`.\n object <- .subset2(object, \"object\")\n object_name <- .subset2(object, \"object_name\")\n for (active in contexts) {\n quad@active <- active\n quad <- quad_layout_add(object, quad, object_name)\n }\n quad@active <- old\n quad\n}\n\n##################################################################\n#' @export\nquad_layout_add.quad_active <- function(object, quad, object_name) {\n if (!is.null(width <- .subset2(object, \"width\"))) {\n quad@width <- width\n }\n if (!is.null(height <- .subset2(object, \"height\"))) {\n quad@height <- height\n }\n quad@active <- NULL\n quad\n}\n\n#' @importFrom methods slot\n#' @export\nquad_layout_add.quad_anno <- function(object, quad, object_name) {\n position <- .subset2(object, \"position\")\n initialize <- .subset2(object, \"initialize\")\n stack <- slot(quad, position)\n if (is.null(stack) && !isFALSE(initialize)) {\n # try to initialize the annotation stack with the layout data\n direction <- to_direction(position)\n layout_design <- slot(quad, direction)\n # for the annotation stack, we try to take the data from the\n # quad layout\n quad_data <- quad@data\n data <- waiver() # use waiver() to indicate data is not initialized\n quad_matrix <- FALSE # the default value for `quad_matrix` in the stack\n if (is_continuous_design(layout_design)) { # the stack need a data frame\n if (!is.data.frame(quad_data)) {\n if (is.null(initialize)) {\n cli_warn(paste(\n \"`data` in {.fn {quad@name}} is\",\n \"{.obj_type_friendly {quad_data}}, but the\",\n \"{.field {position}} annotation stack need a\",\n \"{.cls data.frame}, won't initialize\",\n \"the {.field {position}} annotation stack\"\n ))\n } else {\n data <- NULL\n }\n } else {\n data <- quad_data\n }\n } else if (is.matrix(quad_data)) { # the stack need a matrix\n if (is_horizontal(direction)) {\n data <- quad_data\n } else {\n data <- ggalign_data_restore(t(quad_data), quad_data)\n }\n quad_matrix <- TRUE\n } else {\n if (is.null(initialize)) {\n cli_warn(paste(\n \"`data` in {.fn {quad@name}} is\",\n \"{.obj_type_friendly {quad_data}}, but the\",\n \"{.field {position}} annotation stack need a\",\n \"{.cls data.frame}, won't initialize\",\n \"the {.field {position}} annotation stack\"\n ))\n } else {\n data <- NULL\n }\n }\n if (!is.waive(data)) { # initialize the annotation stack\n stack <- new_stack_layout(\n data = data,\n direction = direction,\n # the layout parameters should be the same with `quad_layout()`\n design = layout_design,\n # we'll inherit the action data function when\n schemes = default_schemes(if (is.null(data)) NULL else waiver())\n )\n stack@heatmap$position <- position\n stack@heatmap$quad_matrix <- quad_matrix\n }\n } else if (!is.null(stack) && isTRUE(initialize)) {\n cli_abort(c(\n \"Cannot initialize the {position} annotation stack\",\n i = \"{position} annotation stack has already been initialized\"\n ))\n }\n\n if (!is.null(stack)) {\n # update parameters\n if (!is.null(size <- .subset2(object, \"size\"))) {\n stack@sizes <- size\n }\n if (!is.waive(free_guides <- .subset2(object, \"free_guides\"))) {\n stack@heatmap[\"free_guides\"] <- list(free_guides)\n }\n stack <- switch_chain_plot(\n stack, .subset2(object, \"what\"), quote(quad_anno())\n )\n slot(quad, position) <- stack\n }\n quad@active <- position\n quad\n}\n\n#' @export\nquad_layout_add.QuadLayout <- function(object, quad, object_name) {\n cli_abort(c(\n sprintf(\"Cannot add {.var {object_name}} to %s\", object_name(quad)),\n i = \"Did you mean to place multiple {.fn quad_layout} elements inside a {.fn stack_layout}?\"\n ))\n}\n\n#' @export\nquad_layout_add.StackLayout <- function(object, quad, object_name) {\n # we check if there is an active annotation\n if (is.null(position <- quad@active)) {\n cli_abort(c(\n sprintf(\"Cannot add {.var {object_name}} to %s\", object_name(quad)),\n i = \"no active annotation stack\",\n i = \"try to activate an annotation stack with {.fn anno_*}\"\n ))\n }\n # check the annotation stack is not initialized\n if (!is.null(slot(quad, position))) {\n cli_abort(c(\n sprintf(\"Cannot add {.var {object_name}} to %s\", object_name(quad)),\n i = \"{position} annotation stack already exists\"\n ))\n }\n # cannot contain nested layout\n if (!all(vapply(object@plot_list, is_craftbox, logical(1L),\n USE.NAMES = FALSE))) { # styler: off\n cli_abort(c(\n sprintf(\"Cannot add {.var {object_name}} to %s\", object_name(quad)),\n i = \"annotation stack cannot contain nested layout\"\n ))\n }\n # check quad layout is compatible with stack layout\n if (!identical(direction <- to_direction(position), object@direction)) {\n cli_abort(c(\n sprintf(\"Cannot add {.var {object_name}} to %s\", object_name(quad)),\n i = \"only {.field {direction}} stack is allowed in {position} annotation\"\n ))\n }\n if (length(object@sizes) > 1L) {\n cli_abort(c(\n sprintf(\"Cannot add {.var {object_name}} to %s\", object_name(quad)),\n i = \"{.arg sizes} must be of length one to use the stack as an annotation\"\n ))\n }\n quad_design <- slot(quad, direction)\n if (is_cross_layout(object) &&\n any(position == c(\"bottom\", \"right\")) &&\n !is_empty(object@cross_points)) {\n # if there are cross points in bottom or right annotation,\n # use the first design\n stack_design <- .subset2(object@odesign, 1L)\n } else {\n stack_design <- object@design\n }\n # check if we can align in this direction\n # `stack_layout()` is free from aligning obervations in this axis\n if (is_continuous_design(stack_design)) {\n if (!is_continuous_design(quad_design)) {\n cli_abort(c(\n sprintf(\n \"Cannot add {.var {object_name}} to %s\",\n object_name(quad)\n ),\n i = sprintf(\n \"%s cannot align continuous variable in {.field {direction}} direction\",\n object_name(quad)\n )\n ))\n }\n layout_design <- stack_design\n } else if (is_discrete_design(quad_design)) {\n layout_design <- melt_discrete_design(\n quad_design, stack_design,\n old_name = object_name(quad),\n new_name = object_name\n )\n } else {\n cli_abort(c(\n sprintf(\"Cannot add {.var {object_name}} to %s\", object_name(quad)),\n i = sprintf(\n \"%s cannot align discrete variable in {.field {direction}} direction\",\n object_name(quad)\n )\n ))\n }\n object@heatmap$position <- position\n slot(quad, position) <- object\n update_design(quad,\n direction = direction,\n design = layout_design,\n object_name = object_name\n )\n}\n\n#' @importFrom methods slot slot<-\n#' @export\nquad_layout_add.CraftBox <- function(object, quad, object_name) {\n if (is.null(position <- quad@active)) {\n cli_abort(c(\n sprintf(\"Cannot add {.var {object_name}} to %s\", object_name(quad)),\n i = \"no active annotation stack\",\n i = \"try to activate an annotation stack with {.fn anno_*}\"\n ))\n }\n if (is.null(stack <- slot(quad, position))) {\n cli_abort(c(\n sprintf(\"Cannot add {.var {object_name}} to %s\", object_name(quad)),\n i = \"the {.field {position}} annotation stack is not initialized\",\n i = \"Try to use {.code quad_anno(initialize = TRUE)} or you can add a {.code stack_layout()} manually\"\n ))\n }\n\n # add annotation -----------------------------\n stack <- chain_layout_add(object, stack, object_name)\n slot(quad, position) <- stack\n\n # if there are cross points in bottom or right annotation, we use\n # the first design\n if (is_cross_layout(stack) &&\n any(position == c(\"bottom\", \"right\")) &&\n !is_empty(stack@cross_points)) {\n new_design <- .subset2(stack@odesign, 1L)\n } else {\n new_design <- stack@design\n }\n\n update_design(\n quad,\n direction = to_direction(position),\n design = new_design,\n object_name = object_name\n )\n}\n\n#######################################################\n# used to add elements for main body\n#' @keywords internal\nquad_body_add <- function(object, quad, object_name) {\n UseMethod(\"quad_body_add\")\n}\n\n#' @importFrom ggplot2 ggplot_add\n#' @export\nquad_body_add.default <- function(object, quad, object_name) {\n quad@plot <- ggplot_add(object, ggfun(\"plot_clone\")(quad@plot), object_name)\n quad\n}\n\n#' @export\nquad_body_add.Coord <- function(object, quad, object_name) {\n if (!inherits(object, \"CoordCartesian\")) {\n cli_warn(c(\n \"only {.field cartesian coordinate} is supported\",\n i = \"will discard {.var {object_name}} directly\"\n ))\n return(quad)\n }\n NextMethod() # call default method\n}\n\n#' @export\nquad_body_add.layout_theme <- function(object, quad, object_name) {\n quad@theme <- update_layout_theme(quad@theme, object)\n quad\n}\n\n#' @export\nquad_body_add.ggalign_scheme <- function(object, quad, object_name) {\n name <- ggalign_scheme_name(object)\n quad@body_schemes[name] <- list(update_scheme(\n object, .subset2(quad@body_schemes, name), object_name\n ))\n quad\n}\n"], ["/ggalign/R/scheme-theme.R", "#' Plot default theme\n#'\n#' @description\n#' `r lifecycle::badge('experimental')`\n#'\n#' `scheme_theme()` serves as the default theme and will always be overridden by\n#' any `theme()` settings applied directly to the plot. The default theme\n#' (`scheme_theme()`) is applied first, followed by any specific `theme()`\n#' settings, even if `theme()` is added before `scheme_theme()`.\n#'\n#' @inherit ggplot2::theme\n#' @param ... A [`theme()`][ggplot2::theme] object or additional element\n#' specifications not part of base ggplot2. In general, these should also be\n#' defined in the `element tree` argument. [`Splicing`][rlang::splice] a list\n#' is also supported.\n#' @examples\n#' set.seed(123)\n#' small_mat <- matrix(rnorm(56), nrow = 8)\n#' ggheatmap(small_mat) +\n#' scheme_theme(plot.background = element_rect(fill = \"red\"))\n#'\n#' # `scheme_theme()` serves as the default theme and will always be\n#' # overridden by any `theme()` settings applied directly to the plot\n#' ggheatmap(small_mat) +\n#' theme(plot.background = element_rect(fill = \"blue\")) +\n#' scheme_theme(plot.background = element_rect(fill = \"red\"))\n#'\n#' @importFrom ggplot2 theme\n#' @importFrom rlang inject\n#' @export\nscheme_theme <- rlang::new_function(\n # We utilize editor completion by listing all `theme()` arguments here.\n # By placing `...` at the beginning, we can check if the first\n # following argument is a `theme()` object rather than individual theme\n # elements.\n c(\n rlang::exprs(... = ),\n .subset(\n rlang::fn_fmls(theme),\n vec_set_difference(names(rlang::fn_fmls(theme)), \"...\")\n )\n ),\n quote({\n elements <- ggfun(\"find_args\")(..., complete = NULL, validate = NULL)\n ans <- theme(!!!elements)\n th <- NULL\n for (i in seq_len(...length())) {\n if (inherits(t <- ...elt(i), \"theme\")) {\n th <- ggfun(\"add_theme\")(th, t)\n }\n }\n new_scheme_theme(ggfun(\"add_theme\")(th, ans))\n })\n)\n\n#' @importFrom ggplot2 theme\nnew_scheme_theme <- function(th = theme()) {\n # I don't know why, if I omit the `object = th` argument, it won't work\n UseMethod(\"new_scheme_theme\", th)\n}\n\n#' @importFrom rlang inject\n#' @export\nnew_scheme_theme.theme <- function(th = theme()) {\n attrs <- attributes(th)\n attrs <- vec_slice(\n attrs, vec_set_difference(names(attrs), c(\"names\", \"class\"))\n )\n inject(new_scheme(\n name = \"scheme_theme\", th, !!!attrs,\n class = c(\"scheme_theme\", class(th))\n ))\n}\n\n#' @export\nnew_scheme_theme.scheme_theme <- function(th = theme()) th\n\n###############################################################\n#' @export\nupdate_scheme.scheme_theme <- function(new, old, object_name) {\n ggfun(\"add_theme\")(old, new, object_name)\n}\n\n#' @export\ninherit_scheme.scheme_theme <- function(scheme, pscheme) {\n pscheme + scheme\n}\n\n#' @export\nplot_add_scheme.scheme_theme <- function(plot, scheme) {\n # setup plot theme\n plot$theme <- scheme + plot$theme\n plot\n}\n"], ["/ggalign/R/fortify-data-frame-dendrogram.R", "#' @inherit fortify_data_frame.default title description\n#'\n#' @param data A [`hclust`][stats::hclust] or a\n#' [`dendrogram`][stats::as.dendrogram] object.\n#' @param center A boolean value. if `TRUE`, nodes are plotted centered with\n#' respect to all leaves/tips in the branch. Otherwise (default), plot them in\n#' the middle of the direct child nodes.\n#' @param type A string indicates the plot type, `\"rectangle\"` or `\"triangle\"`.\n#' @param leaf_pos The x-coordinates of the leaf node. Must be the same length\n#' of the number of observations in `tree`.\n#' @param leaf_braches Branches of the leaf node. Must be the same length of the\n#' number of observations in `tree`. Usually come from [cutree][stats::cutree].\n#' @param reorder_branches A single boolean value, indicates whether reorder the\n#' provided `leaf_braches` based on the actual index.\n#' @param branch_gap A single numeric value indicates the gap between different\n#' branches.\n#' @param root A length one string or numeric indicates the root branch.\n#' @param priority A string of \"left\" or \"right\". if we draw from `right` to\n#' `left`, the left will override the right, so we take the `\"left\"` as the\n#' priority. If we draw from `left` to `right`, the right will override the\n#' left, so we take the `\"right\"` as priority. This is used by\n#' [`align_dendro()`] to provide support of facet operation in ggplot2.\n#' @param double A single logical value indicating whether horizontal lines\n#' should be doubled when segments span multiple branches. If `TRUE`, the\n#' horizontal lines will be repeated for each branch that the segment spans. If\n#' `FALSE`, only one horizontal line will be drawn. This is used by\n#' [`align_dendro()`] to provide support of facet operation in ggplot2.\n#' @inheritParams fortify_data_frame\n#' @return A `data frame` with the node coordinates:\n#' - `.panel`: Similar with `panel` column, but always give the correct\n#' branch for usage of the ggplot facet.\n#' - `.index`: the original index in the tree for the the node\n#' - `label`: node label text\n#' - `x` and `y`: x-axis and y-axis coordinates for the node\n#' - `branch`: which branch the node is. You can use this column to color\n#' different groups.\n#' - `panel`: which panel the node is, if we split the plot into panel\n#' using [facet_grid][ggplot2::facet_grid], this column will show\n#' which panel the node is from. Note: some nodes may\n#' fall outside panel (between two panels), so there are possible\n#' `NA` values in this column.\n#' - `leaf`: A logical value indicates whether the node is a leaf.\n#' @section ggalign attributes:\n#' `edge`: A `data frame` for edge coordinates:\n#' - `.panel`: Similar with `panel` column, but always give the correct\n#' branch for usage of the ggplot facet.\n#' - `x` and `y`: x-axis and y-axis coordinates for the start node of the edge.\n#' - `xend` and `yend`: the x-axis and y-axis coordinates of the terminal node\n#' for edge.\n#' - `branch`: which branch the edge is. You can use this column to color\n#' different groups.\n#' - `panel1` and `panel2`: The panel1 and panel2 columns have the same\n#' functionality as `panel`, but they are specifically for the `edge` data\n#' and correspond to both nodes of each edge.\n#' @examples\n#' fortify_data_frame(hclust(dist(USArrests), \"ave\"))\n#' @importFrom grid is.unit\n#' @importFrom stats order.dendrogram\n#' @importFrom rlang arg_match0\n#' @family fortify_data_frame\n#' @export\nfortify_data_frame.dendrogram <- function(data, ...,\n priority = \"right\",\n center = FALSE,\n type = \"rectangle\",\n leaf_pos = NULL,\n leaf_braches = NULL,\n reorder_branches = TRUE,\n branch_gap = NULL,\n root = NULL,\n double = TRUE,\n data_arg = NULL, call = NULL) {\n call <- call %||% current_call()\n data_arg <- data_arg %||% \"data\"\n rlang::check_dots_empty(call = call)\n assert_bool(center, call = call)\n assert_bool(reorder_branches, call = call)\n type <- arg_match0(type, c(\"rectangle\", \"triangle\"), error_call = call)\n priority <- arg_match0(priority, c(\"left\", \"right\"), error_call = call)\n N <- stats::nobs(data)\n rectangle <- type == \"rectangle\"\n if (is.null(leaf_pos)) {\n leaf_pos <- seq_len(N)\n } else if (length(leaf_pos) != N) {\n cli_abort(\n \"{.arg leaf_pos} must be of the same length of {.arg tree}\",\n call = call\n )\n }\n\n # if no branches provided, all branch will be regarded as the `root`\n if (is.null(leaf_braches)) {\n root <- root %||% \"root\"\n } else if (anyNA(leaf_braches)) {\n cli_abort(\"`NA` is not allowed in {.arg leaf_braches}\",\n call = call\n )\n } else if (length(leaf_braches) != N) {\n cli_abort(\n \"{.arg leaf_braches} must be of the same length of {.arg tree}\",\n call = call\n )\n } else if (is.character(leaf_braches)) {\n root <- root %||% \"root\"\n } else if (is.factor(leaf_braches)) {\n leaf_braches <- as.character(leaf_braches)\n root <- root %||% \"root\"\n } else if (is.numeric(leaf_braches)) {\n root <- root %||% (min(leaf_braches) - 1L)\n } else {\n cli_abort(\"{.arg leaf_braches} must be a character or numeric\",\n call = call\n )\n }\n\n if (!is.null(leaf_braches) && reorder_branches) {\n leaf_braches <- .subset(leaf_braches, order.dendrogram(data))\n }\n\n # check `branch_gap`\n if (is.numeric(branch_gap)) {\n if (!is_scalar(branch_gap)) {\n cli_abort(\"{.arg branch_gap} must be of length 1\",\n call = call\n )\n }\n } else if (is.null(branch_gap)) {\n branch_gap <- 0\n } else {\n cli_abort(\"{.arg branch_gap} must be numeric value.\",\n call = call\n )\n }\n\n # the root value shouldn't be the same of leaf branches.\n if (!is_scalar(root)) {\n cli_abort(\"{.arg root} must be of length 1\", call = call)\n } else if (anyNA(root)) {\n cli_abort(\"{.arg root} cannot be `NA`\", call = call)\n } else if (any(root == leaf_braches)) {\n cli_abort(\n \"{.arg root} cannot contain value in {.arg leaf_braches}\",\n call = call\n )\n }\n\n # initialize values\n i <- 0L # leaf index\n branch_levels <- NULL\n last_branch <- root\n total_gap <- 0\n dendrogram_data <- function(dend, from_root = TRUE) {\n if (stats::is.leaf(dend)) { # base version\n index <- as.integer(dend) # the column index of the original data\n y <- attr(dend, \"height\") %||% 0\n label <- attr(dend, \"label\") %||% NA\n i <<- i + 1L\n if (is.null(leaf_braches)) {\n branch <- root\n } else {\n branch <- .subset(leaf_braches, i)\n }\n\n x <- .subset(leaf_pos, i) + total_gap\n # for every new branch, we saved the branch for later use, in order\n # to order the branch levels, and we add a gap between two branch\n if (branch != last_branch) {\n branch_levels <<- c(branch_levels, branch)\n x <- x + branch_gap\n total_gap <<- total_gap + branch_gap\n }\n last_branch <<- branch\n\n node <- data_frame0(\n index = index, label = label,\n x = x, y = y, branch = branch,\n leaf = TRUE, panel = branch,\n ggpanel = branch\n )\n list(\n # current node\n node = node, edge = NULL,\n # current node information\n x = x, y = y,\n branch = branch,\n panel = branch,\n ggpanel = branch\n )\n } else if (inherits(dend, \"dendrogram\")) { # recursive version\n # the parent height -------------------------------------\n y <- attr(dend, \"height\")\n\n # for the children nodes ---------------------------------\n data <- list_transpose(\n lapply(dend, dendrogram_data, from_root = FALSE)\n )\n\n # node should be the direct children\n node <- vec_rbind(!!!.subset2(data, \"node\"))\n edge <- vec_rbind(!!!.subset2(data, \"edge\"))\n\n # all coordinate for direct children nodes -------------\n # following should be length 2\n direct_leaves_x <- unlist(\n .subset2(data, \"x\"),\n recursive = FALSE, use.names = FALSE\n )\n direct_leaves_y <- unlist(\n .subset2(data, \"y\"),\n recursive = FALSE, use.names = FALSE\n )\n direct_leaves_branch <- unlist(\n .subset2(data, \"branch\"),\n recursive = FALSE, use.names = FALSE\n )\n direct_leaves_panel <- unlist(\n .subset2(data, \"panel\"),\n recursive = FALSE, use.names = FALSE\n )\n direct_leaves_ggpanel <- unlist(\n .subset2(data, \"ggpanel\"),\n recursive = FALSE, use.names = FALSE\n )\n\n # prepare node data ------------------------------------\n\n # all x coordinate for children nodes --------------------\n # used if center is `TRUE`, we'll calculate the center position\n # among all children nodes\n leaves <- vec_slice(node, .subset2(node, \"leaf\")) # all leaves\n\n # we assign the `panel` for current branch node\n ranges <- split(\n .subset2(leaves, \"x\"),\n .subset2(leaves, \"panel\")\n )\n ranges <- ranges[\n order(vapply(ranges, min, numeric(1L), USE.NAMES = FALSE))\n ]\n full_panel <- names(ranges)\n\n # x coordinate for current branch: the midpoint\n if (center) {\n x <- sum(range(.subset2(leaves, \"x\"))) / 2L\n } else {\n x <- sum(direct_leaves_x) / 2L\n }\n if (is.null(leaf_braches)) { # no branches\n ggpanel <- panel <- branch <- root\n } else {\n # we assign the branch for current branch node\n branch <- unique(direct_leaves_branch)\n # if two children leaves are different, this branch should be\n # `root`, this is often used to color the segments\n if (length(branch) > 1L) branch <- root\n\n # we assign the `panel` for current branch node\n panel <- NA\n for (i in seq_along(ranges)) {\n if (x < min(.subset2(ranges, i))) {\n panel <- NA\n break\n } else if (x <= max(.subset2(ranges, i))) {\n panel <- .subset2(full_panel, i)\n break\n }\n }\n # if the node is between two panels, no panel\n # we choose the priority\n if (is.na(ggpanel <- panel)) {\n # it's not possible for an branch node live outside the\n # all panels - the left or right most. So `i` won't be 1 or\n # length(ranges). we don't need to check the argument\n ggpanel <- switch(priority,\n left = .subset(full_panel, i - 1L),\n right = .subset(full_panel, i)\n )\n }\n }\n\n # there is no node data in dendrogram root\n if (!from_root) {\n node <- vec_rbind(node, data_frame0(\n index = NA, label = NA,\n x = x, y = y, branch = branch, leaf = FALSE,\n panel = panel, ggpanel = ggpanel\n ))\n }\n\n # if it's the `rectangle`\n if (rectangle) {\n # 2 vertical lines\n vertical_lines <- data_frame0(\n x = direct_leaves_x,\n xend = direct_leaves_x,\n y = direct_leaves_y,\n yend = rep_len(y, 2L),\n branch = direct_leaves_branch,\n panel1 = direct_leaves_panel,\n panel2 = direct_leaves_panel,\n ggpanel = direct_leaves_ggpanel\n )\n # 2 horizontal lines\n # if the horizontal lines spanned multiple panels\n # we double the left line and the right line\n added_edge <- vec_rbind(\n vertical_lines,\n # left horizontal line\n make_horizontal(\n c(direct_leaves_x[1L], x),\n panels = c(direct_leaves_panel[1L], panel),\n ggpanels = c(direct_leaves_ggpanel[1L], ggpanel),\n y = y,\n branch = direct_leaves_branch[1L],\n ranges = ranges,\n full_panel = full_panel,\n double = double\n ),\n # right horizontal line\n make_horizontal(\n c(x, direct_leaves_x[2L]),\n panels = c(panel, direct_leaves_panel[2L]),\n ggpanels = c(ggpanel, direct_leaves_ggpanel[2L]),\n y = y,\n branch = direct_leaves_branch[2L],\n ranges = ranges,\n full_panel = full_panel,\n double = double\n )\n )\n } else {\n added_edge <- data_frame0(\n x = rep_len(x, 2L),\n xend = direct_leaves_x,\n y = rep_len(y, 2L),\n yend = direct_leaves_y,\n branch = direct_leaves_branch,\n panel1 = rep_len(panel, 2L),\n panel2 = direct_leaves_panel,\n ggpanel = rep_len(ggpanel, 2L)\n )\n }\n if (is.null(edge)) {\n edge <- added_edge\n } else {\n edge <- vec_rbind(edge, added_edge)\n }\n list(\n node = node, edge = edge,\n x = x, y = y, branch = branch,\n panel = panel, ggpanel = ggpanel\n )\n } else {\n cli_abort(\"Invalid {.cls dendrogram} provided in {.arg {data_arg}}\",\n call = call\n )\n }\n }\n ans <- dendrogram_data(data)\n node <- .subset2(ans, \"node\")\n edge <- .subset2(ans, \"edge\")\n\n # set factor levels for branch and panel ---------------\n panel_levels <- branch_levels\n branch_levels <- c(branch_levels, root)\n node$panel <- factor(.subset2(node, \"panel\"), panel_levels)\n node$branch <- factor(.subset2(node, \"branch\"), branch_levels)\n node$ggpanel <- factor(.subset2(node, \"ggpanel\"), panel_levels)\n if (!is.null(edge)) {\n edge$panel1 <- factor(.subset2(edge, \"panel1\"), panel_levels)\n edge$panel2 <- factor(.subset2(edge, \"panel2\"), panel_levels)\n edge$branch <- factor(.subset2(edge, \"branch\"), branch_levels)\n edge$ggpanel <- factor(.subset2(edge, \"ggpanel\"), panel_levels)\n }\n node <- rename(node, c(ggpanel = \".panel\", index = \".index\"))\n edge <- rename(edge, c(ggpanel = \".panel\"))\n ggalign_data_set(node, edge = edge)\n}\n\n#' @param ... Additional arguments passed to `dendrogram` method.\n#' @export\n#' @rdname fortify_data_frame.dendrogram\nfortify_data_frame.hclust <- function(data, ...) {\n fortify_data_frame.dendrogram(stats::as.dendrogram(data), ...)\n}\n\n#' @param ggpanels Won't be `NA`\n#' @noRd\nmake_horizontal <- function(x, panels, ggpanels, y, branch,\n ranges, full_panel = names(ranges),\n double = TRUE) {\n if (!isTRUE(double) || identical(ggpanels[1L], ggpanels[2L])) {\n # in the same panel\n data_frame0(\n x = x[1L],\n xend = x[2L],\n y = y,\n yend = y,\n branch = branch,\n panel1 = panels[1L],\n panel2 = panels[2L],\n ggpanel = ggpanels[1L]\n )\n } else {\n index <- match(ggpanels, full_panel)\n ending <- index[2L] # right index\n panel0 <- panels[1L]\n ggpanel0 <- ggpanels[1L]\n point0 <- x[1L] # the left point coordinate x\n out <- vector(\"list\", diff(index))\n right_index <- (index[1L] + 1L):ending\n for (i in seq_along(right_index)) {\n i1 <- .subset(right_index, i) # right index\n if (i1 == ending) {\n point1 <- x[2L]\n panel1 <- panels[2L]\n ggpanel1 <- ggpanels[2L]\n } else {\n point1 <- mean(range(.subset2(ranges, i1)))\n ggpanel1 <- panel1 <- .subset(full_panel, i1)\n }\n out[[i]] <- data_frame0(\n x = c(point0, point1),\n xend = c(point1, point0),\n y = y,\n yend = y,\n branch = branch,\n panel1 = c(panel0, panel1),\n panel2 = c(panel1, panel0),\n ggpanel = c(ggpanel0, ggpanel1)\n )\n point0 <- point1\n panel0 <- panel1\n ggpanel0 <- ggpanel1\n }\n vec_rbind(!!!out)\n }\n}\n"], ["/ggalign/R/ggplot-geom-pie.R", "#' Pie charts\n#' @section new aesthetics:\n#' - `angle`: the pie circle angle.\n#' - `angle0`: the initial pie circle angle.\n#' - `radius`: the circle radius.\n#' @inheritParams ggplot2::layer\n#' @inheritParams ggplot2::geom_polygon\n#' @inheritParams ggplot2::geom_path\n#' @param steps An integer indicating the number of steps to generate the pie\n#' chart radian. Increasing this value results in a smoother pie circular.\n#' @param clockwise A single boolean value indicates clockwise or not.\n#' @aesthetics GeomPie\n#' @examples\n#' ggplot(data.frame(x = 1:10, y = 1:10, value = 1:10 / sum(1:10))) +\n#' geom_pie(aes(x, y, angle = value * 360))\n#' @export\ngeom_pie <- function(mapping = NULL, data = NULL, stat = \"identity\",\n position = \"identity\", ...,\n clockwise = TRUE, steps = 100,\n lineend = \"butt\", linejoin = \"round\", linemitre = 10,\n na.rm = FALSE,\n show.legend = NA, inherit.aes = TRUE) {\n ggplot2::layer(\n data = data,\n mapping = mapping,\n stat = stat,\n geom = GeomPie,\n position = position,\n show.legend = show.legend,\n inherit.aes = inherit.aes,\n params = list(\n lineend = lineend,\n linejoin = linejoin,\n linemitre = linemitre,\n clockwise = clockwise,\n na.rm = na.rm, steps = steps, ...\n )\n )\n}\n\n#' @importFrom grid gpar\n#' @importFrom ggplot2 ggproto aes resolution fill_alpha\n#' @importFrom rlang set_names\nGeomPie <- ggproto(\"GeomPie\",\n ggplot2::GeomPolygon,\n default_aes = aes(\n !!!set_names(\n ggplot2::GeomPolygon$default_aes,\n function(nms) {\n nms <- set_names(nms)\n vec_slice(nms, \"subgroup\") <- \"radius\"\n nms\n }\n ),\n angle0 = 0\n ),\n non_missing_aes = c(\"x\", \"y\", \"angle\", \"angle0\", \"radius\"),\n required_aes = c(\"x\", \"y\", \"angle\"),\n handle_na = ggplot2::Geom$handle_na,\n setup_params = function(self, data, params) {\n steps <- vec_cast(.subset2(params, \"steps\"), integer(),\n x_arg = \"steps\",\n call = call(snake_class(self))\n )\n assert_bool(.subset2(params, \"clockwise\"),\n arg = \"clockwise\", call = call(snake_class(self))\n )\n params$steps <- max(steps, 1L) + 1L\n params\n },\n setup_data = function(data, params) {\n # use the same strategy of geom_bar\n data$radius <- data$radius %||%\n params$radius %||% (\n min(\n vapply(\n split(data$x, data$PANEL, drop = TRUE),\n resolution, numeric(1),\n zero = FALSE,\n USE.NAMES = FALSE\n ),\n vapply(\n split(data$y, data$PANEL, drop = TRUE),\n resolution, numeric(1),\n zero = FALSE,\n USE.NAMES = FALSE\n )\n ) * 0.45)\n data\n },\n draw_panel = function(data, panel_params, coord, steps = 100L,\n clockwise = TRUE, lineend = \"butt\",\n linejoin = \"round\", linemitre = 10) {\n # Expand x, y, radius data to points along circle\n circular_data <- .mapply(\n function(x, y, radius, ang, ang0) {\n if (clockwise) {\n ang0 <- 90 - ang0\n radians <- seq(ang0, ang0 - ang, length.out = steps)[-1L]\n } else {\n ang0 <- 90 + ang0\n radians <- seq(ang0, ang0 + ang, length.out = steps)[-1L]\n }\n radians <- radians / 180 * pi\n data_frame0(\n x = c(x, cos(radians) * radius + x),\n y = c(y, sin(radians) * radius + y)\n )\n },\n list(\n x = data$x, y = data$y,\n radius = data$radius, ang = data$angle, ang0 = data$angle0\n ),\n MoreArgs = NULL\n )\n circular_data <- vec_rbind(!!!circular_data)\n\n # Transform to viewport coords\n circular_data <- coord$transform(circular_data, panel_params)\n\n # Draw as grob\n grid::polygonGrob(\n x = circular_data$x,\n y = circular_data$y,\n id.lengths = rep_len(steps, nrow(data)),\n default.units = \"native\",\n gp = gpar(\n col = data$colour,\n fill = fill_alpha(data$fill, data$alpha),\n lwd = data$linewidth,\n lty = data$linetype,\n lineend = lineend,\n linejoin = linejoin,\n linemitre = linemitre\n )\n )\n }\n)\n"], ["/ggalign/R/ggplot-helper.R", "# Exported function for ggplot2\n# Usually a quick shortcuts to define something\n#\n#' Remove axis elements\n#'\n#' @param axes Which axes elements should be removed? A string containing\n#' one or more of `r oxford_and(c(.tlbr, \"x\", \"y\"))`.\n#' @param text If `TRUE`, will remove the axis labels.\n#' @param ticks If `TRUE`, will remove the axis ticks.\n#' @param title If `TRUE`, will remove the axis title.\n#' @param line If `TRUE`, will remove the axis line.\n#' @return A [`theme()`][ggplot2::theme] object.\n#' @examples\n#' p <- ggplot() +\n#' geom_point(aes(x = wt, y = qsec), data = mtcars)\n#' p + theme_no_axes()\n#' p + theme_no_axes(\"b\")\n#' p + theme_no_axes(\"l\")\n#' @importFrom rlang inject\n#' @importFrom ggplot2 theme element_blank\n#' @export\ntheme_no_axes <- function(axes = \"xy\", text = TRUE, ticks = TRUE,\n title = TRUE, line = FALSE) {\n assert_string(axes, empty_ok = FALSE)\n if (grepl(\"[^tlbrxy]\", axes)) {\n cli_abort(sprintf(\n \"{.arg axes} can only contain the %s characters\",\n oxford_and(c(.tlbr, \"x\", \"y\"))\n ))\n }\n axes <- split_position(axes)\n el <- list(text = text, ticks = ticks, title = title, line = line)\n el <- names(el)[vapply(el, isTRUE, logical(1L), USE.NAMES = FALSE)]\n el_axis <- el_pos <- NULL\n if (length(positions <- vec_set_intersect(axes, .tlbr))) {\n positions <- .subset(\n c(t = \"top\", l = \"left\", b = \"bottom\", r = \"right\"),\n positions\n )\n el_pos <- vec_expand_grid(pos = positions, el = el)\n el_pos <- paste(\"axis\",\n .subset2(el_pos, \"el\"),\n if_else(.subset2(el_pos, \"pos\") %in% c(\"top\", \"bottom\"), \"x\", \"y\"),\n .subset2(el_pos, \"pos\"),\n sep = \".\"\n )\n }\n if (length(axes <- vec_set_intersect(axes, c(\"x\", \"y\")))) {\n el_axis <- vec_expand_grid(axes = axes, el = el)\n el_axis <- paste(\"axis\",\n .subset2(el_axis, \"el\"), .subset2(el_axis, \"axes\"),\n sep = \".\"\n )\n }\n el <- c(el_axis, el_pos)\n el <- vec_set_names(vec_rep(list(element_blank()), length(el)), el)\n inject(theme(!!!el, validate = FALSE))\n}\n\n##########################################################################\n#' Theme Polygon elements\n#'\n#' Draw polygon.\n#'\n#' @inheritParams ggplot2::element_rect\n#' @inheritParams geom_rect3d\n#' @inheritParams ggplot2::fill_alpha\n#' @param linewidth Line size in `mm`.\n#' @param linetype Line type for lines. An integer (0:8), a name (blank, solid,\n#' dashed, dotted, dotdash, longdash, twodash), or a string with an even number\n#' (up to eight) of hexadecimal digits which give the lengths in consecutive\n#' positions in the string.\n#' @seealso [`element_rect`][ggplot2::element_rect]\n#' @return A `element_polygon` object\n#' @export\nelement_polygon <- function(fill = NULL, colour = NULL, linewidth = NULL,\n linetype = NULL, alpha = NULL, lineend = NULL,\n linejoin = NULL, linemitre = NULL, color = NULL,\n inherit.blank = FALSE) {\n if (!is.null(color)) colour <- color\n structure(\n list(\n fill = fill, colour = colour, alpha = alpha,\n linewidth = linewidth, linetype = linetype,\n lineend = lineend, linejoin = linejoin, linemitre = linemitre,\n inherit.blank = inherit.blank\n ),\n class = c(\"ggalign_element_polygon\", \"element_polygon\", \"element\")\n )\n}\n\n#' @importFrom utils packageVersion\n#' @importFrom grid gpar\n#' @importFrom ggplot2 element_grob fill_alpha\n#' @export\nelement_grob.ggalign_element_polygon <- function(element,\n x = c(0, 0.5, 1, 0.5),\n y = c(0.5, 1, 0.5, 0),\n fill = NULL,\n colour = NULL,\n linewidth = NULL,\n linetype = NULL, ...) {\n if (packageVersion(\"ggplot2\") > \"3.5.2\") {\n gp <- ggfun(\"gg_par\")(\n lwd = linewidth, col = colour, fill = fill, lty = linetype\n )\n element_gp <- ggfun(\"gg_par\")(\n lwd = element$linewidth,\n col = element$colour,\n fill = fill_alpha(element$fill, element$alpha %||% NA),\n lty = element$linetype,\n lineend = element$lineend,\n linejoin = element$linejoin,\n linemitre = element$linemitre\n )\n } else {\n gp <- gpar(\n lwd = ggfun(\"len0_null\")(linewidth * .pt),\n col = colour,\n fill = fill,\n lty = linetype\n )\n element_gp <- gpar(\n lwd = ggfun(\"len0_null\")(element$linewidth * .pt),\n col = element$colour,\n fill = fill_alpha(element$fill, element$alpha %||% NA),\n lty = element$linetype,\n lineend = element$lineend,\n linejoin = element$linejoin,\n linemitre = element$linemitre\n )\n }\n grid::polygonGrob(\n x = x, y = y,\n gp = ggfun(\"modify_list\")(element_gp, gp), ...\n )\n}\n\n#' Theme curve elements\n#'\n#' Draw curve.\n#'\n#' @inheritParams element_polygon\n#' @inheritParams grid::curveGrob\n#' @param arrow.fill Fill colour for arrows.\n#' @return A `element_curve` object\n#' @export\nelement_curve <- function(colour = NULL, linewidth = NULL, linetype = NULL,\n lineend = NULL, color = NULL, curvature = NULL,\n angle = NULL, ncp = NULL, shape = NULL,\n arrow = NULL, arrow.fill = NULL,\n inherit.blank = FALSE) {\n colour <- color %||% colour\n arrow.fill <- arrow.fill %||% colour\n arrow <- arrow %||% FALSE\n structure(\n list(\n colour = colour, linewidth = linewidth, linetype = linetype,\n lineend = lineend, curvature = curvature, angle = angle,\n ncp = ncp, shape = shape, arrow = arrow, arrow.fill = arrow.fill,\n inherit.blank = inherit.blank\n ),\n class = c(\"ggalign_element_curve\", \"element_curve\", \"element\")\n )\n}\n\n#' @importFrom grid gpar gTree gList\n#' @importFrom ggplot2 element_grob\n#' @export\nelement_grob.ggalign_element_curve <- function(element, x = 0:1, y = 0:1,\n colour = NULL, linewidth = NULL, linetype = NULL, lineend = NULL,\n arrow.fill = NULL,\n default.units = \"npc\",\n id = NULL,\n id.lengths = NULL, ...) {\n arrow <- if (is.logical(element$arrow) && !element$arrow) {\n NULL\n } else {\n element$arrow\n }\n if (is.null(arrow)) {\n arrow.fill <- colour\n element$arrow.fill <- element$colour\n }\n # The gp settings can override element_gp\n gp <- gpar(\n col = colour,\n fill = arrow.fill %||% colour,\n lwd = ggfun(\"len0_null\")(linewidth * .pt),\n lty = linetype,\n lineend = lineend\n )\n element_gp <- gpar(\n col = element$colour,\n fill = element$arrow.fill %||% element$colour,\n lwd = ggfun(\"len0_null\")(element$linewidth * .pt),\n lty = element$linetype,\n lineend = element$lineend\n )\n gp <- ggfun(\"modify_list\")(element_gp, gp)\n if (is.null(id)) {\n if (is.null(id.lengths)) {\n id <- vec_rep(1L, length(x))\n } else {\n id <- vec_rep_each(seq_along(id.lengths), id.lengths)\n }\n }\n index_list <- .subset2(vec_split(seq_along(x), id), \"val\")\n ans <- lapply(index_list, function(index) {\n grid::curveGrob(\n vec_slice(x, index),\n vec_slice(y, index),\n default.units = default.units,\n gp = gp[index],\n curvature = element$curvature,\n angle = element$angle,\n ncp = element$ncp,\n shape = element$shape,\n arrow = arrow,\n square = FALSE, squareShape = 1,\n inflect = FALSE, open = TRUE,\n ...\n )\n })\n gTree(children = inject(gList(!!!ans)))\n}\n\n##########################################################################\nelement_lengths <- function(.el, .fn, ...) {\n fields <- element_vec_fields(.el)\n if (is.null(fields)) 0L\n lengths(.el[fields])\n}\n\n#' Apply a function to the fields of an element object\n#'\n#' @description\n#' For an [`element`][ggplot2::element_blank] object, some fields are\n#' vectorized, while others are not. This function allows you to apply a\n#' function to the vectorized fields.\n#'\n#' The following helper functions are available:\n#'\n#' - `element_rep`: Applies [`rep()`].\n#' - `element_rep_len`: Applies [`rep_len()`].\n#' - `element_vec_recycle`: Applies [`vec_recycle()`][vctrs::vec_recycle].\n#' - `element_vec_rep`: Applies [`vec_rep()`][vctrs::vec_rep].\n#' - `element_vec_rep_each`: Applies [`vec_rep_each()`][vctrs::vec_rep_each].\n#' - `element_vec_slice`: Applies [`vec_slice()`][vctrs::vec_slice].\n#'\n#' @param .el An [`element`][ggplot2::element_blank] object.\n#' @param .fn The function to be applied to the vectorized fields of the element\n#' object.\n#' @param ... Additional arguments passed on to `fn`.\n#' @export\nelement_vec <- function(.el, .fn, ...) {\n fields <- element_vec_fields(.el)\n if (is.null(fields)) {\n return(.el)\n }\n .el[fields] <- lapply(.el[fields], function(value) {\n if (!is.null(value)) value <- .fn(value, ...)\n value\n })\n .el\n}\n\n#' @export\n#' @rdname element_vec\nelement_rep <- function(.el, ...) element_vec(.el, rep, ...)\n\n#' @param length.out Non-negative integer. The desired length of the output\n#' vector. Other inputs will be coerced to a double vector and the first element\n#' taken. Ignored if `NA` or invalid.\n#' @export\n#' @rdname element_vec\nelement_rep_len <- function(.el, length.out, ...) {\n element_vec(.el, rep_len, ..., length.out = length.out)\n}\n\n#' @inheritParams vctrs::vec_recycle\n#' @export\n#' @rdname element_vec\nelement_vec_recycle <- function(.el, size, ...) {\n element_vec(.el, vec_recycle, size = size, ...)\n}\n\n#' @inheritParams vctrs::vec_rep\n#' @export\n#' @rdname element_vec\nelement_vec_rep <- function(.el, times, ...) {\n element_vec(.el, vec_rep, times = times, ...)\n}\n\n#' @export\n#' @rdname element_vec\nelement_vec_rep_each <- function(.el, times, ...) {\n element_vec(.el, vec_rep_each, times = times, ...)\n}\n\n#' @inheritParams vctrs::vec_slice\n#' @importFrom grid is.unit\n#' @export\n#' @rdname element_vec\nelement_vec_slice <- function(.el, i, ...) {\n element_vec(.el, function(x) {\n if (is.unit(x)) x[i, ...] else vec_slice(x, i, ...)\n })\n}\n\nelement_vec_fields <- function(el) UseMethod(\"element_vec_fields\")\n\n#' @export\nelement_vec_fields.ggalign_element_polygon <- function(el) {\n c(\n \"fill\", \"colour\", \"linewidth\", \"linetype\",\n \"lineend\", \"linejoin\", \"linemitre\", \"alpha\"\n )\n}\n\n#' @export\nelement_vec_fields.element_blank <- function(el) NULL\n\n#' @export\nelement_vec_fields.element_polygon <- function(el) {\n c(\"fill\", \"colour\", \"linewidth\", \"linetype\")\n}\n\n#' @export\nelement_vec_fields.element_point <- function(el) {\n c(\"colour\", \"shape\", \"size\", \"fill\", \"stroke\")\n}\n\n#' @export\nelement_vec_fields.element_rect <- function(el) {\n c(\"fill\", \"colour\", \"linewidth\", \"linetype\")\n}\n\n#' @export\nelement_vec_fields.element_line <- function(el) {\n c(\"colour\", \"linewidth\", \"linetype\", \"lineend\")\n}\n\n#' @export\nelement_vec_fields.element_text <- function(el) {\n c(\n \"family\", \"face\", \"colour\", \"size\", \"hjust\", \"vjust\",\n \"angle\", \"lineheight\"\n )\n}\n\n#' @export\nelement_vec_fields.default <- function(el) stop_input_type(el, \"an element\")\n\n######################################################\n#' Remove scale expansion\n#'\n#' @param borders Which border should be removed? A string containing\n#' one or more of `r oxford_and(c(.tlbr, \"x\", \"y\"))`.\n#' @return An object which can be added to ggplot.\n#' @export\nno_expansion <- function(borders = \"tlbr\") {\n assert_string(borders, empty_ok = FALSE)\n if (grepl(\"[^tlbrxy]\", borders)) {\n cli_abort(sprintf(\n \"{.arg borders} can only contain the %s characters\",\n oxford_and(c(.tlbr, \"x\", \"y\"))\n ))\n }\n borders <- .subset(list(\n t = \"top\", l = \"left\", b = \"bottom\", r = \"right\",\n x = c(\"left\", \"right\"), y = c(\"bottom\", \"top\")\n ), split_position(borders))\n borders <- vec_unique(unlist(borders, recursive = FALSE, use.names = FALSE))\n # expansion in x-axis\n structure(list(borders = borders), class = c(\"ggalign_no_expansion\"))\n}\n\n#' @importFrom ggplot2 ggplot_add ggproto ggproto_parent\n#' @export\nggplot_add.ggalign_no_expansion <- function(object, plot, object_name, ...) {\n borders <- .subset2(object, \"borders\")\n ParentLayout <- plot$layout\n\n # tricks to ensure remove `coord` won't remove `no_expansion()`\n plot$layout <- ggproto(NULL, ParentLayout,\n setup_panel_params = function(self) {\n ParentCoord <- self$coord\n self$coord <- ggproto(NULL, ParentCoord,\n setup_panel_params = function(self, scale_x, scale_y,\n params = list()) {\n if (!is.null(scale_x)) {\n expansion <- scale_x$expand %|w|%\n if (packageVersion(\"ggplot2\") > \"3.5.2\") {\n ggfun(\"default_expansion\")(\n scale_y,\n # for ggplot2 > 3.5.2, expand was passed by\n # params\n expand = params$expand[c(4, 2)]\n )\n } else {\n ggfun(\"default_expansion\")(\n scale_y,\n # for ggplot2 > 3.5.2, expand was passed by\n # params\n expand = self$expand\n )\n }\n if (any(borders == \"left\")) {\n expansion[1:2] <- 0\n }\n if (any(borders == \"right\")) {\n expansion[3:4] <- 0\n }\n scale_x$expand <- expansion\n }\n if (!is.null(scale_y)) {\n expansion <- scale_y$expand %|w|%\n if (packageVersion(\"ggplot2\") > \"3.5.2\") {\n ggfun(\"default_expansion\")(\n scale_y,\n # for ggplot2 > 3.5.2, expand was passed by\n # params\n expand = params$expand[c(3, 1)]\n )\n } else {\n ggfun(\"default_expansion\")(\n scale_y,\n # for ggplot2 > 3.5.2, expand was passed by\n # params\n expand = self$expand\n )\n }\n if (any(borders == \"bottom\")) {\n expansion[1:2] <- 0\n }\n if (any(borders == \"top\")) {\n expansion[3:4] <- 0\n }\n scale_y$expand <- expansion\n }\n ggproto_parent(ParentCoord, self)$setup_panel_params(\n scale_x = scale_x, scale_y = scale_y, params = params\n )\n }\n )\n ggproto_parent(ParentLayout, self)$setup_panel_params()\n }\n )\n plot\n}\n"], ["/ggalign/R/ggplot-coord-circle.R", "#' Polar Coordinates with Enhanced Controls\n#'\n#' An extended version of [`coord_radial()`][ggplot2::coord_radial], providing\n#' additional customization options.\n#'\n#' @inheritParams ggplot2::coord_radial\n#' @param thetalim,rlim Limits for the `theta` and `r` axes.\n#' @param inner.radius A numeric in `[0, 1)` indicates the inner radius.\n#' @param outer.radius A numeric in `(0, 1]` indicates the outer radius.\n#' [`coord_radial()`][ggplot2::coord_radial] by default uses `0.8`.\n#' @examples\n#' ggplot(mtcars, aes(disp, mpg)) +\n#' geom_point() +\n#' coord_circle(\n#' start = -0.4 * pi, end = 0.4 * pi,\n#' inner.radius = 0.3, outer.radius = 1\n#' )\n#' ggplot(mtcars, aes(disp, mpg)) +\n#' geom_point() +\n#' coord_circle(\n#' start = -0.4 * pi, end = 0.4 * pi,\n#' inner.radius = 0.3, outer.radius = 0.5\n#' )\n#' @importFrom ggplot2 ggproto\n#' @importFrom rlang arg_match0\n#' @export\ncoord_circle <- function(theta = \"x\", start = 0, end = NULL,\n thetalim = NULL, rlim = NULL, expand = FALSE,\n direction = 1, clip = \"off\",\n r.axis.inside = NULL, rotate.angle = FALSE,\n inner.radius = 0, outer.radius = 0.95) {\n theta <- arg_match0(theta, c(\"x\", \"y\"))\n assert_number_decimal(start, allow_infinite = FALSE)\n assert_number_decimal(end, allow_infinite = FALSE, allow_null = TRUE)\n if (packageVersion(\"ggplot2\") <= \"3.5.2\") {\n assert_bool(expand)\n }\n clip <- arg_match0(clip, c(\"off\", \"on\"))\n\n valid_inside_axis <- .rlang_check_bool(r.axis.inside,\n allow_null = TRUE\n ) ||\n .rlang_check_number(r.axis.inside,\n allow_decimal = TRUE, allow_infinite = FALSE\n ) == 0L\n if (!valid_inside_axis) {\n cli_abort(\n \"{.arg r.axis.inside} must be a single boolean value or a number\"\n )\n }\n\n assert_bool(rotate.angle)\n assert_number_decimal(inner.radius,\n min = 0, max = 1,\n allow_infinite = FALSE\n )\n assert_number_decimal(outer.radius,\n min = 0, max = 1,\n allow_infinite = FALSE\n )\n if (inner.radius >= outer.radius) {\n cli_abort(\n \"{.arg outer.radius} must be larger than {.arg inner.radius}\"\n )\n }\n r <- if (theta == \"x\") \"y\" else \"x\"\n\n arc <- c(start, end %||% (start + 2 * pi))\n if (arc[1] > arc[2]) {\n n_rotate <- ((arc[1] - arc[2]) %/% (2 * pi)) + 1\n arc[1] <- arc[1] - n_rotate * 2 * pi\n }\n r.axis.inside <- r.axis.inside %||% !(abs(arc[2] - arc[1]) >= 1.999 * pi)\n inner_radius <- c(inner.radius, outer.radius) / 2\n\n ggproto(NULL, CoordCircle,\n limits = list(theta = thetalim, r = rlim),\n theta = theta,\n r = r,\n arc = arc,\n expand = expand,\n direction = sign(direction),\n r_axis_inside = r.axis.inside,\n rotate_angle = rotate.angle,\n inner_radius = inner_radius,\n clip = clip\n )\n}\n\n#' @importFrom ggplot2 ggproto_parent\ncircle_panel_params <- function(self, scale_x, scale_y, params = list()) {\n out <- ggproto_parent(ggplot2::CoordRadial, self)$setup_panel_params(\n scale_x, scale_y, params\n )\n if (packageVersion(\"ggplot2\") <= \"3.5.2\") {\n if (self$theta == \"x\") {\n xlimits <- self$limits$theta\n ylimits <- self$limits$r\n } else {\n xlimits <- self$limits$r\n ylimits <- self$limits$theta\n }\n new <- c(\n view_scales_polar(\n scale_x, self$theta, xlimits,\n expand = params$expand[c(4, 2)] %||% self$expand\n ),\n view_scales_polar(\n scale_y, self$theta, ylimits,\n expand = params$expand[c(3, 1)] %||% self$expand\n )\n )\n out[names(new)] <- new\n }\n out$bbox <- ggfun(\"polar_bbox\")(\n self$arc, margin = c(0, 0, 0, 0),\n inner_radius = self$inner_radius\n )\n out\n}\n\nview_scales_polar <- function(scale, theta, coord_limits, expand = TRUE) {\n aesthetic <- scale$aesthetics[1]\n is_theta <- theta == aesthetic\n name <- if (is_theta) \"theta\" else \"r\"\n expansion <- ggfun(\"default_expansion\")(scale, expand = expand)\n limits <- scale$get_limits()\n continuous_range <- ggfun(\"expand_limits_scale\")(\n scale, expansion, limits, coord_limits = coord_limits\n )\n primary <- ggfun(\"view_scale_primary\")(scale, limits, continuous_range)\n view_scales <- list(\n primary,\n sec = ggfun(\"view_scale_secondary\")(scale, limits, continuous_range),\n major = primary$map(primary$get_breaks()),\n minor = primary$map(primary$get_breaks_minor()),\n range = continuous_range\n )\n names(view_scales) <- c(name, paste0(name, \".\", names(view_scales)[-1]))\n view_scales\n}\n\n#' @importFrom ggplot2 ggproto\nCoordCircle <- ggproto(\n \"CoordCircle\", ggplot2::CoordRadial,\n setup_panel_params = circle_panel_params\n)\n"], ["/ggalign/R/alignpatch-ggplot2.R", "#' @export\nggalign_gtable.ggplot <- function(x) alignpatch(x)$patch_gtable()\n\n#' @export\nggalign_build.ggplot <- function(x) x\n\n##################################################\n#' @export\n#' @include alignpatch-build.R\nprint.patch_ggplot <- print.alignpatches\n\n#' @importFrom grid grid.draw\n#' @exportS3Method\ngrid.draw.patch_ggplot <- grid.draw.alignpatches\n\n#################################################\n#' @importFrom ggplot2 ggproto\n#' @export\nalignpatch.ggplot <- function(x) ggproto(NULL, PatchGgplot, plot = x)\n\n# ggplot2 has following grobs:\n# panel\n# axis: must follow panel\n# strip: must follow the panel\n# xlab/ylab: can be aligned or follow the panel\n# subtitle\n# title\n# caption\n# guide: can be collected or kept\n#' @importFrom ggplot2 ggplotGrob update_labels\n#' @include alignpatch-.R\nPatchGgplot <- ggproto(\"PatchGgplot\", Patch,\n set_guides = function(guides) guides,\n patch_gtable = function(self, theme, guides, plot = self$plot) {\n # extract patch titles --------------------------------\n patch_titles <- plot$ggalign_patch_labels\n\n # complete_theme() will ensure elements exist --------\n theme <- complete_theme(plot$theme)\n # here: we remove tick length when the tick is blank\n theme <- setup_tick_length_element(theme)\n plot$theme <- theme\n\n # build the grob -------------------------------------\n ans <- ggplotGrob(plot)\n strip_pos <- find_strip_pos(ans)\n # always add strips columns and/or rows\n ans <- add_strips(ans, strip_pos)\n setup_patch_titles(ans, patch_titles = patch_titles, theme = theme)\n },\n respect = function(self, gt = self$gt) .subset2(gt, \"respect\"),\n\n #' @importFrom ggplot2 find_panel\n align_panel_sizes = function(self, panel_width, panel_height,\n gt = self$gt) {\n panel_pos <- find_panel(gt)\n rows <- c(.subset2(panel_pos, \"t\"), .subset2(panel_pos, \"b\"))\n cols <- c(.subset2(panel_pos, \"l\"), .subset2(panel_pos, \"r\"))\n respect <- .subset2(gt, \"respect\")\n if (rows[1L] == rows[2L] && cols[1L] == cols[2L]) {\n if (respect) {\n can_set_width <- is.na(as.numeric(panel_width))\n can_set_height <- is.na(as.numeric(panel_height))\n w <- .subset2(gt, \"widths\")[LEFT_BORDER + 1L]\n h <- .subset2(gt, \"heights\")[TOP_BORDER + 1L]\n if (can_set_width && can_set_height) {\n panel_width <- w\n panel_height <- h\n } else if (can_set_width) {\n panel_width <- as.numeric(w) / as.numeric(h) * panel_height\n } else if (can_set_height) {\n panel_height <- as.numeric(h) / as.numeric(w) * panel_width\n } else {\n respect <- FALSE\n }\n }\n } else {\n respect <- FALSE\n }\n list(width = panel_width, height = panel_height, respect = respect)\n },\n\n #' @importFrom gtable gtable_add_grob gtable_height gtable_width\n #' @importFrom grid unit viewport\n #' @importFrom ggplot2 find_panel\n free_border = function(self, borders, gt = self$gt) {\n panel_pos <- find_panel(gt)\n for (border in borders) {\n if (border == \"top\") {\n gt <- liberate_area(\n gt,\n 1L,\n 1L,\n .subset2(panel_pos, \"t\") - 1L,\n ncol(gt),\n clip = \"off\",\n name = \"free-border-top\",\n vp = ~ viewport(\n y = 0L, just = \"bottom\",\n height = gtable_height(.x)\n )\n )\n } else if (border == \"left\") {\n gt <- liberate_area(\n gt,\n 1L,\n 1L,\n nrow(gt),\n .subset2(panel_pos, \"l\") - 1L,\n clip = \"off\",\n name = \"free-border-left\",\n vp = ~ viewport(\n x = 1L, just = \"right\",\n width = gtable_width(.x)\n )\n )\n } else if (border == \"bottom\") {\n gt <- liberate_area(\n gt,\n .subset2(panel_pos, \"b\") + 1L,\n 1L,\n nrow(gt),\n ncol(gt),\n clip = \"off\",\n name = \"free-border-bottom\",\n vp = ~ viewport(\n y = 1L, just = \"top\",\n height = gtable_height(.x)\n )\n )\n } else if (border == \"right\") {\n gt <- liberate_area(\n gt,\n 1L,\n .subset2(panel_pos, \"r\") + 1L,\n nrow(gt),\n ncol(gt),\n clip = \"off\",\n name = \"free-border-right\",\n vp = ~ viewport(\n x = 0L, just = \"left\",\n width = gtable_width(.x)\n )\n )\n }\n }\n gt\n },\n align_free_border = function(self, borders,\n t = NULL, l = NULL, b = NULL, r = NULL,\n gt = self$gt) {\n if (is.null(t) && is.null(l) && is.null(b) && is.null(r)) {\n return(gt)\n }\n # For free borders, we also align the margins\n for (border in borders) {\n i <- .subset2(.subset2(gt, \"layout\"), \"name\") ==\n sprintf(\"free-border-%s\", border)\n if (any(i)) {\n i <- which(i)\n gt$grobs[[i]] <- switch_position(\n border,\n Patch$align_border(l = l, r = r, gt = gt$grobs[[i]]),\n Patch$align_border(t = t, b = b, gt = gt$grobs[[i]])\n )\n }\n }\n gt\n },\n\n #' @importFrom ggplot2 find_panel\n #' @importFrom gtable is.gtable gtable_height gtable_width gtable_add_grob\n #' @importFrom grid grobHeight grobWidth viewport\n free_lab = function(self, labs, gt = self$gt) {\n panel_pos <- find_panel(gt)\n for (lab in labs) {\n name <- paste(\n switch_position(lab, \"xlab\", \"ylab\"),\n \"axis\", lab,\n sep = \"-\"\n )\n if (lab == \"top\") {\n panel_border <- .subset2(panel_pos, \"t\")\n gt <- liberate_area(\n gt,\n panel_border - 3L,\n .subset2(panel_pos, \"l\"),\n panel_border - 1L,\n .subset2(panel_pos, \"r\"),\n name = name,\n vp = ~ viewport(\n y = 0L, just = \"bottom\",\n height = gtable_height(.x)\n )\n )\n } else if (lab == \"left\") {\n panel_border <- .subset2(panel_pos, \"l\")\n gt <- liberate_area(\n gt,\n .subset2(panel_pos, \"t\"),\n panel_border - 3L,\n .subset2(panel_pos, \"b\"),\n panel_border - 1L,\n name = name,\n vp = ~ viewport(\n x = 1L, just = \"right\",\n width = gtable_width(.x)\n )\n )\n } else if (lab == \"bottom\") {\n panel_border <- .subset2(panel_pos, \"b\")\n gt <- liberate_area(\n gt,\n panel_border + 1L,\n .subset2(panel_pos, \"l\"),\n panel_border + 3L,\n .subset2(panel_pos, \"r\"),\n name = name,\n vp = ~ viewport(\n y = 1L, just = \"top\",\n height = gtable_height(.x)\n )\n )\n } else if (lab == \"right\") {\n panel_border <- .subset2(panel_pos, \"r\")\n gt <- liberate_area(\n gt,\n .subset2(panel_pos, \"t\"),\n panel_border + 1L,\n .subset2(panel_pos, \"b\"),\n panel_border + 3L,\n name = name,\n vp = ~ viewport(\n x = 0L, just = \"left\",\n width = gtable_width(.x)\n )\n )\n }\n }\n gt\n }\n)\n\n#' @importFrom ggplot2 calc_element\n#' @importFrom grid unit\nsetup_tick_length_element <- function(theme) {\n for (tick in c(\"x.top\", \"y.left\", \"x.bottom\", \"y.right\")) {\n for (axis in c(\"axis.minor\", \"axis\")) {\n blank <- inherits(calc_element(\n paste(axis, \"ticks\", tick, sep = \".\"), theme\n ), \"element_blank\")\n if (blank) { # No ticks, no length\n element <- paste(axis, \"ticks.length\", tick, sep = \".\")\n theme[[element]] <- unit(0, \"mm\")\n }\n }\n }\n theme\n}\n\n#' @importFrom gtable gtable_add_rows gtable_add_cols\n#' @importFrom ggplot2 find_panel\n#' @importFrom grid unit\nadd_strips <- function(gt, strip_pos) {\n panel_loc <- find_panel(gt)\n strip_pos <- switch(strip_pos, inside = 0L, outside = 2L) # styler: off\n layout <- .subset2(gt, \"layout\")\n if (!any(grepl(\"strip-b\", layout$name))) { # No strips\n gt <- gtable_add_rows(\n gt, unit(0L, \"mm\"),\n panel_loc$b + strip_pos\n )\n } else if (strip_pos == 2L && !any(layout$b == panel_loc$b + 2L)) {\n # Merge the strip-gap height into the axis and remove it. Only performed\n # if an axis exist\n gt$heights[panel_loc$b + 1L] <- sum(gt$heights[panel_loc$b + 1:2])\n gt <- gt[-(panel_loc$b + 2L), ]\n }\n if (!any(grepl(\"strip-t\", layout$name))) {\n gt <- gtable_add_rows(\n gt, unit(0L, \"mm\"),\n panel_loc$t - 1L - strip_pos\n )\n } else if (strip_pos == 2L && !any(layout$t == panel_loc$t - 2L)) {\n gt$heights[panel_loc$t - 1L] <- sum(gt$heights[panel_loc$t - 1:2])\n gt <- gt[-(panel_loc$t - 2L), ]\n }\n if (!any(grepl(\"strip-r\", layout$name))) {\n gt <- gtable_add_cols(\n gt, unit(0L, \"mm\"),\n panel_loc$r + strip_pos\n )\n } else if (strip_pos == 2L && !any(layout$r == panel_loc$r + 2L)) {\n gt$widths[panel_loc$r + 1L] <- sum(gt$widths[panel_loc$r + 1:2])\n gt <- gt[, -(panel_loc$r + 2L)]\n }\n if (!any(grepl(\"strip-l\", layout$name))) {\n gt <- gtable_add_cols(\n gt, unit(0L, \"mm\"),\n panel_loc$l - 1L - strip_pos\n )\n } else if (strip_pos == 2L && !any(layout$l == panel_loc$l - 2L)) {\n gt$widths[panel_loc$l - 1L] <- sum(gt$widths[panel_loc$l - 1:2])\n gt <- gt[, -(panel_loc$l - 2L)]\n }\n gt\n}\n\n# theme(strip.placement)\n#' @importFrom ggplot2 find_panel\nfind_strip_pos <- function(gt) {\n panel_loc <- find_panel(gt)\n layout <- .subset2(gt, \"layout\")\n nms <- .subset2(layout, \"name\")\n ind <- grep(\"strip-t\", nms)\n if (length(ind) != 0L && panel_loc$t - min(layout$t[ind]) != 1L) {\n return(\"outside\")\n }\n ind <- grep(\"strip-l\", nms)\n if (length(ind) != 0L && panel_loc$l - min(layout$l[ind]) != 1L) {\n return(\"outside\")\n }\n ind <- grep(\"strip-r\", nms)\n if (length(ind) != 0L && max(layout$r[ind]) - panel_loc$r != 1L) {\n return(\"outside\")\n }\n ind <- grep(\"strip-b\", nms)\n if (length(ind) != 0L && max(layout$b[ind]) - panel_loc$b != 1L) {\n return(\"outside\")\n }\n \"inside\"\n}\n"], ["/ggalign/R/fortify-matrix-list.R", "#' Convert the shape of a list for fortify method\n#'\n#' @param data A list\n#' @param shape Not used currently.\n#' @seealso [`fortify_matrix.list_upset()`]\n#' @family tune\n#' @export\ntune.list <- function(data, shape = NULL) {\n if (!is.null(shape)) {\n cli_abort(\"{.arg shape} cannot be used currently for {.cls list} object\")\n }\n new_tune(data, class = \"list_upset\")\n}\n\n#' Build a Matrix for UpSet plot\n#'\n#' @description\n#' `r lifecycle::badge('experimental')`\n#'\n#' This function converts a list into a matrix format suitable for creating an\n#' UpSet plot. It always returns a matrix for a `horizontal` UpSet plot.\n#' @inheritParams rlang::args_dots_empty\n#' @param data A list of sets.\n#' @param mode A string of `r oxford_or(c(\"distinct\", \"intersect\", \"union\"))`\n#' indicates the mode to define the set intersections. Check\n#' \n#' for details.\n#' @inheritParams fortify_matrix\n#' @section ggalign attributes:\n#' - `intersection_sizes`: An integer vector indicating the size of each\n#' intersection.\n#' - `set_sizes`: An integer vector indicating the size of each set.\n#' @seealso [`tune.list()`]\n#' @family fortify_matrix\n#' @aliases fortify_matrix.list\n#' @export\nfortify_matrix.list_upset <- function(data, mode = \"distinct\", ...,\n data_arg = NULL, call = NULL) {\n call <- call %||% current_call()\n rlang::check_dots_empty(call = call)\n mode <- arg_match0(mode, c(\"distinct\", \"intersect\", \"union\"),\n error_call = call\n )\n data <- lapply(tune_data(data), function(x) {\n vec_unique(vec_slice(x, !vec_detect_missing(x)))\n })\n data <- list_drop_empty(data)\n if (length(data) == 0L) {\n cli::cli_abort(\n \"No valid data: All input lists are either empty or contain only missing values.\",\n call = call\n )\n }\n\n # Based on the explanation from\n # https://jokergoo.github.io/ComplexHeatmap-reference/book/upset-plot.html\n action <- switch(mode,\n distinct = function(data, intersection) {\n out <- NULL\n for (i in which(intersection)) {\n if (is.null(out)) {\n out <- .subset2(data, i)\n } else if (vec_size(out) == 0L) { # early exit for empty items\n return(out)\n } else {\n out <- vec_set_intersect(out, .subset2(data, i))\n }\n }\n for (i in which(!intersection)) {\n if (vec_size(out) == 0L) { # early exit for empty items\n return(out)\n }\n out <- vec_set_difference(out, .subset2(data, i))\n }\n return(out)\n },\n intersect = function(data, intersection) {\n out <- NULL\n for (i in which(intersection)) {\n if (is.null(out)) {\n out <- .subset2(data, i)\n } else if (vec_size(out) == 0L) { # early exit for empty items\n return(out)\n } else {\n out <- vec_set_intersect(out, .subset2(data, i))\n }\n }\n out\n },\n union = function(data, intersection) {\n Reduce(vec_set_union, .subset(data, intersection))\n }\n )\n\n intersection <- logical(vec_size(data)) # template\n intersection_and_size <- lapply(\n seq_len(vec_size(intersection)),\n function(n) {\n # generate all possible intersections\n utils::combn(vec_size(intersection), n, function(index) {\n intersection[index] <- TRUE\n list(\n intersection = intersection,\n # for each intersection, we define the size\n size = vec_size(action(data, intersection))\n )\n }, simplify = FALSE)\n }\n )\n\n # https://en.wikipedia.org/wiki/UpSet_plot\n # UpSets can be used horizontally and vertically.\n # In a vertical UpSet plot, the columns of the matrix correspond to the\n # sets, the rows correspond to the intersections.\n # we by default use `horizontal` upset, the rows of the matrix correspond\n # to the sets, the columns correspond to the intersections.\n ans <- list_transpose(unlist(intersection_and_size, FALSE, FALSE))\n intersections <- inject(cbind(!!!.subset2(ans, \"intersection\")))\n rownames(intersections) <- names(data)\n intersection_sizes <- unlist(.subset2(ans, \"size\"), FALSE, FALSE)\n keep <- intersection_sizes > 0L # remove intersection without items\n intersections <- intersections[, keep, drop = FALSE]\n intersection_sizes <- intersection_sizes[keep]\n ggalign_data_set(intersections,\n intersection_sizes = intersection_sizes,\n set_sizes = list_sizes(data),\n upset_mode = mode\n )\n}\n"], ["/ggalign/R/layout-chain-circle-genomic.R", "#' Create a Circular Layout for Genomic Data\n#'\n#' `circle_genomic()` constructs a circular layout specifically for genomic\n#' data. It is a specialized variant of `circle_continuous()` that applies\n#' default axis limits and coerces the first column of each plot’s data to use\n#' chromosome (`seqname`) identifiers—matching those in the layout data—as\n#' factor levels.\n#'\n#' @param data The input data, which can be:\n#' - A `character` string (\"hg19\" or \"hg38\") to load a predefined cytoband\n#' reference.\n#' - A `data.frame` with at least three columns: `chromosome`, `start`, and\n#' `end` positions.\n#' - A genomic object convertible via `fortify_data_frame()`.\n#' @param ... Additional arguments passed to specific methods or\n#' `fortify_data_frame()`.\n#' @inheritParams circle_continuous\n#' @return A `circle_layout` object representing the genomic layout.\n#' @export\ncircle_genomic <- function(data, ..., radial = NULL,\n direction = \"outward\",\n sector_spacing = NULL,\n theme = NULL) {\n UseMethod(\"circle_genomic\")\n}\n\n#' @export\ncircle_genomic.NULL <- function(data, ...) {\n cli_abort(\"{.arg data} must be provided to initialize `circle_genomic()`\")\n}\n\n#' @export\ncircle_genomic.waiver <- circle_genomic.NULL\n\n#' @export\ncircle_genomic.character <- function(data, ...) {\n data <- arg_match0(data, c(\"hg19\", \"hg38\"))\n data <- readRDS(\n pkg_extdata(\n switch(data,\n hg19 = \"ref_cytoband_hg19.rds\",\n hg38 = \"ref_cytoband_hg38.rds\"\n ),\n mustWork = TRUE\n )\n )\n circle_genomic(data, ...)\n}\n\n#' @export\n#' @keywords internal\ncircle_genomic.data.frame <- function(data, ..., radial = NULL,\n direction = \"outward\",\n sector_spacing = NULL,\n theme = NULL) {\n rlang::check_dots_empty()\n if (ncol(data) < 3L) {\n cli_abort(\"{.arg data} must have at least 3 columns: chromosome, start, and end\")\n }\n if (anyNA(data[[1L]]) || anyNA(data[[2L]]) || anyNA(data[[3L]])) {\n cli_abort(\"Columns 1, 2, and 3 of {.arg data} must not contain missing values\")\n }\n if (!is.numeric(data[[2L]]) || !is.numeric(data[[3L]])) {\n cli_abort(\"Columns 2 and 3 of {.arg data} must be numeric (start and end positions)\")\n }\n if (any(data[[2L]] > data[[3L]])) {\n cli_abort(\"Column 2 (start) must not be greater than column 3 (end) in any row of {.arg data}\")\n }\n data[[1L]] <- as.factor(data[[1L]])\n # seqnames, start, end\n # Special considerations for `data.table`, we cannot use `data[1:2]`\n groups <- vec_split(\n data.frame(start = data[[2L]], end = data[[3L]]),\n data[[1L]]\n )\n ranges <- lapply(\n .subset2(groups, \"val\"),\n function(d) genomic_range(.subset2(d, 1L), .subset2(d, 2L))\n )\n lvls <- levels(data[[1L]])\n names(ranges) <- .subset2(groups, \"key\")\n ranges <- ranges[lvls]\n limits <- continuous_limits(!!!ranges)\n ranges <- vec_rbind(!!!ranges, .names_to = \"seqnames\")\n ranges$seqnames <- factor(ranges$seqnames, levels = lvls)\n new_circle_layout(\n data = ggalign_data_set(data, seqnames = lvls, ranges = ranges),\n design = limits,\n radial = radial, direction = direction,\n sector_spacing = sector_spacing,\n schemes = default_schemes(data), theme = theme,\n name = \"circle_genomic\"\n )\n}\n\n#' @export\ncircle_genomic.default <- function(data, ..., radial = NULL,\n direction = \"outward\",\n sector_spacing = NULL,\n theme = NULL) {\n data <- fortify_data_frame(data = data, ...)\n circle_genomic(data,\n radial = radial, direction = direction,\n sector_spacing = sector_spacing, theme = theme\n )\n}\n\ngenomic_range <- function(start, end) {\n if (length(start) == 1) return(c(start = start, end = end)) # styler: off\n ordering <- order(start)\n s <- start[ordering[1L]]\n e <- end[ordering[1L]]\n for (i in ordering[-1L]) {\n if (start[ordering[i]] - e > 1) {\n cli_abort(\"Input genomic ranges cannot contain intervals\")\n }\n e <- end[ordering[i]]\n }\n c(start = s, end = e)\n}\n\n#' @export\nchain_decorate.CircleLayout <- function(layout, plot) {\n if (!identical(layout@name, \"circle_genomic\")) {\n return(plot)\n }\n if (is.data.frame(data <- plot$data)) {\n data[[1L]] <- factor(\n data[[1L]],\n levels = ggalign_attr(layout@data, \"seqnames\")\n )\n missing <- is.na(data[[1L]])\n if (any(missing)) {\n cli_warn(\"Removing {.val {sum(missing)}} rows contain missing {.field seqnames}\")\n data <- vec_slice(data, !missing)\n }\n plot$data <- data\n }\n plot\n}\n"], ["/ggalign/R/alignpatch-patchwork.R", "########################################\n#' @importFrom utils modifyList getFromNamespace\n#' @export\nalignpatch.patchwork <- function(x) {\n rlang::check_installed(\"patchwork\", \"to align patchwork\")\n get_patches <- getFromNamespace(\"get_patches\", \"patchwork\")\n # patchwork will keep the class when extracting patches from it.\n # we removed the classes for patchwork, added behind patchwork\n # in this way, the last plot won't have class like `free_align`,\n # `free_border`, `free_lab`, et al. which is added for the patchwork\n sub_patchwork_cls <- which(class(x) == \"patchwork\") - 1L # nolint\n if (sub_patchwork_cls > 0L) {\n class(x) <- class(x)[-seq_len(sub_patchwork_cls)]\n }\n x <- get_patches(x)\n plots <- .subset2(x, \"plots\")\n layout <- .subset2(x, \"layout\")\n annotation <- .subset2(x, \"annotation\")\n default <- getFromNamespace(\"default_layout\", \"patchwork\")\n layout <- modifyList(default, layout[\n !vapply(layout, is.null, logical(1L), USE.NAMES = FALSE)\n ])\n if (identical(.subset2(layout, \"guides\"), \"collect\")) {\n layout$guides <- .TLBR\n } else {\n layout$guides <- NULL\n }\n alignpatch(AlignPatches(\n plots,\n layout = layout,\n titles = .subset(annotation, names(layout_title())),\n theme = .subset2(annotation, \"theme\")\n ))\n}\n\n#' @export\nalignpatch.free_plot <- function(x) {\n if (inherits(x, \"patchwork\")) {\n free_settings <- attr(x, \"patchwork_free_settings\")\n } else {\n free_settings <- attr(x, \"free_settings\")\n }\n free_settings <- split(\n names(free_settings),\n factor(free_settings, rev(unique(free_settings)))\n )\n class(x) <- vec_set_difference(class(x), \"free_plot\")\n for (type in names(free_settings)) {\n side <- paste(.subset2(free_settings, type), collapse = \"\")\n x <- switch(type,\n panel = free_align(x, side),\n label = free_lab(x, side),\n space = free_space(free_border(x, side), side),\n )\n }\n alignpatch(x)\n}\n\n######################################\n# `patch` from `patchwork`: patchwork::plot_spacer\n#' @importFrom ggplot2 ggproto\n#' @export\nalignpatch.patch <- function(x) {\n rlang::check_installed(\n \"patchwork\", sprintf(\"to align %s plot\", obj_type_friendly(x))\n )\n ggproto(NULL, PatchPatchworkPatch, plot = x)\n}\n\n#' @importFrom ggplot2 ggproto\nPatchPatchworkPatch <- ggproto(\n \"PatchPatchworkPatch\", Patch,\n # `patch` from `patchwork`: patchwork::plot_spacer\n #' @importFrom gtable gtable_add_rows gtable_add_cols\n #' @importFrom ggplot2 find_panel\n patch_gtable = function(self, theme, guides, plot = self$plot) {\n guides <- if (length(guides)) \"collect\" else \"keep\"\n ans <- patchwork::patchGrob(patch, guides = guides)\n for (border in .TLBR) {\n panel_pos <- find_panel(ans)\n if (border == \"top\") {\n h <- .subset2(panel_pos, \"t\") - 4L # above original xlab\n ans <- gtable_add_rows(ans, unit(0L, \"mm\"), pos = h)\n } else if (border == \"left\") {\n v <- .subset2(panel_pos, \"l\") - 4L # left of the ylab\n ans <- gtable_add_cols(ans, unit(0, \"mm\"), pos = v)\n } else if (border == \"bottom\") {\n h <- .subset2(panel_pos, \"b\") + 3L # below original xlab\n ans <- gtable_add_rows(ans, unit(0L, \"mm\"), pos = h)\n } else if (border == \"right\") {\n v <- .subset2(panel_pos, \"r\") + 3L # right of the ylab\n ans <- gtable_add_cols(ans, unit(0, \"mm\"), pos = v)\n }\n }\n ans\n }\n)\n\n#' @export\nalignpatch.spacer <- function(x) NULL\n\n#########################################\n# `patch` from `patchwork`: patchwork::wrap_elements\n#' @export\nalignpatch.wrapped_patch <- alignpatch.patch\n"], ["/ggalign/R/genomic-helper.R", "#' Calculate inter-region distances for genomic rainfall plots\n#'\n#' This function computes distances between adjacent genomic regions, grouped by\n#' chromosome. Useful for visualizing clustering or dispersion of genomic\n#' features.\n#'\n#' @param region A data frame with at least 3 columns: chromosome, start, and\n#' end.\n#' @param mode How to assign distance for intermediate regions: one of `\"min\"`,\n#' `\"max\"`, `\"mean\"`, `\"left\"`, or `\"right\"`.\n#' @details\n#' The distance between two adjacent regions is calculated as the number of\n#' bases between the **end position of the upstream region** and the\n#' **start position of the downstream region**. If two regions overlap or are\n#' adjacent (≤1 bp apart), the distance is set to `0`. The resulting distance is\n#' assigned to each region according to the selected `mode`:\n#'\n#' - `\"left\"`: assign the distance to the upstream region\n#' - `\"right\"`: assign to the downstream region\n#' - `\"min\"` / `\"max\"` / `\"mean\"`: for intermediate regions, calculate the\n#' minimum, maximum, or average of the distances to neighboring regions\n#'\n#' @return A data frame with an additional `dist` column.\n#' @export\ngenomic_dist <- function(region, mode = NULL) {\n # Check input validity\n if (is.null(mode)) {\n mode <- \"min\"\n } else {\n mode <- arg_match0(mode, c(\"min\", \"max\", \"mean\", \"left\", \"right\"))\n }\n if (!is.data.frame(region) || ncol(region) < 3L) {\n cli_abort(\"{.arg region} must have at least 3 columns: chromosome, start, and end\")\n }\n if (anyNA(region[[1L]]) || anyNA(region[[2L]]) || anyNA(region[[3L]])) {\n cli_abort(\"Columns 1, 2, and 3 of {.arg region} must not contain missing values\")\n }\n if (!is.numeric(region[[2L]]) || !is.numeric(region[[3L]])) {\n cli_abort(\"Columns 2 and 3 of {.arg region} must be numeric (start and end positions)\")\n }\n if (any(region[[2L]] > region[[3L]])) {\n cli_abort(\"Column 2 (start) must not be greater than column 3 (end) in any row of {.arg region}\")\n }\n\n # Split the region data frame by chromosome (first column)\n groups <- vec_split(region, .subset2(region, 1L))\n dist_list <- lapply(.subset2(groups, \"val\"), function(d) {\n n <- nrow(d)\n if (n < 2L) {\n d$dist <- NA_real_\n return(d)\n }\n\n # Sort regions by start, then end positions\n ordering <- order(.subset2(d, 2L), .subset2(d, 3L))\n\n # Compute distances between adjacent regions\n dists <- vapply(seq_len(n - 1L), function(i) {\n first <- vec_slice(d, ordering[i])\n second <- vec_slice(d, ordering[i + 1])\n out <- .subset2(second, 2L) - .subset2(first, 3L)\n # If overlapping or adjacent (≤1 bp), treat distance as 0\n if (out <= 1L) out <- 0L else out <- as.integer(out)\n out\n }, integer(1L), USE.NAMES = FALSE)\n\n # If only two regions, just repeat the distance\n if (n == 2L) {\n d$dist <- rep_len(dists, n)\n return(d)\n }\n\n # For intermediate regions (not first or last), choose how to assign\n # distance\n d1 <- dists[seq_len(n - 2L)]\n d2 <- dists[2:(n - 1L)]\n if (mode == \"min\") {\n body_dists <- pmin(d1, d2)\n } else if (mode == \"max\") {\n body_dists <- pmax(d1, d2)\n } else if (mode == \"mean\") {\n body_dists <- (d1 + d2) / 2L\n } else if (mode == \"left\") {\n body_dists <- d1\n } else if (mode == \"right\") {\n body_dists <- d2\n }\n\n # Combine distances: head, body, and tail\n d$dist <- c(dists[1L], body_dists, dists[n - 1L])[order(ordering)]\n d\n })\n vec_rbind(!!!dist_list)\n}\n\n#' Calculate Genomic Region Density\n#'\n#' Computes the density or count of genomic regions in sliding or fixed windows\n#' across the genome. The density can be reported as the percentage of uncovered\n#' bases or the number of overlapping regions within each window.\n#'\n#' This function splits the input by chromosome and tiles the genomic space\n#' into windows, optionally overlapping. For each window, it calculates:\n#'\n#' - the number of regions that overlap it (if `mode = \"count\"`), or\n#' - the fraction of bases covered by any region (if `mode = \"percent\"`).\n#'\n#' @param region A data frame with at least 3 columns: chromosome, start, and\n#' end.\n#' - Column 1: character or factor, chromosome name.\n#' - Column 2: numeric, start position (must be ≤ end).\n#' - Column 3: numeric, end position.\n#' @param window_size Numeric, the width of each window (default is `1e+07`).\n#' Ignored if `n_window` is specified.\n#' @param n_window Integer, the number of windows per chromosome. If provided,\n#' overrides `window_size` and evenly splits the chromosome into `n_window`\n#' (non-overlapping) or `2*n_window - 1` (overlapping) windows.\n#' @param overlap Logical, whether to use overlapping windows (default `TRUE`).\n#' Overlapping windows are spaced by half the window size.\n#' @param mode Character, either `\"coverage\"` or `\"count\"`:\n#' - `\"count\"`: reports the number of regions overlapping each window.\n#' - `\"coverage\"`: reports the fraction of each window covered by regions.\n#' @param seqlengths Optional named vector of chromosome lengths. If missing,\n#' the maximum `end` value in the input is used as the chromosome length.\n#'\n#' @return A data frame with columns:\n#' - `seqnames`: The sequence (e.g., chromosome) names.\n#' - `start`: start of each window\n#' - `end`: end of each window\n#' - `density`: the region count or covered percent, depending on `mode`\n#'\n#' @examples\n#' region <- data.frame(\n#' chr = rep(\"chr1\", 3),\n#' start = c(100, 5000000, 15000000),\n#' end = c(2000000, 7000000, 17000000)\n#' )\n#' genomic_density(region, window_size = 1e7, mode = \"count\")\n#' genomic_density(region, n_window = 3, overlap = FALSE, mode = \"coverage\")\n#'\n#' @export\ngenomic_density <- function(region, window_size = 1e+07, n_window = NULL,\n overlap = TRUE, mode = c(\"coverage\", \"count\"),\n seqlengths = NULL) {\n # Check input validity\n assert_number_whole(window_size, allow_null = TRUE, min = 1)\n assert_number_whole(n_window, allow_null = TRUE, min = 1)\n if (is.null(window_size) && is.null(n_window)) {\n cli_abort(c(\n \"Both {.arg window_size} and {.arg n_window} are {.val NULL}.\",\n \"i\" = \"You must supply at least one of these arguments to define the binning strategy.\"\n ))\n }\n assert_bool(overlap)\n if (is.null(mode)) {\n mode <- \"coverage\"\n } else {\n mode <- arg_match0(mode, c(\"coverage\", \"count\"))\n }\n if (!is.data.frame(region) || ncol(region) < 3L) {\n cli_abort(\"{.arg region} must have at least 3 columns: chromosome, start, and end\")\n }\n if (anyNA(region[[1L]]) || anyNA(region[[2L]]) || anyNA(region[[3L]])) {\n cli_abort(\"Columns 1, 2, and 3 of {.arg region} must not contain missing values\")\n }\n if (!is.numeric(region[[2L]]) || !is.numeric(region[[3L]])) {\n cli_abort(\"Columns 2 and 3 of {.arg region} must be numeric (start and end positions)\")\n }\n if (any(region[[2L]] > region[[3L]])) {\n cli_abort(\"Column 2 (start) must not be greater than column 3 (end) in any row of {.arg region}\")\n }\n\n # Split the region data frame by chromosome (first column)\n groups <- vec_split(region, .subset2(region, 1L))\n density_list <- lapply(.subset2(groups, \"val\"), function(d) {\n chr <- .subset2(d, 1L)[1L]\n if (is.null(seqlengths)) {\n max_pos <- max(.subset2(region, 3L))\n } else {\n max_pos <- seqlengths[chr]\n if (is.na(max_pos)) {\n cli_abort(\"Chromosome {.val {chr}} is not found in {.arg seqlengths}. Please check that all chromosomes in {.arg region} have corresponding sequence lengths.\")\n }\n }\n if (overlap) {\n if (is.null(n_window)) {\n # Half-step sliding windows: start at 1, step = half window size\n b <- seq(0L, max_pos, by = window_size %/% 2L)\n s <- b[-length(b)]\n s <- s[-length(s)] + 1L\n e <- s + window_size - 1L\n } else {\n b <- seq(0L, max_pos, length.out = 2L * n_window + 1L)\n s <- b[-length(b)]\n s <- s[-length(s)] + 1L\n e <- s + b[3L] - b[1L] - 1L\n }\n } else {\n if (is.null(n_window)) {\n b <- seq(0L, max_pos, by = window_size)\n s <- b[-length(b)] + 1L\n e <- s + window_size - 1L\n } else {\n b <- seq(0, max_pos, length.out = n_window + 1L)\n s <- b[-length(b)] + 1L\n e <- s + b[2L] - b[1L]\n }\n }\n s <- as.integer(s)\n e <- as.integer(e)\n region_s <- .subset2(d, 2L)\n region_e <- .subset2(d, 3L)\n if (mode == \"count\") {\n # For each window, count how many regions overlap with it\n density <- vapply(seq_along(s), function(i) {\n si <- s[i]\n ei <- e[i]\n sum(!(region_s > ei | region_e < si))\n }, integer(1L), USE.NAMES = FALSE)\n } else {\n region_s <- as.integer(ceiling(region_s))\n region_e <- as.integer(floor(region_e))\n # For each window, calculate the proportion of bases covered by\n # regions\n density <- vapply(seq_along(s), function(i) {\n si <- s[i]\n ei <- e[i]\n # Keep regions that overlap with current window\n keep <- !(region_s > ei | region_e < si)\n\n # Clip regions to fit within the current window\n region_s_used <- pmax(region_s[keep], si)\n region_e_used <- pmin(region_e[keep], ei)\n\n # If no overlapping region, coverage is zero\n if (length(region_s_used) == 0L) {\n return(0)\n }\n\n # Sort intervals by start, then end\n ordering <- order(region_s_used, region_e_used)\n region_s_used <- region_s_used[ordering]\n region_e_used <- region_e_used[ordering]\n\n # Initialize with the first interval\n start <- region_s_used[1L]\n end <- region_e_used[1L]\n\n # If there's only one interval, just compute its coverage\n if (length(region_s_used) == 1L) {\n cov <- end - start + 1L\n return(cov / (ei - si + 1L))\n }\n # Merge overlapping/adjacent intervals and compute total\n # coverage\n cov <- 0L\n for (j in 2:length(region_s_used)) {\n if (region_s_used[j] - end <= 1L) {\n end <- max(end, region_e_used[j])\n } else {\n cov <- cov + (end - start + 1L)\n start <- region_s_used[j]\n end <- region_e_used[j]\n }\n }\n cov <- cov + (end - start + 1L)\n cov / (ei - si + 1L)\n }, numeric(1L), USE.NAMES = FALSE)\n }\n data_frame0(seqnames = chr, start = s, end = e, density = density)\n })\n vec_rbind(!!!density_list)\n}\n"], ["/ggalign/R/ggplot-geom-gshape.R", "#' Layer with a customized shape graphic using grid functions.\n#'\n#' @description\n#' `r lifecycle::badge('questioning')`\n#'\n#' `geom_gshape` depends on the new aesthetics `gshape` (shape with grid\n#' functions), which should always be provided with [`scale_gshape_manual()`],\n#' in which, we can provide a list of grobs or functions that define how each\n#' value should be drawn. Any ggplot2 aesthetics can be used as the arguments.\n#'\n#' @inheritParams ggplot2::layer\n#' @inheritParams ggplot2::geom_point\n#' @section Life cycle:\n#' We're unsure whether this function is truly necessary, which is why it is\n#' marked as questioning. So far, we've found that [`geom_subrect()`] and\n#' [`geom_subtile()`] handle most use cases effectively.\n#'\n#' @aesthetics GeomGshape\n#' @examples\n#' library(grid)\n#' ggplot(data.frame(value = letters[seq_len(5)], y = seq_len(5))) +\n#' geom_gshape(aes(x = 1, y = y, gshape = value, fill = value)) +\n#' scale_gshape_manual(values = list(\n#' a = function(x, y, width, height, fill) {\n#' rectGrob(x, y,\n#' width = width, height = height,\n#' gp = gpar(fill = fill),\n#' default.units = \"native\"\n#' )\n#' },\n#' b = function(x, y, width, height, fill) {\n#' rectGrob(x, y,\n#' width = width, height = height,\n#' gp = gpar(fill = fill),\n#' default.units = \"native\"\n#' )\n#' },\n#' c = function(x, y, width, height, fill) {\n#' rectGrob(x, y,\n#' width = width, height = height,\n#' gp = gpar(fill = fill),\n#' default.units = \"native\"\n#' )\n#' },\n#' d = function(x, y, width, height, shape) {\n#' gList(\n#' pointsGrob(x, y, pch = shape),\n#' # To ensure the rectangle color is shown in the legends, you\n#' # must explicitly provide a color argument and include it in\n#' # the `gpar()` of the graphical object\n#' rectGrob(x, y, width, height,\n#' gp = gpar(col = \"black\", fill = NA)\n#' )\n#' )\n#' },\n#' e = function(xmin, xmax, ymin, ymax) {\n#' segmentsGrob(\n#' xmin, ymin,\n#' xmax, ymax,\n#' gp = gpar(lwd = 2)\n#' )\n#' }\n#' )) +\n#' scale_fill_brewer(palette = \"Dark2\") +\n#' theme_void()\n#'\n#' @importFrom rlang list2\n#' @export\ngeom_gshape <- function(mapping = NULL, data = NULL, stat = \"identity\",\n position = \"identity\", ..., na.rm = FALSE,\n show.legend = NA, inherit.aes = TRUE) {\n dots <- list2(...)\n ggplot2::layer(\n data = data,\n mapping = mapping,\n stat = stat,\n geom = GeomGshape,\n position = position,\n show.legend = show.legend,\n inherit.aes = inherit.aes,\n params = c(list(na.rm = na.rm), dots, list(.__gshape_dots__ = dots))\n )\n}\n\n#' @inherit ggplot2::draw_key_point\n#' @description\n#' Each geom has an associated function that draws the key when the geom needs\n#' to be displayed in a legend. These functions are called `draw_key_*()`, where\n#' `*` stands for the name of the respective key glyph. The key glyphs can be\n#' customized for individual geoms by providing a geom with the `key_glyph`\n#' argument. The `draw_key_gshape` function provides this interface for custom\n#' key glyphs used with [`geom_gshape()`].\n#'\n#' @importFrom rlang inject\n#' @importFrom methods formalArgs\n#' @importFrom grid gTree\n#' @export\ndraw_key_gshape <- function(data, params, size) {\n gshape <- .subset2(data$gshape, 1L)\n data$gshape <- NULL\n if (is.function(gshape)) {\n for (d in formalArgs(gshape)) {\n if (is.null(.subset2(data, d))) {\n data[[d]] <- switch(d,\n x = ,\n y = 0.5,\n xmin = ,\n ymin = 0,\n xmax = ,\n ymax = 1,\n width = ,\n height = 1,\n color = data$colour %||% GeomGshape$default_aes[[\"colour\"]],\n fill = data$colour %||% GeomGshape$default_aes[[\"fill\"]],\n GeomGshape$default_aes[[d]]\n )\n }\n }\n }\n make_draw_grob(gshape, data, .subset2(params, \".__gshape_dots__\"))\n}\n\n#' @importFrom ggplot2 ggproto zeroGrob\n#' @importFrom rlang inject\n#' @importFrom grid gList\nGeomGshape <- ggproto(\n \"GeomGshape\",\n ggplot2::Geom,\n required_aes = c(\"x\", \"y\", \"gshape\"),\n default_aes = aes(\n shape = 19,\n colour = \"black\",\n size = 1.5,\n fill = NA,\n alpha = NA,\n stroke = 0.5,\n linewidth = 0.5,\n linetype = 1\n ),\n setup_data = ggplot2::GeomTile$setup_data,\n draw_panel = function(data, panel_params, coord, .__gshape_dots__) {\n coords <- coord$transform(data, panel_params)\n\n if (!is.null(coords$colour) && is.null(coords$color)) {\n coords$color <- coords$colour\n }\n if (!is.null(coords$color) && is.null(coords$colour)) {\n coords$colour <- coords$color\n }\n\n # restore width and height\n if (!is.null(coords$xmin) && !is.null(coords$xmax)) {\n coords$width <- coords$xmax - coords$xmin\n }\n if (!is.null(coords$ymin) && !is.null(coords$ymax)) {\n coords$height <- coords$ymax - coords$ymin\n }\n\n groups <- vec_group_loc(.subset2(coords, \"gshape\"))\n coords$gshape <- NULL\n\n # reordering by drawing order\n ordering <- vapply(\n .subset2(groups, \"key\"),\n function(gshape) {\n attr(gshape, \"gshape_ordering\", exact = TRUE) %||% NA_integer_\n },\n integer(1L),\n USE.NAMES = FALSE\n )\n groups <- vec_slice(groups, order(ordering))\n coords <- vec_chop(coords, indices = .subset2(groups, \"loc\"))\n\n grobs <- .mapply(\n make_draw_grob,\n list(draw = .subset2(groups, \"key\"), data = coords),\n list(dots = .__gshape_dots__)\n )\n grobs <- grobs[vapply(grobs, is.grob, logical(1L), USE.NAMES = FALSE)]\n if (is_empty(grobs)) {\n zeroGrob()\n } else {\n gTree(children = inject(gList(!!!grobs)))\n }\n },\n draw_key = draw_key_gshape\n)\n\n#' Scale for `gshape` aesthetic\n#'\n#' @inheritDotParams ggplot2::discrete_scale -expand -position -aesthetics -palette -scale_name\n#' @param values A list of grobs or functions (including purrr-like lambda\n#' syntax) that define how each cell's grob (graphical object) should be drawn.\n#' @inheritParams ggplot2::scale_discrete_manual\n#' @inherit geom_gshape\n#' @export\nscale_gshape_manual <- function(..., values, breaks = waiver(), na.value = NA) {\n ggplot2::scale_discrete_manual(\n aesthetics = \"gshape\",\n values = .mapply(function(f, i) {\n f <- allow_lambda(f)\n attr(f, \"gshape_ordering\") <- i # save the drawing order\n f\n }, list(values, seq_along(values)), NULL),\n breaks = breaks,\n na.value = na.value,\n ...\n )\n}\n\n# `gshape` should be provided manually\nscale_gshape_discrete <- function(name = waiver(), ...) {\n cli_abort(paste(\n \"You must provide {.fn scale_gshape_manual}\",\n \"to use {.field draw} aesthetic\"\n ))\n}\n\n# `gshape` should be provided manually\nscale_gshape_continuous <- scale_gshape_discrete\n"], ["/ggalign/R/fortify-matrix-matrix.R", "#' Build a matrix\n#'\n#' @param data A matrix object.\n#' @inheritParams rlang::args_dots_empty\n#' @inheritParams fortify_matrix\n#' @section shape:\n#' - `upset`: [`fortify_matrix.matrix_upset()`]\n#' - `oncoplot`: [`fortify_matrix.matrix_oncoplot()`]\n#' @family fortify_matrix\n#' @export\nfortify_matrix.matrix <- fortify_matrix.waiver\n\n#' Convert the shape of a matrix for fortify method\n#'\n#' @param data A matrix.\n#' @param shape A string of `r oxford_or(c(\"upset\", \"oncoplot\"))`.\n#' @seealso\n#' - [`fortify_matrix.matrix()`]\n#' - [`fortify_matrix.matrix_upset()`]\n#' - [`fortify_matrix.matrix_oncoplot()`]\n#' @family tune\n#' @importFrom rlang arg_match0\n#' @export\ntune.matrix <- function(data, shape) {\n shape <- arg_match0(shape, c(\"upset\", \"oncoplot\"))\n if (identical(shape, \"oncoplot\")) {\n if (!is.character(data)) {\n cli_abort(\n \"{.arg data} must be a character matrix to use {shape} shape\"\n )\n }\n }\n new_tune(data, class = sprintf(\"matrix_%s\", shape))\n}\n\n#' @inherit fortify_matrix.list_upset title\n#' @description\n#' Converts a matrix suitable for creating an UpSet plot. [`tune.matrix()`]\n#' helps convert `matrix` object to a `matrix_upset` object.\n#' @param data A matrix where each row represents an element, and each column\n#' defines a set. The values in the matrix indicate whether the element is part\n#' of the set. Any non-missing value signifies that the element exists in the\n#' set.\n#' @inheritParams fortify_matrix.list_upset\n#' @inheritDotParams fortify_matrix.list_upset\n#' @inheritSection fortify_matrix.list_upset ggalign attributes\n#' @seealso [`tune.matrix()`]\n#' @family fortify_matrix\n#' @export\nfortify_matrix.matrix_upset <- function(data, ..., data_arg = NULL,\n call = NULL) {\n call <- call %||% current_call()\n data <- !is.na(tune_data(data))\n elements <- vec_seq_along(data)\n fortify_matrix.list_upset(\n lapply(seq_len(ncol(data)), function(i) {\n .subset(elements, data[, i, drop = TRUE])\n }),\n ...,\n data_arg = data_arg,\n call = call\n )\n}\n\n#' Build a Matrix for OncoPrint\n#'\n#' @description\n#' Converts a matrix suitable for creating an OncoPrint. [`tune.matrix()`]\n#' helps convert `matrix` object to a `matrix_oncoplot` object.\n#'\n#' @param data A matrix where each row represents an genes, and each column\n#' represents samples. The values in the matrix indicate whether the element is\n#' part of the set.\n#' @inheritParams fortify_matrix.MAF\n#' @section ggalign attributes:\n#' - `gene_summary`: An integer vector of the altered samples for each gene.\n#' - `sample_summary`: An integer vector of the altered genes for each sample.\n#' - `n_genes`: Total number of genes.\n#' - `n_samples`: Total number of samples.\n#'\n#' @seealso [`tune.matrix()`]\n#' @family fortify_matrix\n#' @export\nfortify_matrix.matrix_oncoplot <- function(data, ...,\n genes = NULL, n_top = NULL,\n remove_empty_genes = TRUE,\n remove_empty_samples = TRUE,\n missing_genes = \"error\",\n data_arg = NULL,\n call = NULL) {\n call <- call %||% current_call()\n rlang::check_dots_empty(call = call)\n\n # check arguments\n missing_genes <- arg_match0(\n missing_genes, c(\"error\", \"remove\"),\n error_call = call\n )\n\n data <- tune_data(data)\n alt <- !is.na(data)\n storage.mode(alt) <- \"integer\"\n gene_summary <- rowSums(alt)\n sample_summary <- colSums(alt)\n n_genes <- nrow(data)\n n_samples <- ncol(data)\n\n # filter by genes --------------------------------------\n if (!is.null(genes)) {\n genes <- vec_cast(genes, character())\n if (vec_any_missing(genes)) {\n cli_abort(\n \"{.arg genes} cannot contain missing values\",\n call = call\n )\n }\n if (vec_duplicate_any(genes)) {\n cli_abort(\n \"{.arg genes} cannot contain duplicated values\",\n call = call\n )\n }\n if (identical(missing_genes, \"remove\")) {\n genes <- genes[genes %in% rownames(data)]\n }\n if (is_empty(genes)) {\n cli_abort(\n \"No {.arg genes} remain after removing missing genes\",\n call = call\n )\n }\n index <- vec_as_location(\n genes,\n n = vec_size(data),\n names = rownames(data),\n missing = \"error\"\n )\n data <- vec_slice(data, index)\n alt <- vec_slice(alt, index)\n gene_summary <- vec_slice(gene_summary, index)\n }\n\n if (!is.null(n_top)) {\n n_top <- min(n_top, vec_size(alt))\n index <- vec_slice(\n order(rowSums(alt), decreasing = TRUE),\n seq_len(n_top)\n )\n data <- vec_slice(data, index)\n alt <- vec_slice(alt, index)\n gene_summary <- vec_slice(gene_summary, index)\n }\n\n # filter empty genes\n if (remove_empty_genes) {\n keep <- rowSums(alt) > 0L\n data <- vec_slice(data, keep)\n gene_summary <- vec_slice(gene_summary, keep)\n }\n\n # filter empty samples\n if (remove_empty_samples) {\n keep <- colSums(alt) > 0L\n data <- data[, keep, drop = FALSE]\n sample_summary <- vec_slice(sample_summary, keep)\n }\n\n ggalign_data_set(data,\n sample_summary = sample_summary,\n gene_summary = gene_summary,\n n_samples = n_samples,\n n_genes = n_genes\n )\n}\n"], ["/ggalign/R/active.R", "#' Plot Adding Context Settings\n#'\n#' @description\n#' `r lifecycle::badge('experimental')`\n#'\n#' These settings control the behavior of the plot when added to a layout, as\n#' well as the arrangement of individual plot areas within the layout.\n#'\n#' @details\n#' By default, the active context is set only for functions that add plot areas.\n#' This allows other `ggplot2` elements-such as `geoms`, `stats`, `scales`, or\n#' `themes`- to be seamlessly added to the current plot area.\n#'\n#' The default ordering of the plot areas is from top to bottom or from left to\n#' right, depending on the layout orientation. However, users can customize this\n#' order using the `order` argument.\n#'\n#' @param order An integer specifying the order of the plot area within the\n#' layout.\n#' @param use A logical (`TRUE`/`FALSE`) indicating whether to set the\n#' active context to the current plot when added to a layout. If `TRUE`,\n#' any subsequent `ggplot` elements will be applied to this plot.\n#' @param name A string specifying the plot's name, useful for switching active\n#' contexts through the `what` argument in functions like\n#' [`quad_anno()`]/[`stack_switch()`].\n#' @export\nactive <- function(order = waiver(), use = waiver(), name = waiver()) {\n if (!is.waive(order)) order <- check_order(order)\n if (!is.waive(use)) assert_bool(use)\n if (!is.waive(name)) {\n assert_string(name,\n empty_ok = FALSE, allow_na = TRUE,\n allow_null = FALSE\n )\n }\n new_active(order = order, use = use, name = name)\n}\n\n# for internal function, we only adjust to the `use` argument\n# here, we put it in the first\nnew_active <- function(use, order = NA_integer_, name = NA_character_) {\n structure(\n list(order = order, use = use, name = name),\n class = \"ggalign_active\"\n )\n}\n\n#' @importFrom utils modifyList\nupdate_active <- function(active, default) {\n if (is.null(active)) return(default) # styler: off\n modifyList(default,\n active[!vapply(active, is.waive, logical(1L), USE.NAMES = FALSE)],\n keep.null = TRUE\n )\n}\n"], ["/ggalign/R/alignpatch-build.R", "#' @importFrom grid grid.draw\n#' @importFrom rlang try_fetch cnd_signal\n#' @export\nprint.alignpatches <- function(x, newpage = is.null(vp), vp = NULL, ...) {\n ggplot2::set_last_plot(x)\n if (newpage) {\n grid::grid.newpage()\n if (is.character(vp)) {\n cli_abort(c(\n \"{.arg vp} cannot be a character string when {.arg newpage} is TRUE.\",\n i = \"Please provide a viewport object or set {.arg newpage} to FALSE.\"\n ))\n }\n }\n if (!is.null(vp)) {\n if (is.character(vp)) {\n cur <- grid::current.viewport()$name\n grid::seekViewport(vp)\n if (!identical(cur, \"ROOT\")) on.exit(grid::seekViewport(cur))\n } else {\n grid::pushViewport(vp)\n on.exit(grid::upViewport())\n }\n }\n\n # render the plot\n try_fetch(\n grid.draw(x, ...),\n error = function(e) {\n if (inherits(e, \"simpleError\") &&\n deparse(conditionCall(e)[[1L]]) == \"grid.Call\") {\n error_name <- obj_type_friendly(x)\n if (Sys.getenv(\"RSTUDIO\") == \"1\") {\n cli_abort(c(paste(\n \"The RStudio {.field Plots} window may be\",\n \"too small to show\", error_name\n ), i = \"Please make the window larger.\"), parent = e)\n } else {\n cli_abort(c(\n \"The viewport may be too small to show {error_name}.\",\n i = \"Please make the window larger.\"\n ), parent = e)\n }\n }\n cnd_signal(e)\n }\n )\n invisible(x)\n}\n\n#' @importFrom grid grid.draw\n#' @exportS3Method\ngrid.draw.alignpatches <- function(x, recording = TRUE) {\n grid.draw(ggalignGrob(x), recording = recording)\n}\n\n#' @export\nggalign_build.alignpatches <- function(x) x\n\n#' @importFrom ggplot2 find_panel element_render theme theme_get\n#' @importFrom gtable gtable_add_grob gtable_add_rows gtable_add_cols\n#' @importFrom rlang arg_match0\n#' @importFrom S7 prop\n#' @export\nggalign_gtable.alignpatches <- function(x) {\n titles <- prop(x, \"titles\")\n\n # ensure theme has no missing value\n theme <- prop(x, \"theme\") %||% theme_get()\n\n # `TO-DO`: use `complete_theme()` from ggplot2 release\n theme <- complete_theme(theme)\n attr(x, \"theme\") <- theme # bypass the setter function\n table <- alignpatch(x)$patch_gtable(top_level = TRUE)\n\n fix_respect <- is.matrix(.subset2(table, \"respect\"))\n\n # Add title, subtitle, and caption -------------------\n # https://github.com/tidyverse/ggplot2/blob/2e08bba0910c11a46b6de9e375fade78b75d10dc/R/plot-build.R#L219C3-L219C9\n title <- element_render(\n theme = theme, \"plot.title\", .subset2(titles, \"title\"),\n margin_y = TRUE, margin_x = TRUE\n )\n title_height <- grobHeight(title)\n\n # Subtitle\n subtitle <- element_render(\n theme, \"plot.subtitle\", .subset2(titles, \"subtitle\"),\n margin_y = TRUE, margin_x = TRUE\n )\n subtitle_height <- grobHeight(subtitle)\n\n # caption\n caption <- element_render(\n theme, \"plot.caption\", .subset2(titles, \"caption\"),\n margin_y = TRUE, margin_x = TRUE\n )\n caption_height <- grobHeight(caption)\n\n # positioning of title and subtitle is governed by plot.title.position\n # positioning of caption is governed by plot.caption.position\n # \"panel\" means align to the panel(s)\n # \"plot\" means align to the entire plot (except margins and tag)\n panel_pos <- find_panel(table)\n title_pos <- arg_match0(\n theme$plot.title.position %||% \"panel\",\n c(\"panel\", \"plot\"),\n arg_nm = \"plot.title.position\",\n error_call = quote(theme())\n )\n\n caption_pos <- arg_match0(\n theme$plot.caption.position %||% \"panel\",\n values = c(\"panel\", \"plot\"),\n arg_nm = \"plot.caption.position\",\n error_call = quote(theme())\n )\n if (title_pos == \"panel\") {\n title_l <- panel_pos$l\n title_r <- panel_pos$r\n } else {\n title_l <- 1L\n title_r <- ncol(table)\n }\n if (caption_pos == \"panel\") {\n caption_l <- panel_pos$l\n caption_r <- panel_pos$r\n } else {\n caption_l <- 1L\n caption_r <- ncol(table)\n }\n\n table <- gtable_add_rows(table, subtitle_height, pos = 0)\n table <- gtable_add_grob(table, subtitle,\n name = \"subtitle\",\n t = 1, b = 1, l = title_l, r = title_r, clip = \"off\"\n )\n\n table <- gtable_add_rows(table, title_height, pos = 0)\n table <- gtable_add_grob(table, title,\n name = \"title\",\n t = 1, b = 1, l = title_l, r = title_r, clip = \"off\"\n )\n\n table <- gtable_add_rows(table, caption_height, pos = -1)\n table <- gtable_add_grob(table, caption,\n name = \"caption\",\n t = -1, b = -1, l = caption_l, r = caption_r, clip = \"off\"\n )\n if (fix_respect) {\n table$respect <- rbind(0L, 0L, table$respect, 0L)\n }\n\n # add margins --------------------------------------\n plot_margin <- calc_element(\"plot.margin\", theme)\n\n table <- gtable_add_rows(table, plot_margin[1L], 0L)\n table <- gtable_add_rows(table, plot_margin[3L])\n if (fix_respect) table$respect <- rbind(0L, table$respect, 0L)\n table <- gtable_add_cols(table, plot_margin[2L], 0L)\n table <- gtable_add_cols(table, plot_margin[4L])\n if (fix_respect) table$respect <- cbind(0L, table$respect, 0L)\n\n # add background -----------------------------------\n if (inherits(theme$plot.background, \"element\")) {\n table <- gtable_add_grob(table,\n element_render(theme, \"plot.background\"),\n t = 1L, l = 1L, b = -1L, r = -1L, name = \"background\", z = -Inf\n )\n table$layout <- table$layout[\n c(nrow(table$layout), 1:(nrow(table$layout) - 1L)),\n ]\n table$grobs <- table$grobs[\n c(nrow(table$layout), 1:(nrow(table$layout) - 1L))\n ]\n }\n table\n}\n"], ["/ggalign/R/grid-utils.R", "#' @importFrom grid gpar\n#' @export\ngrid::gpar\n\n#' @importFrom grid unit\n#' @export\ngrid::unit\n\nis.gList <- function(x) inherits(x, \"gList\")\n\nis.gTree <- function(x) inherits(x, \"gTree\")\n\n#' @importFrom grid unitType absolute.size\nis_absolute_unit <- function(x) unitType(absolute.size(x)) != \"null\"\n\n#' @importFrom grid unitType\nis_null_unit <- function(x) unitType(x) == \"null\"\n\nis_null_grob <- function(x) inherits(x, c(\"zeroGrob\", \"null\"))\n\n#' @importFrom grid is.grob nullGrob\nensure_grob <- function(x, default = nullGrob()) {\n if (is.gList(x)) x <- gTree(children = x)\n if (is.grob(x)) x else default\n}\n\n# `current.transform()` transforms from *inches* within the current viewport to\n# *inches* on the overall device.\ngrid_solve_loc <- function(loc, trans, valueOnly = FALSE) {\n x <- grid::convertX(loc$x, \"inches\", valueOnly = TRUE)\n y <- grid::convertY(loc$y, \"inches\", valueOnly = TRUE)\n out <- matrix(c(x, y, rep_len(1, length(x))), ncol = 3L) %*%\n trans\n out <- list(x = out[, 1L, drop = TRUE], y = out[, 2L, drop = TRUE])\n if (!valueOnly) out <- lapply(out, unit, \"inches\")\n out\n}\n\nloc_device2vp <- function(x, y, valueOnly = FALSE) {\n assert_s3_class(x, \"unit\")\n assert_s3_class(y, \"unit\")\n if (length(x) != length(y)) {\n cli_abort(\"{.arg x} and {.arg y} must have the same length\")\n }\n assert_bool(valueOnly)\n grid_solve_loc(\n list(x = x, y = y),\n solve(grid::current.transform()),\n valueOnly = valueOnly\n )\n}\n\nloc_vp2device <- function(x, y, valueOnly = FALSE) {\n assert_s3_class(x, \"unit\")\n assert_s3_class(y, \"unit\")\n if (length(x) != length(y)) {\n cli_abort(\"{.arg x} and {.arg y} must have the same length\")\n }\n assert_bool(valueOnly)\n grid::deviceLoc(x, y, valueOnly = valueOnly)\n}\n\n# # allow the missing value in the unit for `str` method\n# ggalign_unit <- function(x, ...) UseMethod(\"ggalign_unit\")\n# #' @export\n# ggalign_unit.default <- function(x, ...) ggalign_unit(as.numeric(x), ...)\n# #' @export\n# ggalign_unit.numeric <- function(x, units = \"null\", data = NULL, ...) {\n# add_class(unit(x, units, data = data), \"ggalign_unit\")\n# }\n# #' @export\n# ggalign_unit.unit <- function(x, ...) add_class(x, \"ggalign_unit\")\n# is_ggalign_unit <- function(x) inherits(x, \"ggalign_unit\")\n\n# # allow the missing value in the unit for `str` method\n#' @importFrom utils str\n#' @export\nstr.unit <- function(object, ...) obj_str(object, ...)\n\n#' @export\nvec_ptype_abbr.unit <- function(x, ...) fclass(x)\n\n#' @importFrom utils str\n#' @export\nobj_str_footer.unit <- function(x, ..., indent.str = \" \", nest.lev = 0,\n give.attr = TRUE) {\n if (!isTRUE(give.attr)) {\n return(invisible(x))\n }\n attr <- attributes(x)\n attr[[\"class\"]] <- NULL\n attr[[\"names\"]] <- NULL\n if (length(attr) == 0) {\n return(invisible(x))\n }\n indent.str <- paste0(\" \", indent.str)\n for (nm in names(attr)) {\n cat(indent.str, paste0(\"- attr(*, \\\"\", nm, \"\\\"):\"), sep = \"\")\n str(\n attr[[nm]],\n no.list = TRUE, ...,\n nest.lev = nest.lev + 1L,\n indent.str = indent.str\n )\n }\n invisible(x)\n}\n\n#' @importFrom gtable gtable_trim\nsubset_gt <- function(gt, index, trim = TRUE) {\n gt$layout <- vec_slice(.subset2(gt, \"layout\"), index)\n gt$grobs <- .subset(.subset2(gt, \"grobs\"), index)\n if (trim) gtable_trim(gt) else gt\n}\n\ngtable_trim_widths <- function(gt) {\n layout <- .subset2(gt, \"layout\")\n w <- range(.subset2(layout, \"l\"), .subset2(layout, \"r\"))\n gt$widths <- .subset2(gt, \"widths\")[seq.int(w[1L], w[2L])]\n if (is.matrix(respect <- .subset2(gt, \"respect\"))) {\n respect <- respect[, seq.int(w[1L], w[2L]), drop = FALSE]\n if (all(respect == 0L)) respect <- FALSE\n gt$respect <- respect\n }\n layout$l <- .subset2(layout, \"l\") - w[1L] + 1L\n layout$r <- .subset2(layout, \"r\") - w[1L] + 1L\n gt$layout <- layout\n gt\n}\n\ngtable_trim_heights <- function(gt) {\n layout <- .subset2(gt, \"layout\")\n h <- range(.subset2(layout, \"t\"), .subset2(layout, \"b\"))\n gt$heights <- .subset2(gt, \"heights\")[seq.int(h[1L], h[2L])]\n if (is.matrix(respect <- .subset2(gt, \"respect\"))) {\n respect <- respect[seq.int(h[1L], h[2L]), , drop = FALSE]\n if (all(respect == 0L)) respect <- FALSE\n gt$respect <- respect\n }\n layout$t <- .subset2(layout, \"t\") - h[1L] + 1L\n layout$b <- .subset2(layout, \"b\") - h[1L] + 1L\n gt$layout <- layout\n gt\n}\n\nliberate_area <- function(gt, top, left, bottom, right,\n clip = \"inherit\", name = NULL, vp = NULL) {\n if (any(remove <- grob_in_area(gt, top, right, bottom, left))) {\n liberated <- gt[top:bottom, left:right]\n if (is.function(vp <- allow_lambda(vp))) {\n liberated$vp <- vp(liberated)\n } else if (inherits(vp, \"viewport\")) {\n liberated$vp <- vp\n }\n liberated$respect <- FALSE\n name <- name %||%\n paste(\n .subset2(.subset2(liberated, \"layout\"), \"name\"),\n collapse = \"; \"\n )\n gt <- subset_gt(gt, !remove, trim = FALSE)\n gt <- gtable_add_grob(\n gt,\n list(liberated),\n top,\n left,\n bottom,\n right,\n z = max(.subset2(.subset2(liberated, \"layout\"), \"z\")),\n clip = clip,\n name = name\n )\n }\n gt\n}\n\ngrob_in_area <- function(gt, top, right, bottom, left) {\n .subset2(.subset2(gt, \"layout\"), \"l\") >= left &\n .subset2(.subset2(gt, \"layout\"), \"t\") >= top &\n .subset2(.subset2(gt, \"layout\"), \"r\") <= right &\n .subset2(.subset2(gt, \"layout\"), \"b\") <= bottom\n}\n\ncompute_null_width <- function(x, unitTo = \"mm\", valueOnly = FALSE) {\n compute_null_unit(x, \"width\", unitTo = unitTo, valueOnly = valueOnly)\n}\n\ncompute_null_height <- function(x, unitTo = \"mm\", valueOnly = FALSE) {\n compute_null_unit(x, \"height\", unitTo = unitTo, valueOnly = valueOnly)\n}\n\n#' @importFrom grid unit convertHeight convertWidth\ncompute_null_unit <- function(x, type = c(\"width\", \"height\"), unitTo = \"mm\",\n valueOnly = FALSE) {\n null <- is_null_unit(x) # null unit\n if (type == \"width\") {\n ans <- convertWidth(x, unitTo, valueOnly = TRUE)\n total <- convertWidth(unit(1, \"npc\"), unitTo = unitTo, valueOnly = TRUE)\n } else {\n ans <- convertHeight(x, unitTo, valueOnly = TRUE)\n total <- convertHeight(\n unit(1, \"npc\"),\n unitTo = unitTo,\n valueOnly = TRUE\n )\n }\n if (any(null)) {\n null_size <- total - sum(ans[!null])\n # other units in the same row/ column also have unit null\n coef <- as.numeric(x[null])\n ans[null] <- (null_size / sum(coef)) * coef\n }\n if (!valueOnly) ans <- unit(ans, unitTo)\n ans\n}\n"], ["/ggalign/R/ggplot-theme.R", "#' @importFrom ggplot2 theme_bw element_blank\ndefault_theme <- function() {\n if (is_theme_unset()) {\n theme_bw() +\n theme(\n axis.text = ggplot2::element_text(color = \"black\"),\n strip.text = ggplot2::element_text(color = \"black\"),\n panel.border = element_blank(),\n panel.grid = element_blank()\n )\n } else {\n theme_get()\n }\n}\n\n# Check if user has set the theme\nis_theme_unset <- function() {\n isTRUE(all.equal(\n complete_theme(ggfun(\"ggplot_global\")$theme_default),\n complete_theme(theme_get())\n ))\n}\n\nis_theme_complete <- function(x) isTRUE(attr(x, \"complete\", exact = TRUE))\n\n#' @importFrom ggplot2 rel element_blank\ntheme_no_strip <- function() {\n theme(\n strip.text = element_blank(),\n strip.background = element_blank()\n )\n}\n\ntheme_panel_border <- function() theme(panel.border = element_rect(fill = NA))\n\n#' @importFrom utils packageVersion\n#' @importFrom rlang try_fetch\ncomplete_theme <- function(theme) {\n if (packageVersion(\"ggplot2\") > \"3.5.2\") {\n ggfun(\"complete_theme\")(theme)\n } else {\n ggfun(\"plot_theme\")(list(theme = theme))\n }\n}\n\n#' @importFrom ggplot2 register_theme_elements el_def element_line\ntheme_elements <- function() {\n register_theme_elements(\n ggalign.line = element_line(\n color = \"black\",\n linewidth = 0.5,\n linetype = 1,\n lineend = \"butt\",\n linejoin = \"round\"\n ),\n ggalign.polygon = element_polygon(\n fill = NA,\n color = \"black\",\n linewidth = 0.5,\n linetype = 1,\n alpha = NA,\n lineend = \"butt\",\n linejoin = \"round\",\n linemitre = 10\n ),\n element_tree = list(\n plot.patch_title = el_def(\"element_text\", \"text\"),\n plot.patch_title.top = el_def(\"element_text\", \"text\"),\n plot.patch_title.left = el_def(\"element_text\", \"text\"),\n plot.patch_title.bottom = el_def(\"element_text\", \"text\"),\n plot.patch_title.right = el_def(\"element_text\", \"text\"),\n plot.patch_title.position = el_def(\"character\"),\n plot.patch_title.position.top = el_def(\"character\"),\n plot.patch_title.position.left = el_def(\"character\"),\n plot.patch_title.position.bottom = el_def(\"character\"),\n plot.patch_title.position.right = el_def(\"character\"),\n panel.spacing.r = el_def(c(\"unit\", \"rel\"), \"panel.spacing\"),\n ggalign.line = el_def(\"element_line\"),\n ggalign.curve = el_def(\"element_curve\"),\n ggalign.polygon = el_def(\"element_polygon\")\n )\n )\n}\n\n#' Used to match theme\n#'\n#' @keywords internal\n#' @noRd\ntheme_recycle <- function() structure(list(), class = \"theme_recycle\")\n\n#' @importFrom ggplot2 ggplot_add ggproto ggproto_parent\n#' @export\nggplot_add.theme_recycle <- function(object, plot, object_name, ...) {\n ParentFacet <- plot$facet\n if (!inherits(ParentFacet, c(\"FacetGrid\", \"FacetWrap\"))) {\n return(plot)\n }\n # recycle axis theme elements\n plot$facet <- ggproto(\n NULL, ParentFacet,\n draw_panels = function(self, panels, layout,\n x_scales = NULL, y_scales = NULL,\n ranges, coord, data = NULL, theme, params) {\n # we recycle the theme elements of the guide axis\n theme <- recycle_theme_axis(\"x\", theme, x_scales)\n theme <- recycle_theme_axis(\"y\", theme, y_scales)\n ParentCoord <- coord\n h_tick0 <- h_text0 <- 0L\n v_tick0 <- v_text0 <- 0L\n # subset theme for each panel\n coord <- ggproto(NULL, ParentCoord,\n # `align_scales` will attach the `.__plot_index__`\n render_axis_h = function(self, panel_params, theme) {\n scale <- (.subset2(panel_params, \"x\") %||%\n .subset2(panel_params, \"theta\")\n )$scale\n h_tick1 <- h_tick0 + length(scale$get_breaks())\n h_text1 <- h_text0 + length(scale$get_labels())\n theme <- subset_theme_axis(\n \"x\", theme, h_tick0, h_text0, h_tick1, h_text1\n )\n h_tick0 <<- h_tick1\n h_text0 <<- h_text1\n ggproto_parent(ParentCoord, self)$render_axis_h(\n panel_params, theme\n )\n },\n render_axis_v = function(self, panel_params, theme) {\n scale <- (.subset2(panel_params, \"y\") %||%\n .subset2(panel_params, \"r\")\n )$scale\n v_tick1 <- v_tick0 + length(scale$get_breaks())\n v_text1 <- v_text0 + length(scale$get_labels())\n theme <- subset_theme_axis(\n \"y\", theme, v_tick0, v_text0, v_tick1, v_text1\n )\n v_tick0 <<- v_tick1\n v_text0 <<- v_text1\n ggproto_parent(ParentCoord, self)$render_axis_v(\n panel_params, theme\n )\n }\n )\n ggproto_parent(ParentFacet, self)$draw_panels(\n panels = panels, layout = layout,\n x_scales = x_scales, y_scales = y_scales,\n ranges = ranges, coord = coord, data = data,\n theme = theme, params = params\n )\n }\n )\n plot\n}\n\n#################################################################\n# Apply a function to the vectorized field of the theme object\ntheme_vec <- function(.th, .el, .fn, ...) {\n element <- calc_element(.el, .th)\n if (inherits(element, \"element\")) {\n .th[[.el]] <- element_vec(element, .fn, ...)\n } else if (!is.null(element)) {\n .th[[.el]] <- .fn(element, ...)\n }\n .th\n}\n\nrecycle_theme_axis <- function(axis, theme, scales) {\n breaks <- unlist(lapply(scales, function(s) s$get_breaks()), FALSE, FALSE)\n labels <- unlist(lapply(scales, function(x) x$get_labels()), FALSE, FALSE)\n align_theme_axis(axis, theme,\n tick_fn = function(v, arg) rep(v, length.out = length(breaks)),\n text_fn = function(v, arg) rep(v, length.out = length(labels))\n )\n}\n\nsubset_theme_axis <- function(axis, theme, tick0, text0, tick1, text1) {\n tick_index <- (tick0 + 1L):tick1\n text_index <- (text0 + 1L):text1\n align_theme_axis(\n axis, theme,\n tick_fn = function(value) vec_slice(value, tick_index),\n text_fn = function(value) vec_slice(value, text_index)\n )\n}\n\nalign_theme_axis <- function(axis, theme, text_fn, tick_fn) {\n if (axis == \"y\") {\n positions <- c(\"left\", \"right\")\n } else {\n positions <- c(\"top\", \"bottom\")\n }\n # only apply the function when the element values is not a scalar\n .text_fn <- function(v) if (length(v) > 1L) text_fn(v) else v\n .tick_fn <- function(v) if (length(v) > 1L) tick_fn(v) else v\n for (element in paste(\"axis.text\", axis, positions, sep = \".\")) {\n theme <- theme_vec(theme, element, .text_fn)\n }\n for (element in paste(\"axis.ticks\", axis, positions, sep = \".\")) {\n theme <- theme_vec(theme, element, .tick_fn)\n }\n for (element in paste(\"axis.ticks.length\", axis, positions, sep = \".\")) {\n theme <- theme_vec(theme, element, .tick_fn)\n }\n theme\n}\n"], ["/ggalign/R/alignpatch-inset.R", "#' Create a ggplot inset\n#'\n#' @inheritParams ggwrap\n#' @return A `patch_inset` object, which can be added in ggplot.\n#' @inherit patch seealso\n#' @examples\n#' library(grid)\n#' p1 <- ggplot(mtcars) +\n#' geom_point(aes(mpg, disp))\n#' p2 <- ggplot(mtcars) +\n#' geom_boxplot(aes(gear, disp, group = gear))\n#' p1 + inset(p2, vp = viewport(0.6, 0.6,\n#' just = c(0, 0), width = 0.4, height = 0.4\n#' ))\n#' @export\ninset <- function(\n plot,\n ...,\n align = \"panel\",\n on_top = TRUE,\n clip = TRUE,\n vp = NULL) {\n make_inset(\n plot = plot,\n ...,\n align = align,\n on_top = on_top,\n clip = clip,\n vp = vp\n )\n}\n\n#' @importFrom grid editGrob\n#' @importFrom rlang arg_match0\nmake_inset <- function(\n plot,\n ...,\n align,\n on_top,\n clip,\n vp,\n call = caller_call()) {\n assert_bool(on_top, call = call)\n align <- arg_match0(align, c(\"panel\", \"plot\", \"full\"), error_call = call)\n assert_bool(clip, call = call)\n assert_s3_class(vp, \"viewport\", allow_null = TRUE, call = call)\n if (!is.grob(grob <- patch(x = plot, ...))) {\n cli_abort(\"{.fn patch} must return a {.cls grob}\", call = call)\n }\n if (!is.null(vp)) grob <- editGrob(grob, vp = vp)\n structure(\n list(\n grob = grob,\n align = align,\n clip = if (clip) \"on\" else \"off\",\n on_top = on_top\n ),\n class = \"patch_inset\"\n )\n}\n\n#' @importFrom grid grid.draw\n#' @export\ngrid.draw.patch_inset <- function(x, recording = TRUE) {\n grid.draw(.subset2(x, \"grob\"))\n}\n\n#' @importFrom ggplot2 ggplot_add\n#' @export\nggplot_add.patch_inset <- function(object, plot, object_name, ...) {\n make_wrap(plot, object)\n}\n"], ["/ggalign/R/grid-grob-channel.R", "#' Create a Grob That Spans Multiple Viewports\n#'\n#' This function initializes a communication channel to share location signals\n#' across different viewports. It returns a `channelSenderGrob` object, which\n#' can transmit multiple signals using its `$signal` method (see the \"Signal\"\n#' section below for details). When drawn, all collected signals are passed to\n#' the `make_content` function to generate the final [`grob`][grid::grob].\n#'\n#' @param make_content A function that accepts the list of signal locations and\n#' returns a [`grob`][grid::grob].\n#' @param ... Additional arguments passed to `make_content`.\n#' @inheritParams grid::grob\n#'\n#' @section Signal:\n#' A `channelSenderGrob` can emit multiple location signals using the `$signal`\n#' method. This method accepts the following arguments:\n#'\n#' - `x`: X-coordinate.\n#' - `y`: Y-coordinate.\n#' - `default.units`: The default units for `x` and `y`.\n#' - `tag`: A character string used to identify the location.\n#' - `name`: A name for the returned grob.\n#' - `vp`: A [`viewport`][grid::viewport] for the returned grob.\n#'\n#' The `$signal` method returns a `channelSignalGrob`.\n#'\n#' @return A `channelSenderGrob` object.\n#' @examples\n#' # we create a new channel, we will emit two singals\n#' # here: we just add a line between the two signals\n#' channel <- channelGrob(function(locations) {\n#' # you can also use `tag` to identify the locations\n#' loc1 <- .subset2(locations, 1L)\n#' loc2 <- .subset2(locations, 2L)\n#' grid::segmentsGrob(loc1$x, loc1$y, loc2$x, loc2$y)\n#' })\n#'\n#' gt <- gtable::gtable(unit(1:2, c(\"cm\")), unit(5, \"cm\"))\n#' gt <- gtable::gtable_add_grob(\n#' gt,\n#' list(\n#' grid::rectGrob(gp = gpar(color = \"black\", fill = NA)),\n#' channel$signal(0.5, 0.5, \"npc\")\n#' ),\n#' t = 1, l = 1, name = c(\"rect1\", \"signal1\")\n#' )\n#' gt <- gtable::gtable_add_grob(\n#' gt,\n#' list(\n#' grid::rectGrob(gp = gpar(color = \"red\", fill = NA)),\n#' channel$signal(0.5, 0.5, \"npc\")\n#' ),\n#' t = 1, l = 2, name = c(\"rect2\", \"signal2\")\n#' )\n#' grid::grid.newpage()\n#' grid::grid.draw(gt)\n#' @importFrom grid unit is.unit grob\n#' @importFrom rlang list2\n#' @export\nchannelGrob <- function(make_content, ..., name = NULL, vp = NULL) {\n make_content <- allow_lambda(make_content)\n if (!is.function(make_content)) {\n cli_abort(\"{.arg make_content} must be a function\")\n }\n # Used to communicate between different signals\n channel <- new.env(parent = emptyenv())\n channel$make_content <- make_content\n channel$dots <- list2(...)\n channel$n <- 0L # total number of signals\n grob(\n channel = channel,\n name = name,\n vp = vp,\n\n # method used to release signal and retutn a new grob\n signal = function(self, x, y, default.units = \"native\",\n tag = NULL, name = NULL, vp = NULL) {\n if (!is.unit(x)) x <- unit(x, default.units)\n if (!is.unit(y)) y <- unit(y, default.units)\n if (length(x) != length(y)) {\n cli_abort(\"{.arg x} and {.arg y} must have the same length\")\n }\n assert_string(tag, allow_empty = FALSE, allow_null = TRUE)\n signal <- list(list(x = x, y = y))\n if (!is.null(tag)) names(signal) <- tag\n channel <- .subset2(self, \"channel\")\n channel$signals <- c(channel$signals, signal)\n i <- channel$n <- channel$n + 1L\n grob(\n channel = channel,\n i = i,\n name = name,\n vp = vp,\n cl = c(\"channelSignalGrob\", \"channelGrob\")\n )\n },\n # Grob used to send signals\n cl = c(\"channelSenderGrob\", \"channelGrob\")\n )\n}\n\n#' @export\n`$.channelGrob` <- function(self, name) {\n field <- .subset2(self, name)\n if (!is.function(field)) {\n return(field)\n }\n args <- formals(field)\n # is.null is a fast path for a common case; the %in% check is slower but\n # also catches the case where there's a `self = NULL` argument.\n has_self <- !is.null(args[[\"self\"]]) || \"self\" %in% names(args)\n\n # We assign the method with its correct name and construct a call to it to\n # make errors reported as coming from the method name rather than `field()`\n assign(name, field, envir = environment())\n args <- list(quote(...))\n if (has_self) {\n args$self <- quote(self)\n }\n rlang::new_function(alist(... = ), rlang::call2(name, !!!args))\n}\n\n#' @export\n`[[.channelGrob` <- `$.channelGrob`\n\n# https://www.stat.auckland.ac.nz/~paul/Reports/CustomGrobs/custom-grob.html\n# preDraw:\n# - makeContext\n# - pushvpgp\n# - preDrawDetails: by default, do noting\n# makeContent:\n# drawDetails:\n# postDraw:\n# - postDrawDetails: by default, do noting\n# - popgrobvp\n#' @importFrom grid makeContent drawDetails viewport is.grob gTree grob\n#' @export\nmakeContent.channelGrob <- function(x) {\n channel <- .subset2(x, \"channel\")\n # If no signals, do nothing\n if (channel$n == 0L) return(x) # styler: off\n\n if (inherits(x, \"channelSenderGrob\")) {\n # we use the viewport from the signals sender\n channel$vp <- grid::current.viewport()\n } else if (inherits(x, \"channelSignalGrob\")) {\n if (is.null(channel$locations)) {\n channel$locations <- vector(\"list\", channel$n)\n names(channel$locations) <- names(channel$signals)\n }\n\n # convert the viewport coordinates to the device coordinates\n i <- .subset2(x, \"i\")\n signal <- .subset2(channel$signals, i)\n channel$locations[[i]] <- grid::deviceLoc(signal$x, signal$y)\n if (all(!vapply(channel$locations, is.null, logical(1L), # styler: off\n USE.NAMES = FALSE))) { # styler: off\n # When all locations have been prepared\n # we output the grob with all device locations\n x <- grob(\n channel = channel,\n vp = .subset2(x, \"vp\"), # Don't change the viewport\n cl = c(\"channelReceiverGrob\", \"channelGrob\")\n )\n }\n }\n x\n}\n\n#' @export\ndrawDetails.channelGrob <- function(x, recording) {\n}\n\n#' @importFrom grid grid.draw viewport gTree is.grob\n#' @export\ndrawDetails.channelReceiverGrob <- function(x, recording) {\n # we always reset the locations after drawing\n old <- grid::current.viewport()$name\n on.exit(grid::seekViewport(old), add = TRUE)\n channel <- .subset2(x, \"channel\")\n locations <- channel$locations\n on.exit(channel$locations <- NULL, add = TRUE)\n if (!is.null(vp <- channel$vp)) {\n grid::seekViewport(vp$name)\n # convert the device cooridnates into the drawing viewport coordinates\n trans <- solve(grid::current.transform())\n locations <- lapply(locations, grid_solve_loc, trans = trans)\n } else { # If no viewport, we use the `ROOT` viewport\n grid::upViewport(0)\n grid::pushViewport(viewport())\n }\n grob <- rlang::inject(channel$make_content(locations, !!!channel$dots))\n if (is.gList(grob)) grob <- gTree(children = grob)\n if (is.grob(grob)) grid.draw(grob, recording = recording)\n}\n"], ["/ggalign/R/fortify-data-frame-.R", "#' Build a data frame\n#'\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' This function converts various objects to a data frame.\n#'\n#' @param data An object to be converted to a data frame.\n#' @param ... Arguments passed to methods.\n#' @inheritParams fortify_matrix\n#' @return A data frame.\n#' @eval\n#' rd_collect_family(\"fortify_data_frame\",\n#' \"`fortify_data_frame` method collections\"\n#' )\n#' @export\nfortify_data_frame <- function(data, ..., data_arg = NULL, call = NULL) {\n UseMethod(\"fortify_data_frame\")\n}\n\n#' @inherit fortify_data_frame title description\n#' @param ... Additional arguments passed to [`fortify()`][ggplot2::fortify].\n#' @inheritParams fortify_data_frame\n#' @details\n#' By default, it calls [`fortify()`][ggplot2::fortify] to build the\n#' data frame.\n#' @family fortify_data_frame\n#' @export\nfortify_data_frame.default <- function(data, ..., data_arg = NULL,\n call = NULL) {\n ggplot2::fortify(model = data, ...)\n}\n\n#' @inherit fortify_data_frame.default title description\n#' @param data An object to be converted to a data frame.\n#' @inheritParams rlang::args_dots_empty\n#' @inheritParams fortify_data_frame\n#' @return A data frame with following columns:\n#'\n#' - `.names`: the names for the vector (only applicable if names exist).\n#' - `value`: the actual value of the vector.\n#'\n#' @family fortify_data_frame\n#' @export\nfortify_data_frame.character <- function(data, ..., data_arg = NULL,\n call = NULL) {\n call <- call %||% current_call()\n rlang::check_dots_empty(call = call)\n ans <- list(.names = vec_names(data), value = data)\n if (is.null(.subset2(ans, \".names\"))) ans$.names <- NULL\n new_data_frame(ans)\n}\n\n#' @rdname fortify_data_frame.character\n#' @export\nfortify_data_frame.numeric <- fortify_data_frame.character\n\n#' @rdname fortify_data_frame.character\n#' @export\nfortify_data_frame.logical <- fortify_data_frame.character\n\n#' @rdname fortify_data_frame.character\n#' @export\nfortify_data_frame.complex <- fortify_data_frame.character\n\n#' @export\nfortify_data_frame.waiver <- function(data, ..., data_arg = NULL,\n call = NULL) {\n call <- call %||% current_call()\n rlang::check_dots_empty(call = call)\n data\n}\n\n#' @export\nfortify_data_frame.NULL <- fortify_data_frame.waiver\n\n#' @inherit fortify_data_frame.default title description\n#' @param data An object to be converted to a data frame.\n#' @inheritParams fortify_data_frame\n#' @return A data frame with at least following columns:\n#'\n#' - `seqnames`: The sequence (e.g., chromosome) names.\n#' - `start`: The start positions of the ranges.\n#' - `end`: The end positions of the ranges.\n#' - `width`: The width of each range.\n#'\n#' @family fortify_data_frame\n#' @export\nfortify_data_frame.GRanges <- function(data, ..., data_arg = NULL,\n call = NULL) {\n as.data.frame(data, ...)\n}\n\n#' @inherit fortify_data_frame.default title description\n#' @param data A matrix-like object.\n#' @param lvls A logical value indicating whether to restore factor levels using\n#' those stored in [`ggalign_lvls()`], or a character vector specifying custom\n#' levels for the `value` column. If levels are provided or restored, the\n#' `value` column will be returned as a factor.\n#' @inheritParams rlang::args_dots_empty\n#' @inheritParams fortify_data_frame\n#' @return\n#' Matrix will be transformed into a long-form data frame, where each row\n#' represents a unique combination of matrix indices and their corresponding\n#' values. The resulting data frame will contain the following columns:\n#'\n#' - `.row_names` and `.row_index`: the row names (only applicable when names\n#' exist) and an integer representing the row index of the original matrix.\n#'\n#' - `.column_names` and `.column_index`: the column names (only applicable\n#' when names exist) and column index of the original matrix.\n#'\n#' - `value`: the matrix value, returned as a factor if levels are specified or\n#' restored.\n#'\n#' @family fortify_data_frame\n#' @export\nfortify_data_frame.matrix <- function(data, lvls = NULL, ...,\n data_arg = NULL, call = NULL) {\n call <- call %||% current_call()\n rlang::check_dots_empty(call = call)\n row_nms <- vec_names(data)\n col_nms <- colnames(data)\n if (isFALSE(lvls)) {\n lvls <- NULL\n } else if (isTRUE(lvls)) {\n lvls <- ggalign_lvls_get(lvls)\n } else if (!is.null(lvls) && !is.character(lvls)) {\n cli_abort(\n \"{.arg lvls} must be a single boolean value or a character\",\n call = call\n )\n }\n data <- new_data_frame(list(\n .row_index = vec_rep(seq_len(nrow(data)), ncol(data)),\n .column_index = vec_rep_each(seq_len(ncol(data)), nrow(data)),\n value = c(data)\n ))\n if (!is.null(row_nms)) data$.row_names <- row_nms[data$.row_index]\n if (!is.null(col_nms)) data$.column_names <- col_nms[data$.column_index]\n if (!is.null(lvls)) data$value <- factor(data$value, levels = lvls)\n data\n}\n\n#' @export\n#' @rdname fortify_data_frame.matrix\nfortify_data_frame.DelayedMatrix <- function(data, ...) {\n fortify_data_frame(as.matrix(data), ...)\n}\n\n#' @export\n#' @rdname fortify_data_frame.matrix\nfortify_data_frame.Matrix <- function(data, ...) {\n fortify_data_frame(as.matrix(data), ...)\n}\n"], ["/ggalign/R/layout-chain-stack-composer.R", "#' @keywords internal\nstack_composer <- function(direction) {\n structure(\n list(\n t = integer(), l = integer(),\n b = integer(), r = integer(),\n plots = list(), sizes = list(),\n direction = direction,\n align = 1L,\n # attributes used by `stack_layout()`\n left_or_top = FALSE, right_or_bottom = FALSE\n ),\n class = \"stack_composer\"\n )\n}\n\nstack_composer_add_plot <- function(composer, plot, t, l, b = t, r = l) {\n composer$t <- c(.subset2(composer, \"t\"), t)\n composer$l <- c(.subset2(composer, \"l\"), l)\n composer$b <- c(.subset2(composer, \"b\"), b)\n composer$r <- c(.subset2(composer, \"r\"), r)\n composer$plots <- c(.subset2(composer, \"plots\"), list(plot))\n composer\n}\n\n#' @importFrom rlang is_empty\nstack_composer_align_plot <- function(composer, plot, size) {\n if (is.null(plot)) {\n return(composer)\n }\n if (is_horizontal(.subset2(composer, \"direction\"))) {\n r_border <- .subset2(composer, \"r\")\n if (is_empty(r_border)) {\n l <- 1L\n } else {\n l <- max(r_border) + 1L\n }\n t <- .subset2(composer, \"align\")\n } else {\n b_border <- .subset2(composer, \"b\")\n if (is_empty(b_border)) {\n t <- 1L\n } else {\n t <- max(b_border) + 1L\n }\n l <- .subset2(composer, \"align\")\n }\n composer$sizes <- c(.subset2(composer, \"sizes\"), list(size))\n stack_composer_add_plot(composer, plot, t, l)\n}\n\nstack_composer_add <- function(plot, stack, composer, ...) {\n UseMethod(\"stack_composer_add\")\n}\n\n#' @importFrom utils packageVersion\n#' @export\nstack_composer_add.CraftBox <- function(plot, stack, composer, design, ...,\n schemes, theme,\n released_spaces,\n direction, position) {\n size <- plot@size\n\n # for `released_spaces`, release the `free_spaces` in a single plot\n plot_schemes <- inherit_schemes(plot@schemes, schemes)\n if (!is.null(released_spaces)) {\n plot_spaces <- .subset2(\n .subset2(plot_schemes, \"scheme_align\"), \"free_spaces\"\n )\n if (is_string(plot_spaces)) {\n plot_spaces <- setdiff_position(plot_spaces, released_spaces)\n if (!nzchar(plot_spaces)) plot_spaces <- NULL\n plot_schemes$scheme_align[\"free_spaces\"] <- list(plot_spaces)\n }\n }\n\n # let `Align` to determine how to build the plot\n craftsman <- plot@craftsman # `Craftsman` object\n plot <- plot@plot\n if (!craftsman$free_facet && is_discrete_design(design)) {\n if (nlevels(.subset2(design, \"panel\")) > 1L) {\n if (is_horizontal(direction)) {\n facet <- ggplot2::facet_grid(\n rows = ggplot2::vars(.data$.panel),\n scales = \"free_y\", space = \"free\",\n drop = FALSE, as.table = FALSE\n )\n free_row <- FALSE\n free_column <- TRUE\n } else {\n facet <- ggplot2::facet_grid(\n cols = ggplot2::vars(.data$.panel),\n scales = \"free_x\", space = \"free\",\n drop = FALSE, as.table = FALSE\n )\n free_row <- TRUE\n free_column <- FALSE\n }\n } else {\n facet <- facet_stack(direction, craftsman$layout_name)\n }\n plot <- ggmelt_facet(plot, facet,\n free_row = free_row, free_column = free_column\n )\n }\n if (!craftsman$free_coord) {\n plot <- gguse_linear_coord(plot, layout_name = craftsman$layout_name)\n }\n\n # set limits and default scales\n if (!craftsman$free_limits) {\n if (is_horizontal(direction)) {\n plot <- plot + ggalign_design(\n y = design,\n ylabels = .subset(craftsman$labels, .subset2(design, \"index\"))\n )\n } else {\n plot <- plot + ggalign_design(\n x = design,\n xlabels = .subset(craftsman$labels, .subset2(design, \"index\"))\n )\n }\n }\n\n # let `Craftsman` add other components\n plot <- craftsman$build_plot(plot, design = design, ...)\n plot <- craftsman$finish_plot(plot, plot_schemes, theme)\n\n # Let layout finally modify the plot\n plot <- chain_decorate(stack, plot)\n\n # add the plot to the composer\n stack_composer_align_plot(composer, plot, size)\n}\n\n#' @importFrom grid unit.c unit\nstack_composer_add.QuadLayout <- function(plot, stack, composer, schemes, theme,\n direction, ...) {\n patches <- quad_build(plot, schemes, theme, direction)\n plots <- .subset2(patches, \"plots\")\n sizes <- .subset2(patches, \"sizes\")\n\n if (is_horizontal(.subset2(composer, \"direction\"))) {\n composer$left_or_top <- .subset2(composer, \"left_or_top\") ||\n !is.null(.subset2(plots, \"top\"))\n composer$right_or_bottom <- .subset2(composer, \"right_or_bottom\") ||\n !is.null(.subset2(plots, \"bottom\"))\n composer <- stack_composer_align_plot(\n composer,\n .subset2(plots, \"left\"),\n .subset2(sizes, \"left\")\n )\n composer <- stack_composer_align_plot(\n composer,\n .subset2(plots, \"main\"),\n .subset2(.subset2(sizes, \"main\"), \"width\")\n )\n l <- max(.subset2(composer, \"r\"))\n if (!is.null(top <- .subset2(plots, \"top\"))) {\n if (.subset2(composer, \"align\") == 1L) {\n composer$t <- .subset2(composer, \"t\") + 1L\n composer$b <- .subset2(composer, \"b\") + 1L\n composer$align <- .subset2(composer, \"align\") + 1L\n }\n if (!is_null_unit(size <- .subset2(sizes, \"top\"))) {\n attr(top, \"vp\")$height <- size\n }\n composer <- stack_composer_add_plot(composer, top, t = 1L, l = l)\n }\n if (!is.null(bottom <- .subset2(plots, \"bottom\"))) {\n if (!is_null_unit(size <- .subset2(sizes, \"bottom\"))) {\n attr(bottom, \"vp\")$height <- size\n }\n composer <- stack_composer_add_plot(composer, bottom,\n t = .subset2(composer, \"align\") + 1L, l = l\n )\n }\n composer <- stack_composer_align_plot(\n composer,\n .subset2(plots, \"right\"),\n .subset2(sizes, \"right\")\n )\n } else {\n composer$left_or_top <- .subset2(composer, \"left_or_top\") ||\n !is.null(.subset2(plots, \"left\"))\n composer$right_or_bottom <- .subset2(composer, \"right_or_bottom\") ||\n !is.null(.subset2(plots, \"right\"))\n composer <- stack_composer_align_plot(\n composer,\n .subset2(plots, \"top\"),\n .subset2(sizes, \"top\")\n )\n composer <- stack_composer_align_plot(\n composer,\n .subset2(plots, \"main\"),\n .subset2(.subset2(sizes, \"main\"), \"height\")\n )\n t <- max(.subset2(composer, \"b\"))\n if (!is.null(left <- .subset2(plots, \"left\"))) {\n if (.subset2(composer, \"align\") == 1L) {\n composer$l <- .subset2(composer, \"l\") + 1L\n composer$r <- .subset2(composer, \"r\") + 1L\n composer$align <- .subset2(composer, \"align\") + 1L\n }\n if (!is_null_unit(size <- .subset2(sizes, \"left\"))) {\n attr(left, \"vp\")$width <- size\n }\n composer <- stack_composer_add_plot(composer, left, t = t, l = 1L)\n }\n if (!is.null(right <- .subset2(plots, \"right\"))) {\n if (!is_null_unit(size <- .subset2(sizes, \"right\"))) {\n attr(right, \"vp\")$width <- size\n }\n composer <- stack_composer_add_plot(composer, right,\n t = t, l = .subset2(composer, \"align\") + 1L\n )\n }\n composer <- stack_composer_align_plot(\n composer,\n .subset2(plots, \"bottom\"),\n .subset2(sizes, \"bottom\")\n )\n }\n composer\n}\n\n#' @export\nstack_composer_add.list <- function(plot, stack, composer, ...) {\n for (p in plot) {\n composer <- stack_composer_add(\n plot = p, stack = stack, composer = composer, ...\n )\n }\n composer\n}\n"], ["/ggalign/R/import-standalone-tibble.R", "# Standalone file: do not edit by hand\n# Source: https://github.com/Yunuuuu/standalone/blob/HEAD/R/standalone-tibble.R\n# Generated by: usethis::use_standalone(\"Yunuuuu/standalone\", \"tibble\")\n# ----------------------------------------------------------------------\n#\n# ---\n# repo: Yunuuuu/standalone\n# file: standalone-tibble.R\n# last-updated: 2024-11-14\n# license: https://unlicense.org\n# imports: [vctrs (>= 0.5.0), rlang]\n# ---\n\n# when developing R package, instead of depending on `dplyr`, `tidyr`, `tibble`.\n# we prefer use the basic function from `vctrs`\n#\n# Note: these functions won't check arguments\n#\n# Since `vctrs` also depends on `rlang` and `cli`, it has no harm to use\n# function from `rlang` and `cli`.\n#\n# Please initialize the package docs and import vctrs\n# 1. run `usethis::use_package_doc()`\n# 2. in package docs, please add #' @import vctrs\n\n# ## Changelog\n# 2025-03-12\n# - Added `case_when()`\n#\n# 2024-11-14\n# - Added `column_to_rownames()`\n#\n# 2024-11-13\n# - fix wrong results in `coalesce()`: we should assign value in the missing\n# index\n#\n# 2024-11-12\n# - Added `rename`\n# - coalesce() now will return value immediately when no missing value exists.\n#\n# 2024-11-11:\n# - Added `inner_join`\n# - Added `left_join`\n# - Added `right_join`\n# - Added `cross_join`\n# - Added `replace_na`\n# - Added `coalesce`\n# - Added `deframe`\n# - Added `enframe`\n# - Added `remove_rownames`\n# - Added `rownames_to_column`\n#\n# 2024-11-10:\n# - Added `full_join`\n# - Added `if_else`\n#\n# nocov start\n\n#' @importFrom rlang set_names\nfull_join <- function(\n x,\n y,\n by = vec_set_intersect(names(x), names(y)),\n by.x = by,\n by.y = by,\n suffix = c(\".x\", \".y\")\n) {\n loc <- vec_locate_matches(x[by.x], set_names(y[by.y], by.x), remaining = NA)\n x_slicer <- .subset2(loc, \"needles\")\n y_slicer <- .subset2(loc, \"haystack\")\n ans <- join_bind(\n vec_slice(x, x_slicer),\n # drop duplicated join column\n vec_slice(y[vec_set_difference(names(y), by.y)], y_slicer),\n suffix = suffix\n )\n new_rows <- which(vec_detect_missing(x_slicer)) # should come from `y`\n if (length(new_rows)) {\n ans[new_rows, by.x] <- vec_slice(y[by.y], y_slicer[new_rows])\n }\n ans\n}\n\n#' @importFrom rlang set_names\ninner_join <- function(\n x,\n y,\n by = vec_set_intersect(names(x), names(y)),\n by.x = by,\n by.y = by,\n suffix = c(\".x\", \".y\")\n) {\n loc <- vec_locate_matches(\n x[by.x],\n set_names(y[by.y], by.x),\n no_match = \"drop\"\n )\n x_slicer <- .subset2(loc, \"needles\")\n y_slicer <- .subset2(loc, \"haystack\")\n join_bind(\n vec_slice(x, x_slicer),\n # drop duplicated join column\n vec_slice(y[vec_set_difference(names(y), by.y)], y_slicer),\n suffix = suffix\n )\n}\n\n#' @importFrom rlang set_names\nleft_join <- function(\n x,\n y,\n by = vec_set_intersect(names(x), names(y)),\n by.x = by,\n by.y = by,\n suffix = c(\".x\", \".y\")\n) {\n loc <- vec_locate_matches(x[by.x], set_names(y[by.y], by.x))\n x_slicer <- .subset2(loc, \"needles\")\n y_slicer <- .subset2(loc, \"haystack\") # can have NA value\n join_bind(\n vec_slice(x, x_slicer),\n # drop duplicated join column\n vec_slice(y[vec_set_difference(names(y), by.y)], y_slicer),\n suffix = suffix\n )\n}\n\n#' @importFrom rlang set_names\nright_join <- function(\n x,\n y,\n by = vec_set_intersect(names(x), names(y)),\n by.x = by,\n by.y = by,\n suffix = c(\".x\", \".y\")\n) {\n loc <- vec_locate_matches(\n x[by.x],\n set_names(y[by.y], by.x),\n no_match = \"drop\",\n remaining = NA\n )\n x_slicer <- .subset2(loc, \"needles\") # can have NA value\n y_slicer <- .subset2(loc, \"haystack\")\n join_bind(\n # drop duplicated join column\n vec_slice(x[vec_set_difference(names(x), by.x)], x_slicer),\n vec_slice(y, y_slicer),\n suffix = suffix\n )\n}\n\ncross_join <- function(x, y, suffix = c(\".x\", \".y\")) {\n x_size <- vec_size(x)\n y_size <- vec_size(y)\n x_out <- vec_rep_each(x, times = y_size)\n y_out <- vec_rep(y, times = x_size)\n join_bind(x_out, y_out, suffix)\n}\n\njoin_bind <- function(x, y, suffix) {\n x_names <- names(x)\n y_names <- names(y)\n common <- vec_set_intersect(x_names, y_names)\n if (length(common)) {\n # add suffix to duplicated names\n index <- vec_match(common, x_names)\n names(x)[index] <- paste0(x_names[index], .subset(suffix, 1L))\n index <- vec_match(common, y_names)\n names(y)[index] <- paste0(y_names[index], .subset(suffix, 2L))\n }\n vec_cbind(x, y, .name_repair = \"check_unique\")\n}\n\n#' Rename elements in a list, data.frame or vector\n#'\n#' This is akin to `dplyr::rename` and `plyr::rename`. It renames elements given\n#' as names in the `replace` vector to the values in the `replace` vector\n#' without touching elements not referenced.\n#'\n#' @param x A data.frame or a named vector or list\n#' @param replace A named character vector. The names identifies the elements in\n#' `x` that should be renamed and the values gives the new names.\n#'\n#' @return `x`, with new names according to `replace`\n#' @noRd\nrename <- function(x, replace) {\n nms <- names(x)\n names(x) <- vec_assign(nms, match(names(replace), nms), replace)\n x\n}\n\nif_else <- function(condition, true, false, na = NULL) {\n # output size from `condition`\n size <- vec_size(condition)\n\n # output type from `true`/`false`/`na`\n ptype <- vec_ptype_common(true = true, false = false, na = na)\n\n args <- vec_recycle_common(\n true = true,\n false = false,\n na = na,\n .size = size\n )\n args <- vec_cast_common(!!!args, .to = ptype)\n\n out <- vec_init(ptype, size)\n\n loc_true <- condition\n loc_false <- !condition\n\n out <- vec_assign(out, loc_true, vec_slice(args$true, loc_true))\n out <- vec_assign(out, loc_false, vec_slice(args$false, loc_false))\n\n if (!is.null(na)) {\n loc_na <- vec_detect_missing(condition)\n out <- vec_assign(out, loc_na, vec_slice(args$na, loc_na))\n }\n\n out\n}\n\ncase_when <- function(.default, ..., .ptype = NULL) {\n if (is.null(.ptype)) {\n .ptype <- vec_ptype(.default)\n } else {\n .default <- vec_cast(.default, .ptype)\n }\n env <- rlang::caller_env()\n dots <- rlang::list2(...)\n unused <- vec_rep(TRUE, times = vec_size(.default))\n for (i in seq_along(dots)) {\n if (!any(unused)) {\n break\n }\n dot <- .subset2(dots, i)\n loc <- unused & rlang::eval_tidy(rlang::f_lhs(dot), env = env)\n value <- rlang::eval_tidy(rlang::f_rhs(dot), env = env)\n value <- vec_cast(value, .ptype, x_arg = sprintf(\"`...` (%d)\", i))\n if (length(value) > 1L) value <- vec_slice(value, loc)\n .default <- vec_assign(\n .default,\n loc,\n value,\n value_arg = sprintf(\"`...` (%d)\", i)\n )\n unused[loc] <- FALSE\n }\n .default\n}\n\n\n#' Replace NAs with specified values\n#' @param value A single value.\n#' @noRd\nreplace_na <- function(x, value) {\n value <- vec_cast(x = value, to = x, x_arg = \"value\", to_arg = \"x\")\n vec_assign(x, vec_detect_missing(x), value)\n}\n\n#' Find the first non-missing element\n#' @param ... A list of atomic vector (You shouldn't input `NULL`).\n#' @noRd\ncoalesce <- function(...) {\n dots <- vec_recycle_common(...)\n out <- .subset2(dots, 1L)\n for (i in 2:length(dots)) {\n if (vec_any_missing(out)) {\n missing <- vec_detect_missing(out)\n out <- vec_assign(\n out,\n missing,\n vec_slice(.subset2(dots, i), missing)\n )\n } else {\n return(out)\n }\n }\n out\n}\n\n#' Convert values to `NA`\n#' @noRd\nna_if <- function(x, y) {\n y <- vec_cast(x = y, to = x, x_arg = \"y\", to_arg = \"x\")\n y <- vec_recycle(y, size = vec_size(x), x_arg = \"y\")\n na <- vec_init(x)\n vec_assign(x, vec_equal(x, y, na_equal = TRUE), na)\n}\n\ndeframe <- function(x) {\n if (ncol(x) == 1L) {\n return(x[[1]])\n }\n vec_set_names(x[[1L]], x[[2]])\n}\n\nenframe <- function(x, name = \"name\", value = \"value\") {\n if (!is.null(names(x))) {\n data <- list(names(x), unname(x))\n } else {\n data <- list(seq_along(x), unname(x))\n }\n new_data_frame(vec_set_names(data, c(name, value)))\n}\n\nremove_rownames <- function(.data) {\n rownames(.data) <- NULL\n .data\n}\n\nrownames_to_column <- function(.data, var = \"rowname\") {\n if (!is.null(var_col <- rownames(.data))) {\n nms <- names(.data)\n .data[[var]] <- var_col\n .data <- .data[c(var, nms)]\n }\n .data\n}\n\ncolumn_to_rownames <- function(.data, var = 1L) {\n rownames(.data) <- .subset2(.data, var)\n .data[[var]] <- NULL\n .data\n}\n\n# nocov end\n"], ["/ggalign/R/alignpatch-guides.R", "#' Returns a list of guide boxes collected from all plots.\n#' Each element in the list corresponds to a specific position, containing a\n#' sub-list of guide boxes, where each guide box represents a single plot.\n#' @noRd\ncollect_guides_list <- function(guides_list, empty = NULL) {\n ans <- lapply(c(.TLBR, \"inside\"), function(guide_pos) {\n guides <- lapply(guides_list, function(guides) {\n # IF no guide-box, a single `zeroGrob()` will be given\n # here, we regard each position is a `zeroGrob()`\n if (is_null_grob(guides)) return(list(guides)) # styler: off\n o <- .subset2(guides, guide_pos)\n # A guide-box should be a `zeroGrob()` or a `gtable` object\n if (maybe_guide_box(o)) {\n return(list(o))\n }\n # For other grobs, we just removed them silently\n if (is.grob(o)) {\n list(NULL)\n } else if (is.list(o)) {\n o[\n vapply(o, maybe_guide_box, # styler: off\n logical(1L), USE.NAMES = FALSE # styler: off\n )\n ]\n } else {\n list(NULL)\n }\n })\n guides <- unlist(guides, FALSE, FALSE)\n guides <- guides[\n !vapply(guides, is.null, logical(1L), USE.NAMES = FALSE)\n ]\n if (is_empty(guides)) empty else guides\n })\n names(ans) <- c(.TLBR, \"inside\")\n ans[!vapply(ans, is.null, logical(1L), USE.NAMES = FALSE)]\n}\n\n#' @param guides A list of guide-box\n#' @importFrom ggplot2 zeroGrob\n#' @importFrom gtable gtable gtable_add_grob\n#' @noRd\nassemble_guides <- function(guides, guide_pos, theme) {\n if (guide_pos == \"inside\") {\n # for `zeroGrob()`, it doesn't record the `viewport` information\n # used to identify the inside guide groups, we just removed them\n guides <- guides[\n !vapply(guides, is_null_grob, logical(1L), USE.NAMES = FALSE)\n ]\n if (is_empty(guides)) {\n guide_box <- zeroGrob()\n } else {\n positions <- justs <- vector(\"list\", length(guides))\n for (i in seq_along(guides)) {\n guide <- .subset2(guides, i)\n # for inside guides, it may contain multiple guide-box\n is_box <- grepl(\"guide-box-inside\", guide$layout$name)\n if (any(is_box)) {\n guides[[i]] <- guide$grobs[is_box]\n } else {\n guides[[i]] <- list(guide)\n }\n positions[[i]] <- lapply(guides[[i]], function(guide_box) {\n unit.c(guide_box$vp$x, guide_box$vp$y)\n })\n justs[[i]] <- lapply(guides[[i]], function(guide_box) {\n guide_box$vp$justification\n })\n }\n guides <- unlist(guides, FALSE, FALSE)\n groups <- data_frame0(\n positions = unlist(positions, FALSE, FALSE),\n justs = unlist(justs, FALSE, FALSE)\n )\n groups <- vec_group_loc(groups)\n index <- vec_seq_along(groups)\n\n # pakcage each group into a guide-box\n box_list <- vector(\"list\", vec_size(index))\n for (i in index) {\n box_list[[i]] <- assemble_box(\n guides[groups$loc[[i]]], guide_pos,\n theme = theme + theme(\n legend.position.inside = groups$key$positions[[i]],\n legend.justification.inside = groups$key$justs[[i]]\n )\n )\n }\n if (vec_size(box_list) > 1L) {\n guide_box <- gtable(unit(1L, \"npc\"), unit(1L, \"npc\"))\n guide_box <- gtable_add_grob(\n guide_box, box_list,\n t = 1L, l = 1L, clip = \"off\",\n name = paste(\"guide-box-collected-inside\", index, sep = \"-\")\n )\n } else {\n guide_box <- box_list[[1L]]\n }\n }\n } else {\n guide_box <- assemble_box(guides, guide_pos, theme = theme)\n }\n guide_box\n}\n\n#' @param guides A list of guide-box\n#' @importFrom rlang try_fetch\n#' @importFrom ggplot2 zeroGrob\n#' @noRd\nassemble_box <- function(guides, guide_pos, theme) {\n guides <- guides[\n !vapply(guides, is_null_grob, logical(1L), USE.NAMES = FALSE)\n ]\n if (is_empty(guides)) {\n zeroGrob()\n } else {\n # Remove the guide box background\n grobs <- lapply(guides, function(box) {\n box$grobs[grepl(\"guides\", box$layout$name)]\n })\n grobs <- unlist(grobs, FALSE, FALSE)\n\n # remove duplicated guides\n grobs <- collapse_guides(grobs)\n if (is_empty(grobs)) return(zeroGrob()) # styler: off\n # for every position, collect all individual guides and arrange them\n # into a guide box which will be inserted into the main gtable\n package_box <- try_fetch(\n .subset2(ggfun(\"Guides\"), \"package_box\"),\n error = function(cnd) package_box\n )\n package_box(grobs, guide_pos, theme)\n }\n}\n\n# The following code was used in earlier versions of ggplot2; \n# coverage is not calculated here.\n# nocov start\n#' @importFrom gtable gtable_add_rows gtable_add_cols\n#' @importFrom ggplot2 calc_element\n#' @importFrom grid valid.just editGrob viewport\npackage_box <- function(guides, guide_pos, theme) {\n theme <- complete_guide_theme(guide_pos, theme)\n guides <- guides_build(guides, theme)\n\n # Set the justification of the legend box\n # First value is xjust, second value is yjust\n just <- valid.just(calc_element(\"legend.justification\", theme))\n xjust <- just[1L]\n yjust <- just[2L]\n guides <- editGrob(guides,\n vp = viewport(x = xjust, y = yjust, just = c(xjust, yjust))\n )\n guides <- gtable_add_rows(guides, unit(yjust, \"null\"))\n guides <- gtable_add_rows(guides, unit(1L - yjust, \"null\"), 0L)\n guides <- gtable_add_cols(guides, unit(xjust, \"null\"), 0L)\n guides <- gtable_add_cols(guides, unit(1L - xjust, \"null\"))\n guides\n}\n\n#' @importFrom gtable gtable_width gtable_height gtable gtable_add_grob\n#' @importFrom grid editGrob heightDetails widthDetails valid.just unit.c unit\n#' @importFrom ggplot2 margin element_grob element_blank calc_element element_render\nguides_build <- function(guides, theme) {\n legend.spacing.y <- .subset2(theme, \"legend.spacing.y\")\n legend.spacing.x <- .subset2(theme, \"legend.spacing.x\")\n legend.box.margin <- calc_element(\"legend.box.margin\", theme) %||%\n margin()\n widths <- do.call(`unit.c`, lapply(guides, gtable_width))\n heights <- do.call(`unit.c`, lapply(guides, gtable_height))\n\n just <- valid.just(.subset2(theme, \"legend.box.just\"))\n xjust <- just[1]\n yjust <- just[2]\n vert <- identical(.subset2(theme, \"legend.box\"), \"horizontal\")\n guides <- lapply(guides, function(g) {\n editGrob(g, vp = viewport(\n x = xjust, y = yjust, just = c(xjust, yjust),\n height = if (vert) heightDetails(g) else 1,\n width = if (!vert) widthDetails(g) else 1\n ))\n })\n guide_ind <- seq(by = 2, length.out = length(guides))\n sep_ind <- seq(2, by = 2, length.out = length(guides) - 1)\n if (vert) {\n heights <- max(heights)\n if (length(widths) != 1) {\n w <- unit(rep_len(0, length(widths) * 2 - 1), \"mm\")\n w[guide_ind] <- widths\n w[sep_ind] <- legend.spacing.x\n widths <- w\n }\n } else {\n widths <- max(widths)\n if (length(heights) != 1) {\n h <- unit(rep_len(0, length(heights) * 2 - 1), \"mm\")\n h[guide_ind] <- heights\n h[sep_ind] <- legend.spacing.y\n heights <- h\n }\n }\n widths <- unit.c(legend.box.margin[4], widths, legend.box.margin[2])\n heights <- unit.c(legend.box.margin[1], heights, legend.box.margin[3])\n guides <- gtable_add_grob(\n gtable(widths, heights, name = \"guide-box\"),\n guides,\n t = 1 + if (!vert) guide_ind else 1,\n l = 1 + if (vert) guide_ind else 1,\n name = \"guides\"\n )\n gtable_add_grob(\n guides,\n element_render(theme, \"legend.box.background\"),\n t = 1, l = 1, b = -1, r = -1,\n z = -Inf, clip = \"off\", name = \"legend.box.background\"\n )\n}\n\n#' @importFrom ggplot2 calc_element\ncomplete_guide_theme <- function(guide_pos, theme) {\n if (guide_pos %in% c(\"top\", \"bottom\")) {\n theme$legend.box <- calc_element(\"legend.box\", theme) %||% \"horizontal\"\n theme$legend.direction <- calc_element(\"legend.direction\", theme) %||%\n \"horizontal\"\n theme$legend.box.just <- calc_element(\"legend.box.just\", theme) %||%\n c(\"center\", \"top\")\n } else {\n theme$legend.box <- calc_element(\"legend.box\", theme) %||% \"vertical\"\n theme$legend.direction <- calc_element(\"legend.direction\", theme) %||%\n \"vertical\"\n theme$legend.box.just <- calc_element(\"legend.box.just\", theme) %||%\n c(\"left\", \"top\")\n }\n theme\n}\n# nocov end\n\n################################################################ 3\n# Copied from patchwork\ncollapse_guides <- function(guides) {\n unnamed <- lapply(guides, unname_grob)\n for (i in rev(seq_along(unnamed)[-1])) {\n for (j in seq_len(i - 1)) {\n if (isTRUE(all.equal(unnamed[[i]], unnamed[[j]],\n check.names = FALSE, check.attributes = FALSE\n ))) {\n guides[i] <- NULL\n break\n }\n }\n }\n guides\n}\n\n#' @importFrom grid is.unit absolute.size\nunname_vp <- function(x) {\n if (inherits(x, \"vpTree\")) {\n x$parent <- unname_vp(x$parent)\n x$children <- lapply(x$children, unname_vp)\n } else if (inherits(x, \"viewport\")) {\n x$name <- \"\"\n if (!is.null(x$layout$widths)) {\n x$layout$widths <- absolute.size(x$layout$widths)\n }\n if (!is.null(x$layout$heights)) {\n x$layout$heights <- absolute.size(x$layout$heights)\n }\n }\n unit_elements <- vapply(x, is.unit, logical(1), USE.NAMES = FALSE)\n x[unit_elements] <- lapply(.subset(x, unit_elements), absolute.size)\n x\n}\n\n#' @importFrom grid is.grob is.unit absolute.size\n#' @importFrom gtable is.gtable\nunname_grob <- function(x) {\n if (is.gtable(x)) {\n x$name <- \"\"\n x$rownames <- NULL\n x$vp <- unname_vp(x$vp)\n names(x$grobs) <- NULL\n x$grobs <- lapply(x$grobs, unname_grob)\n } else if (is.grob(x)) {\n x$name <- \"\"\n x$vp <- unname_vp(x$vp)\n x$children <- unname(lapply(x$children, unname_grob))\n x$childrenOrder <- rep_len(\"\", length(x$childrenOrder))\n }\n unit_elements <- vapply(x, is.unit, logical(1), USE.NAMES = FALSE)\n x[unit_elements] <- lapply(.subset(x, unit_elements), absolute.size)\n x\n}\n"], ["/ggalign/R/utils.R", "# `vec_rep`\nrecycle_whole <- function(x, len) {\n out <- x %% len\n if (out == 0L) len else out\n}\n\n# `vec_rep_each`\nrecycle_each <- function(x, len) {\n (x - 1L) %/% len + 1L\n}\n\n#' @importFrom utils modifyList\nupdate_non_waive <- function(old, new, keep_null = TRUE) {\n modifyList(old,\n new[!vapply(new, is.waive, logical(1L), USE.NAMES = FALSE)],\n keep.null = keep_null\n )\n}\n\nis_s3 <- function(x) is.object(x) && !isS4(x) && !inherits(x, \"R6\")\n\n#' @importFrom rlang names2\nnames_or_index <- function(x) {\n nms <- names2(x)\n empty <- nms == \"\"\n nms[empty] <- seq_along(x)[empty]\n nms\n}\n\n#################################################################\n#' Read Example Data\n#'\n#' This function reads example data from the file. If no file is specified, it\n#' returns a list of available example files.\n#'\n#' @param file A string representing the name of the example file to be read. If\n#' `NULL`, the function will return a list of available example file names.\n#' @return If `file` is `NULL`, returns a character vector of available example\n#' file names. Otherwise, returns the contents of the specified example file,\n#' read as an R object.\n#' @examples\n#' read_example()\n#' @export\nread_example <- function(file = NULL) {\n if (is.null(file)) {\n dir(pkg_extdata())\n } else {\n readRDS(pkg_extdata(file, mustWork = TRUE))\n }\n}\n\nwith_options <- function(code, ...) {\n opts <- options(...)\n on.exit(options(opts))\n force(code)\n}\n\n#' @param ans Whether to assign the final results into the 'ans' variable.\n#' @noRd\nfn_body_append <- function(fn, ..., ans = FALSE) {\n args <- rlang::fn_fmls(fn)\n body <- rlang::fn_body(fn)\n body <- as.list(body)\n if (ans) body[[length(body)]] <- rlang::expr(ans <- !!body[[length(body)]])\n body <- as.call(c(body, rlang::enexprs(...)))\n rlang::new_function(args, body)\n}\n\n# This will work with most things but be aware that it might fail with some\n# complex objects. For example, according to `?S3Methods`, calling foo on\n# matrix(1:4, 2, 2) would try `foo.matrix`, then `foo.numeric`, then\n# `foo.default`; whereas this code will just look for `foo.matrix` and\n# `foo.default`.\n#' @importFrom utils getS3method\n#' @importFrom methods extends\nhas_method <- function(x, f, inherit = TRUE, default = inherit) {\n x_class <- class(x)\n if (inherit) {\n if (isS4(x)) x_class <- extends(x_class)\n if (default) x_class <- c(x_class, \"default\")\n } else {\n x_class <- .subset(x_class, 1L)\n }\n for (cls in x_class) {\n if (!is.null(getS3method(f, cls, optional = TRUE))) {\n return(TRUE)\n }\n }\n return(FALSE)\n}\n\n#' For functions with a `call` argument, we check if the call originates from\n#' the current package. If it does, we use the caller's call; if not, we use the\n#' current call directly. Used by `align()` and `free()`\n#' @noRd\n#' @importFrom utils packageName\noverride_call <- function(call = NULL) {\n # if no caller call\n if (is.null(call) || is.function(f <- .subset2(call, 1L))) {\n return(TRUE)\n }\n # if call from the current package\n !identical(\n packageName(environment(eval(f))),\n pkg_nm()\n )\n}\n\n# library(data.table)\n# library(vctrs)\n# `%nest_unique%` <- function(x, y) {\n# ans <- new_data_frame(list(x = x, y = y))\n# ans <- unique(ans)\n# !anyDuplicated(ans$x)\n# }\n# `%nest_vctrs%` <- function(x, y) {\n# ans <- new_data_frame(list(x = x, y = y))\n# ans <- vec_unique(ans)\n# !vec_duplicate_any(.subset2(ans, \"x\"))\n# }\n# `%nest_vctrs_loc%` <- function(x, y) {\n# # we don't check the inputs for performance\n# loc <- vec_unique_loc(new_data_frame(list(x = x, y = y)))\n# !vec_duplicate_any(vec_slice(x, loc))\n# }\n# `%nest_data_table%` <- function(x, y) {\n# ans <- data.table(x = x, y = y)\n# ans <- unique(ans)\n# !anyDuplicated(.subset2(ans, \"x\"))\n# }\n# `%nest_split%` <- function(x, y) {\n# all(lengths(lapply(split(y, x), unique)) == 1L)\n# }\n# `%nest_table%` <- function(x, y) {\n# all(rowSums(table(x, y) > 0L) == 1L)\n# }\n# foo <- rep(seq(10^4L / 2L), each = 4)\n# bar <- rep(seq(10^4L), each = 2)\n# bench::mark(\n# nest_unique = bar %nest_unique% foo,\n# nest_vctrs = bar %nest_vctrs% foo,\n# nest_vctrs_loc = bar %nest_vctrs_loc% foo,\n# nest_data_table = bar %nest_data_table% foo,\n# nest_split = bar %nest_split% foo,\n# nest_table = bar %nest_table% foo,\n# )\n#> Warning: Some expressions had a GC in every iteration; so filtering is\n#> disabled.\n#> # A tibble: 6 x 6\n#> expression min median `itr/sec` mem_alloc `gc/sec`\n#> \n#> 1 nest_unique 5.37ms 7.49ms 134. 1.33MB 69.2\n#> 2 nest_vctrs 200.3us 214.57us 3591. 754.7KB 6.00\n#> 3 nest_vctrs_loc 193.99us 207.29us 4490. 706.95KB 6.00\n#> 4 nest_data_table 402.71us 459.55us 1918. 985.25KB 4.00\n#> 5 nest_split 11.87ms 14.08ms 69.8 1.15MB 54.3\n#> 6 nest_table 183.52ms 189.87ms 5.20 576.35MB 8.67\n`%nest%` <- function(x, y) {\n # we don't check the inputs for performance\n loc <- vec_unique_loc(new_data_frame(list(x = x, y = y)))\n !vec_duplicate_any(vec_slice(x, loc))\n}\n\nsave_png <- function(code, width = 400L, height = 400L) {\n path <- tempfile(fileext = \".png\")\n grDevices::png(path, width = width, height = height)\n on.exit(grDevices::dev.off())\n print(code)\n path\n}\n\nadd_class <- function(x, ...) {\n if (is.null(x)) return(x) # styler: off\n class(x) <- vec_unique(c(..., class(x)))\n x\n}\n\nremove_class <- function(x, ...) {\n oldClass(x) <- vec_set_difference(oldClass(x), c(...))\n x\n}\n\n###########################################################\nswitch_position <- function(position, x, y) {\n switch(position,\n top = ,\n bottom = x,\n left = ,\n right = y\n )\n}\n\nto_direction <- function(position) {\n switch_position(position, \"vertical\", \"horizontal\")\n}\n\nis_vertical <- function(direction) direction == \"vertical\"\n\nis_horizontal <- function(direction) direction == \"horizontal\"\n\nswitch_direction <- function(direction, h, v) {\n if (is_horizontal(direction)) {\n h\n } else {\n v\n }\n}\n\nto_coord_axis <- function(direction) {\n switch_direction(direction, \"y\", \"x\")\n}\n\nto_matrix_axis <- function(direction) {\n switch_direction(direction, \"row\", \"column\")\n}\n\n##########################################################\ndata_frame0 <- function(...) data_frame(..., .name_repair = \"minimal\")\n\nas_data_frame0 <- function(data, ...) {\n as.data.frame(\n x = data, ...,\n make.names = FALSE,\n stringsAsFactors = FALSE,\n fix.empty.names = FALSE\n )\n}\n\nquickdf <- function(x) {\n class(x) <- \"data.frame\"\n attr(x, \"row.names\") <- .set_row_names(length(.subset2(x, 1L)))\n x\n}\n\nfct_rev <- function(x) {\n ans <- as.factor(x)\n factor(ans, levels = rev(levels(ans)))\n}\n\nreverse_trans <- function(x) sum(range(x, na.rm = TRUE)) - x\n\nfclass <- function(x) .subset(class(x), 1L)\n\nis_scalar <- function(x) length(x) == 1L\n\nis_scalar_numeric <- function(x) length(x) == 1L && is.numeric(x)\n"], ["/ggalign/R/layout-chain-operator.R", "#' @keywords internal\nchain_layout_subtract <- function(object, layout, object_name) {\n UseMethod(\"chain_layout_subtract\")\n}\n\n#' @export\nchain_layout_subtract.default <- function(object, layout, object_name) {\n if (is.null(active_index <- layout@active) ||\n is_craftbox(plot <- .subset2(layout@plot_list, active_index))) {\n layout@plot_list <- lapply(layout@plot_list, function(plot) {\n if (is_craftbox(plot)) {\n chain_plot_add(plot, object, object_name, force = FALSE)\n } else {\n plot\n }\n })\n } else {\n layout@plot_list[[active_index]] <- quad_layout_subtract(\n object, plot, object_name\n )\n }\n layout\n}\n\n# for objects can inherit from layout\n#' @export\nchain_layout_subtract.ggalign_scheme <- function(object, layout, object_name) {\n if (is.null(active_index <- layout@active) ||\n is_craftbox(plot <- .subset2(layout@plot_list, active_index))) {\n layout <- update_layout_scheme(object, layout, object_name)\n } else {\n layout@plot_list[[active_index]] <- quad_layout_subtract(\n object, plot, object_name\n )\n }\n layout\n}\n\n#' @export\nchain_layout_subtract.ggalign_with_quad <- function(object, layout,\n object_name) {\n if (!is_stack_layout(layout)) {\n cli_abort(sprintf(\n \"Cannot add {.var {object_name}} to %s\",\n object_name(layout)\n ))\n }\n if (is.null(active_index <- layout@active) ||\n is_craftbox(plot <- .subset2(layout@plot_list, active_index))) {\n inner <- .subset2(object, \"object\")\n inner_name <- .subset2(object, \"object_name\")\n\n # subtract set at layout level, if it is a plot option\n # we only apply to current active layout\n if (inherits(inner, \"ggalign_scheme\")) {\n layout <- update_layout_scheme(inner, layout, inner_name)\n return(layout)\n }\n\n # otherwise, we apply the object to all plots in the stack layout\n direction <- layout@direction\n layout@plot_list <- lapply(layout@plot_list, function(plot) {\n if (is_craftbox(plot)) {\n plot <- chain_plot_add(plot, inner, inner_name, force = FALSE)\n } else if (is.waive(.subset2(object, \"position\"))) {\n # default behaviour for object wrap with `with_quad()`\n # we add the object along the stack layout\n # if means for horizontal stack, we'll add it\n # to the left and right annotation, and the main plot\n positions <- switch_direction(\n direction,\n c(\"left\", \"right\"),\n c(\"top\", \"bottom\")\n )\n for (position in positions) {\n if (!is.null(slot(plot, position))) {\n slot(plot, position) <- chain_layout_subtract(\n inner, slot(plot, position), inner_name\n )\n }\n }\n if (is.null(main <- .subset2(object, \"main\")) || main) {\n plot <- quad_body_add(inner, plot, inner_name)\n }\n } else {\n # we respect the context setting\n plot <- quad_layout_subtract(object, plot, object_name)\n }\n plot\n })\n } else {\n layout@plot_list[[active_index]] <- quad_layout_subtract(\n object, plot, object_name\n )\n }\n layout\n}\n\n##################################################################\n#' @keywords internal\nchain_layout_and_add <- function(object, layout, object_name) {\n UseMethod(\"chain_layout_and_add\")\n}\n\n#' @export\nchain_layout_and_add.ggalign_with_quad <- function(object, layout, object_name) {\n if (!is_stack_layout(layout)) {\n cli_abort(sprintf(\n \"Cannot add {.var {object_name}} to %s\",\n object_name(layout)\n ))\n }\n object <- .subset2(object, \"object\")\n object_name <- .subset2(object, \"object_name\")\n NextMethod()\n}\n\n#' @export\nchain_layout_and_add.default <- function(object, layout, object_name) {\n layout@plot_list <- lapply(layout@plot_list, function(plot) {\n if (is_craftbox(plot)) {\n plot <- chain_plot_add(plot, object, object_name, force = FALSE)\n } else {\n plot <- quad_layout_and_add(object, plot, object_name)\n }\n plot\n })\n layout\n}\n\n#' @export\nchain_layout_and_add.theme <- function(object, layout, object_name) {\n ans <- NextMethod()\n # to align with `patchwork`, we also modify the layout theme\n # when using `&` to add the theme object.\n ans@theme <- ggfun(\"add_theme\")(ans@theme, object)\n ans\n}\n"], ["/ggalign/R/scheme-data.R", "#' Plot data Specifications\n#'\n#' @description\n#' `r lifecycle::badge('experimental')`\n#'\n#' Transforms the plot data. Many functions in this package require a specific\n#' data format to align observations, `scheme_data()` helps reformat data frames\n#' as needed.\n#'\n#' @param data A function to transform the plot data before rendering.\n#' Acceptable values include:\n#'\n#' - `NULL`: No action taken.\n#' - [`waiver()`][ggplot2::waiver()]: Inherits from the parent layout.\n#' - A `function` or purrr-style `formula`: Used to transform the plot data,\n#' which should accept a data frame and return a data frame. You can apply\n#' this after the parent layout `scheme_data` function, using the `inherit`\n#' argument.\n#'\n#' Use this hook to modify the data for all `geoms` after the layout is created\n#' (for matrix data, it has been melted to a long format data frame) but before\n#' rendering by `ggplot2`. The returned data must be a data frame for ggplot.\n#'\n#' @param inherit A single boolean value indicates whether to apply the parent\n#' `scheme_data` first and then apply the specified `scheme_data` for the plot.\n#' Defaults to `FALSE`.\n#'\n#' @details\n#' Defaults will attempt to inherit from the parent layout if the actual data is\n#' inherited from the parent layout, with one exception: `align_dendro()`, which\n#' will not inherit the `scheme_data` by default.\n#'\n#' @export\nscheme_data <- function(data, inherit = FALSE) {\n data <- check_scheme_data(data)\n assert_bool(inherit)\n new_scheme_data(data, inherit)\n}\n\nnew_scheme_data <- function(data = NULL, inherit = FALSE) {\n new_scheme(\n name = \"scheme_data\",\n list(data = data, inherit = inherit),\n class = \"scheme_data\"\n )\n}\n\n#' @export\ninherit_scheme.scheme_data <- function(scheme, pscheme) {\n if (is.null(o <- .subset2(scheme, \"data\"))) return(scheme) # styler: off\n if (is.waive(o)) return(pscheme) # inherit from parent; styler: off\n if (!is.function(p_function <- .subset2(pscheme, \"data\"))) {\n return(scheme)\n }\n # if both are function, we check if we should call parent first then call\n # itself\n if (.subset2(scheme, \"inherit\")) {\n user_scheme_data <- o # current action data function\n scheme$data <- function(data) {\n # we always restore the attached attribute\n ans <- ggalign_data_restore(p_function(data), data)\n user_scheme_data(ans)\n }\n }\n scheme\n}\n\n#' @export\nplot_add_scheme.scheme_data <- function(plot, scheme) {\n # by default, we won't change the data\n if (!is.null(scheme_data <- .subset2(scheme, \"data\") %|w|% NULL) &&\n !is.null(raw_data <- plot$data)) {\n # To be compatible with ggplot2, it must be a data frame\n if (!is.null(data <- scheme_data(raw_data)) &&\n !is.waive(data) &&\n !is.data.frame(data)) {\n cli_abort(\"{.fn scheme_data} must return a {.cls data.frame}\")\n }\n plot <- gguse_data(plot, data)\n }\n plot\n}\n"], ["/ggalign/R/import-standalone-obj-type.R", "# Standalone file: do not edit by hand\n# Source: https://github.com/Yunuuuu/standalone/blob/HEAD/R/standalone-obj-type.R\n# Generated by: usethis::use_standalone(\"Yunuuuu/standalone\", \"obj-type\")\n# ----------------------------------------------------------------------\n#\n# ---\n# repo: Yunuuuu/standalone\n# file: standalone-obj-type.R\n# last-updated: 2025-04-11\n# license: https://unlicense.org\n# imports: rlang (>= 1.1.0)\n# ---\n#\n# ## Changelog\n# 2025-04-11:\n# - new `allow_what_type`\n#\n# 2024-11-10:\n# - `obj_type_friendly()` gains a `length` argument to control whether to show\n# the length of the vector.\n# - `stop_input_type()` gains a `show_length` argument passed to\n# `obj_type_friendly`.\n#\n# 2024-02-14:\n# - `obj_type_friendly()` now works for S7 objects.\n#\n# 2023-05-01:\n# - `obj_type_friendly()` now only displays the first class of S3 objects.\n#\n# 2023-03-30:\n# - `stop_input_type()` now handles `I()` input literally in `arg`.\n#\n# 2022-10-04:\n# - `obj_type_friendly(value = TRUE)` now shows numeric scalars\n# literally.\n# - `stop_friendly_type()` now takes `show_value`, passed to\n# `obj_type_friendly()` as the `value` argument.\n#\n# 2022-10-03:\n# - Added `allow_na` and `allow_null` arguments.\n# - `NULL` is now backticked.\n# - Better friendly type for infinities and `NaN`.\n#\n# 2022-09-16:\n# - Unprefixed usage of rlang functions with `rlang::` to\n# avoid onLoad issues when called from rlang (#1482).\n#\n# 2022-08-11:\n# - Prefixed usage of rlang functions with `rlang::`.\n#\n# 2022-06-22:\n# - `friendly_type_of()` is now `obj_type_friendly()`.\n# - Added `obj_type_oo()`.\n#\n# 2021-12-20:\n# - Added support for scalar values and empty vectors.\n# - Added `stop_input_type()`\n#\n# 2021-06-30:\n# - Added support for missing arguments.\n#\n# 2021-04-19:\n# - Added support for matrices and arrays (#141).\n# - Added documentation.\n# - Added changelog.\n#\n# nocov start\n# Following codes were modified from `rlang` package\n\n#' @param x The object type which does not conform to `what`. Its\n#' `obj_type_friendly()` is taken and mentioned in the error message.\n#' @param show_value Passed to `value` argument of `obj_type_friendly()`.\n#' @param show_length Passed to `length` argument of `obj_type_friendly()`.\n#' @param ... Arguments passed to [abort()].\n#' @inheritParams args_error_context\n#' @importFrom rlang caller_arg caller_env abort\n#' @noRd\nstop_input_type <- function(x,\n what,\n ...,\n allow_na = FALSE,\n allow_null = FALSE,\n show_value = TRUE,\n show_length = FALSE,\n arg = caller_arg(x),\n call = caller_env()) {\n what <- allow_what_type(\n what,\n allow_na = allow_na,\n allow_null = allow_null\n )\n if (inherits(arg, \"AsIs\")) {\n format_arg <- identity\n } else {\n format_arg <- function(x) sprintf(\"`%s`\", x)\n }\n message <- sprintf(\n \"%s must be %s, not %s.\",\n format_arg(arg), what,\n obj_type_friendly(x, value = show_value, length = show_length)\n )\n abort(message, ..., call = call, arg = arg)\n}\n\n#' @param what The friendly expected type as a string. Can be a\n#' character vector of expected types, in which case the error\n#' message mentions all of them in an \"or\" enumeration.\n#' @noRd\nallow_what_type <- function(what, allow_na = FALSE, allow_null = FALSE) {\n if (allow_na) {\n what <- c(what, \"`NA`\")\n }\n if (allow_null) {\n what <- c(what, \"`NULL`\")\n }\n if (length(what)) {\n what <- .standalone_oxford_comma(what, final = \"or\")\n }\n what\n}\n\n#' Return English-friendly type\n#' @param x Any R object.\n#' @param value Whether to describe the value of `x`. Special values\n#' like `NA` or `\"\"` are always described.\n#' @param length Whether to mention the length of vectors and lists.\n#' @return A string describing the type. Starts with an indefinite\n#' article, e.g. \"an integer vector\".\n#' @importFrom rlang is_missing is_vector\n#' @noRd\nobj_type_friendly <- function(x, value = TRUE, length = FALSE) {\n if (is_missing(x)) {\n return(\"absent\")\n }\n\n if (is.object(x)) {\n if (inherits(x, \"quosure\")) {\n type <- \"quosure\"\n } else {\n type <- class(x)[[1L]]\n }\n return(sprintf(\"a <%s> object\", type))\n }\n\n if (!is_vector(x)) {\n return(.rlang_as_friendly_type(typeof(x)))\n }\n\n n_dim <- length(dim(x))\n\n if (!n_dim) {\n if (!is.list(x) && length(x) == 1) {\n if (is.na(x)) {\n return(switch(typeof(x),\n logical = \"`NA`\",\n integer = \"an integer `NA`\",\n double =\n if (is.nan(x)) {\n \"`NaN`\"\n } else {\n \"a numeric `NA`\"\n },\n complex = \"a complex `NA`\",\n character = \"a character `NA`\",\n .rlang_stop_unexpected_typeof(x)\n ))\n }\n\n show_infinites <- function(x) {\n if (x > 0) {\n \"`Inf`\"\n } else {\n \"`-Inf`\"\n }\n }\n str_encode <- function(x, width = 30, ...) {\n if (nchar(x) > width) {\n x <- substr(x, 1, width - 3)\n x <- paste0(x, \"...\")\n }\n encodeString(x, ...)\n }\n\n if (value) {\n if (is.numeric(x) && is.infinite(x)) {\n return(show_infinites(x))\n }\n\n if (is.numeric(x) || is.complex(x)) {\n number <- as.character(round(x, 2))\n what <- if (is.complex(x)) {\n \"the complex number\"\n } else {\n \"the number\"\n }\n return(paste(what, number))\n }\n\n return(switch(typeof(x),\n logical = if (x) \"`TRUE`\" else \"`FALSE`\",\n character = {\n what <- if (nzchar(x)) {\n \"the string\"\n } else {\n \"the empty string\"\n }\n paste(what, str_encode(x, quote = \"\\\"\"))\n },\n raw = paste(\"the raw value\", as.character(x)),\n .rlang_stop_unexpected_typeof(x)\n ))\n }\n\n return(switch(typeof(x),\n logical = \"a logical value\",\n integer = \"an integer\",\n double = if (is.infinite(x)) show_infinites(x) else \"a number\",\n complex = \"a complex number\",\n character = if (nzchar(x)) \"a string\" else \"\\\"\\\"\",\n raw = \"a raw value\",\n .rlang_stop_unexpected_typeof(x)\n ))\n }\n\n if (length(x) == 0) {\n return(switch(typeof(x),\n logical = \"an empty logical vector\",\n integer = \"an empty integer vector\",\n double = \"an empty numeric vector\",\n complex = \"an empty complex vector\",\n character = \"an empty character vector\",\n raw = \"an empty raw vector\",\n list = \"an empty list\",\n .rlang_stop_unexpected_typeof(x)\n ))\n }\n }\n\n vec_type_friendly(x, length = length)\n}\n\n#' @importFrom rlang is_vector abort\nvec_type_friendly <- function(x, length = FALSE) {\n if (!is_vector(x)) {\n abort(\"`x` must be a vector.\")\n }\n type <- typeof(x)\n n_dim <- length(dim(x))\n\n add_length <- function(type) {\n if (length && !n_dim) {\n paste0(type, sprintf(\" of length %s\", length(x)))\n } else {\n type\n }\n }\n\n if (type == \"list\") {\n if (n_dim < 2) {\n return(add_length(\"a list\"))\n } else if (is.data.frame(x)) {\n return(\"a data frame\")\n } else if (n_dim == 2) {\n return(\"a list matrix\")\n } else {\n return(\"a list array\")\n }\n }\n\n type <- switch(type,\n logical = \"a logical %s\",\n integer = \"an integer %s\",\n numeric = ,\n double = \"a double %s\",\n complex = \"a complex %s\",\n character = \"a character %s\",\n raw = \"a raw %s\",\n type = paste0(\"a \", type, \" %s\")\n )\n\n if (n_dim < 2) {\n kind <- \"vector\"\n } else if (n_dim == 2) {\n kind <- \"matrix\"\n } else {\n kind <- \"array\"\n }\n out <- sprintf(type, kind)\n\n if (n_dim >= 2) {\n out\n } else {\n add_length(out)\n }\n}\n\n.rlang_as_friendly_type <- function(type) {\n switch(type,\n list = \"a list\",\n NULL = \"`NULL`\",\n environment = \"an environment\",\n externalptr = \"a pointer\",\n weakref = \"a weak reference\",\n S4 = \"an S4 object\",\n name = ,\n symbol = \"a symbol\",\n language = \"a call\",\n pairlist = \"a pairlist node\",\n expression = \"an expression vector\",\n char = \"an internal string\",\n promise = \"an internal promise\",\n ... = \"an internal dots object\",\n any = \"an internal `any` object\",\n bytecode = \"an internal bytecode object\",\n primitive = ,\n builtin = ,\n special = \"a primitive function\",\n closure = \"a function\",\n type\n )\n}\n\n#' @importFrom rlang abort caller_env\n.rlang_stop_unexpected_typeof <- function(x, call = caller_env()) {\n abort(sprintf(\"Unexpected type <%s>.\", typeof(x)), call = call)\n}\n\n#' Return OO type\n#' @param x Any R object.\n#' @return One of `\"bare\"` (for non-OO objects), `\"S3\"`, `\"S4\"`,\n#' `\"R6\"`, or `\"S7\"`.\n#' @noRd\nobj_type_oo <- function(x) {\n if (!is.object(x)) {\n return(\"bare\")\n }\n\n class <- inherits(x, c(\"R6\", \"S7_object\"), which = TRUE)\n\n if (class[[1]]) {\n \"R6\"\n } else if (class[[2]]) {\n \"S7\"\n } else if (isS4(x)) {\n \"S4\"\n } else {\n \"S3\"\n }\n}\n\n.standalone_oxford_comma <- function(x, sep = \", \", final = \"and\") {\n n <- length(x)\n\n if (n < 2L) return(x) # styler: off\n\n head <- x[seq_len(n - 1L)]\n last <- x[n]\n\n head <- paste(head, collapse = sep)\n\n # Write a or b. But a, b, or c.\n if (n > 2L) {\n paste0(head, sep, final, \" \", last)\n } else {\n paste0(head, \" \", final, \" \", last)\n }\n}\n\n# nocov end\n"], ["/ggalign/R/alignpatch-title.R", "#' Add patch titles to plot borders\n#'\n#' This function extends ggplot2's title functionality, allowing you to add\n#' titles to each border of the plot: top, left, bottom, and right.\n#'\n#' @details\n#'\n#' The appearance and alignment of these patch titles can be customized using\n#' [theme()][ggplot2::theme]:\n#' - `plot.patch_title`/`plot.patch_title.*`: Controls the text appearance of\n#' patch titles. By default, `plot.patch_title` inherit from `plot.title`, and\n#' settings for each border will inherit from `plot.patch_title`, with the\n#' exception of the `angle` property, which is not inherited.\n#' - `plot.patch_title.position`/`plot.patch_title.position.*`: Determines the\n#' alignment of the patch titles. By default, `plot.patch_title.position`\n#' inherit from `plot.title.position`, and settings for each border will\n#' inherit from `plot.patch_title`. The value `\"panel\"` aligns the patch\n#' titles with the plot panels. Setting this to `\"plot\"` aligns the patch\n#' title with the entire plot (excluding margins and plot tags).\n#'\n#' @param top,left,bottom,right A string specifying the title to be added to the\n#' top, left, bottom, and right border of the plot.\n#' @return A [`labels`][ggplot2::labs] object to be added to ggplot.\n#' @examples\n#' ggplot(mtcars) +\n#' geom_point(aes(mpg, disp)) +\n#' patch_titles(\n#' top = \"I'm top patch title\",\n#' left = \"I'm left patch title\",\n#' bottom = \"I'm bottom patch title\",\n#' right = \"I'm right patch title\"\n#' )\n#' @export\n#' @importFrom ggplot2 waiver\npatch_titles <- function(top = waiver(), left = waiver(), bottom = waiver(),\n right = waiver()) {\n structure(\n list(top = top, left = left, bottom = bottom, right = right),\n class = \"ggalign_patch_labels\"\n )\n}\n\n#' @importFrom ggplot2 find_panel calc_element zeroGrob element_grob merge_element\n#' @importFrom rlang arg_match0\n#' @importFrom grid grobName\nsetup_patch_titles <- function(table, patch_titles, theme) {\n # complete_theme() will ensure `plot_title` exists\n old_text <- calc_element(\"plot.title\", theme)\n # always justification by center for patch title\n old_text$hjust <- 0.5\n if (is.null(text <- .subset2(theme, \"plot.patch_title\"))) {\n text <- old_text\n } else if (inherits(text, \"element_text\")) {\n text <- merge_element(text, old_text)\n } else {\n cli_abort(paste(\n \"Theme element {.var plot.patch_title} must be a\",\n \"{.cls element_text}.\"\n ), call = quote(theme()))\n }\n # inherit from plot.title.position, default use \"panel\"\n position <- .subset2(theme, \"plot.patch_title.position\") %||%\n .subset2(theme, \"plot.title.position\") %||% \"panel\"\n for (border in .TLBR) {\n panel_pos <- find_panel(table)\n patch_title <- .subset2(patch_titles, border)\n name <- paste(\"plot.patch_title\", border, sep = \".\")\n if (is.null(patch_title)) {\n title <- zeroGrob()\n } else {\n # set the default angle\n text$angle <- switch(border,\n top = 0L,\n left = 90L,\n bottom = 0L,\n right = -90L\n )\n # we merge the element with `plot.patch_title`\n if (is.null(el <- .subset2(theme, name))) {\n el <- text\n } else if (inherits(el, \"element_text\")) {\n el <- merge_element(el, text)\n } else {\n cli_abort(paste(\n \"Theme element {.var {name}} must have\",\n \"class {.cls element_text}.\"\n ), call = quote(theme()))\n }\n # render the patch title grob\n title <- element_grob(el, patch_title,\n margin_y = TRUE, margin_x = TRUE\n )\n title$name <- grobName(title, name)\n }\n\n name <- paste(\"plot.patch_title.position\", border, sep = \".\")\n pos <- arg_match0(\n .subset2(theme, name) %||% position,\n c(\"panel\", \"plot\"),\n arg_nm = name,\n error_call = quote(theme())\n )\n if (border == \"top\") {\n height <- grobHeight(title)\n if (pos == \"panel\") {\n l <- panel_pos$l\n r <- panel_pos$r\n } else {\n l <- 1L\n r <- ncol(table)\n }\n h <- .subset2(panel_pos, \"t\") - 4L # above original xlab\n table <- gtable_add_rows(table, height, pos = h)\n table <- gtable_add_grob(table, title,\n name = \"patch-title-top\",\n t = h + 1L, b = h + 1L, l = l, r = r,\n clip = \"off\"\n )\n } else if (border == \"left\") {\n width <- grobWidth(title)\n if (pos == \"panel\") {\n t <- panel_pos$t\n b <- panel_pos$b\n } else {\n t <- 1L\n b <- nrow(table)\n }\n v <- .subset2(panel_pos, \"l\") - 4L # left of the ylab\n table <- gtable_add_cols(table, width, pos = v)\n table <- gtable_add_grob(table, title,\n name = \"patch-title-left\",\n t = t, b = b, l = v + 1L, r = v + 1L,\n clip = \"off\"\n )\n } else if (border == \"bottom\") {\n height <- grobHeight(title)\n if (pos == \"panel\") {\n l <- panel_pos$l\n r <- panel_pos$r\n } else {\n l <- 1L\n r <- ncol(table)\n }\n h <- .subset2(panel_pos, \"b\") + 3L # below original xlab\n table <- gtable_add_rows(table, height, pos = h)\n table <- gtable_add_grob(table, title,\n name = \"patch-title-bottom\",\n t = h + 1L, b = h + 1L, l = l, r = r,\n clip = \"off\"\n )\n } else if (border == \"right\") {\n width <- grobWidth(title)\n if (pos == \"panel\") {\n t <- panel_pos$t\n b <- panel_pos$b\n } else {\n t <- 1L\n b <- nrow(table)\n }\n v <- .subset2(panel_pos, \"r\") + 3L # right of the ylab\n table <- gtable_add_cols(table, width, pos = v)\n table <- gtable_add_grob(table, title,\n name = \"patch-title-right\",\n t = t, b = b, l = v + 1L, r = v + 1L,\n clip = \"off\"\n )\n }\n }\n table\n}\n\n#' @importFrom ggplot2 ggplot_add\n#' @export\nggplot_add.ggalign_patch_labels <- function(object, plot, object_name, ...) {\n plot$ggalign_patch_labels <- update_non_waive(\n plot$ggalign_patch_labels %||% list(), object\n )\n if (!inherits(plot, \"patch_ggplot\")) {\n plot <- add_class(plot, \"patch_ggplot\")\n }\n plot\n}\n"], ["/ggalign/R/alignpatch-free-border.R", "#' @param borders Which border shouldn't be aligned? A string containing one or\n#' more of `r oxford_and(.tlbr)`.\n#' @return\n#' - `free_border`: A modified version of `plot` with a `free_border` class.\n#' @export\n#' @rdname free\nfree_border <- function(plot, borders = \"tlbr\") {\n UseMethod(\"free_border\")\n}\n\n#' @export\nfree_border.ggplot <- function(plot, borders = \"tlbr\") {\n assert_position(borders)\n attr(plot, \"free_borders\") <- borders\n add_class(plot, \"free_border\")\n}\n\n#' @export\nfree_border.alignpatches <- free_border.ggplot\n\n#' @export\nfree_border.free_align <- function(plot, borders = \"tlbr\") {\n assert_position(borders)\n borders <- setdiff_position(borders, attr(plot, \"free_axes\"))\n if (!nzchar(borders)) {\n return(plot)\n }\n NextMethod()\n}\n\n#' @export\nfree_border.free_lab <- function(plot, borders = \"tlbr\") {\n assert_position(borders)\n free_labs <- setdiff_position(attr(plot, \"free_labs\"), borders)\n if (nzchar(free_labs)) {\n attr(plot, \"free_labs\") <- free_labs\n } else {\n attr(plot, \"free_labs\") <- NULL\n plot <- remove_class(plot, \"free_lab\")\n }\n NextMethod()\n}\n\n#' @export\nfree_border.free_border <- function(plot, borders = \"tlbr\") {\n assert_position(borders)\n attr(plot, \"free_borders\") <- union_position(\n attr(plot, \"free_borders\"), borders\n )\n plot\n}\n\n#' @export\nfree_border.default <- function(plot, borders = \"tlbr\") {\n cli_abort(\"Cannot use with {.obj_type_friendly {plot}}\")\n}\n\n################################################################\n#' @importFrom ggplot2 ggproto ggproto_parent\n#' @export\nalignpatch.free_border <- function(x) {\n Parent <- NextMethod()\n ggproto(\n \"PatchFreeBorder\", Parent,\n free_borders = setup_pos(attr(x, \"free_borders\")),\n collect_guides = function(self, guides, gt = self$gt) {\n ans <- ggproto_parent(Parent, self)$collect_guides(\n guides = guides, gt = gt\n )\n self$gt <- ggproto_parent(Parent, self)$free_border(\n borders = self$free_borders, gt = self$gt\n )\n ans\n },\n align_border = function(self, t = NULL, l = NULL, b = NULL, r = NULL,\n gt = self$gt) {\n gt <- ggproto_parent(Parent, self)$align_border(\n t = t, l = l, b = b, r = r, gt = gt\n )\n ggproto_parent(Parent, self)$align_free_border(\n borders = self$free_borders,\n t = t, l = l, b = b, r = r, gt = gt\n )\n },\n free_border = function(self, borders, gt = self$gt) {\n borders <- vec_set_difference(borders, self$free_borders)\n if (length(borders)) {\n gt <- ggproto_parent(Parent, self)$free_border(\n borders = borders, gt = gt\n )\n }\n gt\n },\n align_free_border = function(self, borders,\n t = NULL, l = NULL, b = NULL, r = NULL,\n gt = self$gt) {\n borders <- vec_set_difference(borders, self$free_borders)\n if (length(borders)) {\n gt <- ggproto_parent(Parent, self)$align_free_border(\n borders = borders,\n t = t, l = l, b = b, r = r, gt = gt\n )\n }\n gt\n }\n )\n}\n"], ["/ggalign/R/alignpatch-free-vp.R", "#' @inheritParams grid::viewport\n#' @inheritDotParams grid::viewport -x -y -width -height\n#' @return\n#' - `free_vp`: A modified version of `plot` with a `free_vp` class.\n#' @importFrom grid viewport\n#' @export\n#' @rdname free\nfree_vp <- function(plot, x = 0.5, y = 0.5, width = NA, height = NA, ...) {\n UseMethod(\"free_vp\")\n}\n\n#' @export\nfree_vp.default <- function(plot, x = 0.5, y = 0.5,\n width = NA, height = NA, ...) {\n cli_abort(\"Cannot use with {.obj_type_friendly {plot}}\")\n}\n\n#' @export\nfree_vp.ggplot <- function(plot, x = 0.5, y = 0.5,\n width = NA, height = NA, ...) {\n attr(plot, \"vp\") <- viewport(\n x = x, y = y, width = width, height = height, ...,\n )\n add_class(plot, \"free_vp\")\n}\n\n#' @export\nfree_vp.alignpatches <- free_vp.ggplot\n\n####################################################\n#' @importFrom gtable gtable_width gtable_height\n#' @importFrom ggplot2 ggproto ggproto_parent\n#' @export\nalignpatch.free_vp <- function(x) {\n Parent <- NextMethod()\n ggproto(\n \"PatchFreeViewport\", Parent,\n vp = attr(x, \"vp\"),\n align_border = function(self, t = NULL, l = NULL, b = NULL, r = NULL,\n gt = self$gt) {\n ans <- ggproto_parent(Parent, self)$align_border(\n t = t, l = l, b = b, r = r, gt = gt\n )\n vp <- self$vp\n\n if (!any(is_null_unit(widths <- .subset2(ans, \"widths\")))) {\n horizontal_just <- TRUE\n vp$width <- sum(widths)\n } else if (!is.na(as.numeric(vp$width))) {\n # we guess the width from the gtable\n horizontal_just <- TRUE\n vp$width <- max(vp$width, sum(widths))\n } else {\n vp$width <- unit(1, \"npc\")\n horizontal_just <- FALSE\n }\n if (!any(is_null_unit(heights <- .subset2(ans, \"heights\")))) {\n vertical_just <- TRUE\n vp$height <- sum(heights)\n } else if (!is.na(as.numeric(vp$height))) {\n # we guess the height from the gtable\n vertical_just <- TRUE\n vp$height <- max(vp$height, sum(heights))\n } else {\n vp$height <- unit(1, \"npc\")\n vertical_just <- FALSE\n }\n if (horizontal_just || vertical_just) ans$vp <- vp\n ans\n }\n )\n}\n"], ["/ggalign/R/layout-quad-operator.R", "# `subtract` operates at layout-level\n#' @keywords internal\nquad_layout_subtract <- function(object, quad, object_name) {\n UseMethod(\"quad_layout_subtract\")\n}\n\n#' @export\nquad_layout_subtract.default <- function(object, quad, object_name) {\n if (is.null(context <- quad@active)) context <- c(.TLBR, list(NULL))\n for (active in context) {\n if (is.null(active)) {\n quad <- quad_body_add(object, quad, object_name)\n } else if (!is.null(slot(quad, active))) {\n slot(quad, active) <- chain_layout_subtract(\n object, slot(quad, active), object_name\n )\n }\n }\n quad\n}\n\n# for object can set at layout level\n#' @export\nquad_layout_subtract.ggalign_scheme <- function(object, quad, object_name) {\n if (is.null(context <- quad@active)) {\n quad <- update_layout_scheme(object, quad, object_name)\n } else {\n slot(quad, context) <- update_layout_scheme(\n object, slot(quad, context), object_name\n )\n }\n quad\n}\n\n#' @export\nquad_layout_subtract.ggalign_with_quad <- function(object, quad, object_name) {\n old <- quad@active\n context <- quad_operated_context(object, old, \"-\")\n object <- .subset2(object, \"object\")\n object_name <- .subset2(object, \"object_name\")\n # `subtract` operates at layout-level\n if (is.null(context)) {\n quad@active <- context\n quad <- quad_layout_subtract(object, quad, object_name)\n } else {\n for (active in context) {\n if (is.null(active)) {\n quad <- quad_body_add(object, quad, object_name)\n } else if (!is.null(slot(quad, active))) {\n slot(quad, active) <- chain_layout_subtract(\n object, slot(quad, active), object_name\n )\n }\n }\n }\n quad@active <- old\n quad\n}\n\n###############################################################\n#' @keywords internal\nquad_layout_and_add <- function(object, quad, object_name) {\n UseMethod(\"quad_layout_and_add\")\n}\n\n#' @export\nquad_layout_and_add.default <- function(object, quad, object_name) {\n quad <- quad_body_add(object, quad, object_name)\n for (position in .TLBR) {\n stack <- slot(quad, position)\n if (is.null(stack)) next\n slot(quad, position) <- chain_layout_and_add(\n object, stack, object_name\n )\n }\n quad\n}\n\n#' @export\nquad_layout_and_add.ggalign_with_quad <- function(object, quad, object_name) {\n object <- .subset2(object, \"object\")\n object_name <- .subset2(object, \"object_name\")\n NextMethod()\n}\n\n#' @export\nquad_layout_and_add.theme <- function(object, quad, object_name) {\n ans <- NextMethod()\n # to align with `patchwork`, we also modify the layout theme\n # when using `&` to add the theme object.\n ans@theme <- ggfun(\"add_theme\")(ans@theme, object)\n ans\n}\n"], ["/ggalign/R/attributes.R", "#' Get Data from the Attribute Attached by ggalign\n#'\n#' @description\n#' `ggalign_attr` retrieves supplementary information stored as attributes\n#' during the layout rendering process. These attributes—typically added during\n#' data transformation by functions such as [`fortify_matrix()`] or\n#' [`fortify_data_frame()`]—may contain filtered data, auxiliary metadata, or\n#' other context essential for downstream operations.\n#'\n#' Factor level information, stored as a separate attribute, can be accessed via\n#' `ggalign_lvls`.\n#'\n#' @details\n#' Attributes attached to the data are especially useful when the input data is\n#' transformed in ways that limit access to the complete dataset. For example,\n#' [`fortify_matrix.MAF()`] might filter mutation data while adding attributes\n#' that retain important context, such as the total number of observations, for\n#' detailed or aggregated analyses. Additionally, it stores the levels of\n#' `Variant_Classification` for further usage.\n#'\n#' @param x Data used, typically inherited from the layout `r rd_layout()`.\n#' @param field A string specifying the particular data to retrieve from the\n#' attached attribute. If `NULL`, the entire attached attribute list will be\n#' returned.\n#' @param check A boolean indicating whether to check if the `field` exists. If\n#' `TRUE`, an error will be raised if the specified `field` does not exist.\n#' @return\n#' - `ggalign_attr`: The specified data from the attached supplementary data or\n#' `NULL` if it is unavailable.\n#' - `ggalign_lvls`: The attached supplementary levels or `NULL` if it is\n#' unavailable.\n#'\n#' @export\nggalign_attr <- function(x, field = NULL, check = TRUE) {\n assert_string(field, allow_empty = FALSE, allow_null = TRUE)\n if (is.null(x <- ggalign_attr_get(x)) || is.null(field)) {\n return(x)\n }\n if (isTRUE(check) && !rlang::has_name(x, field)) {\n cli_abort(\"Cannot find {field} in {.arg x}\")\n }\n .subset2(x, field)\n}\n\n#' @export\n#' @rdname ggalign_attr\nggalign_lvls <- function(x) ggalign_lvls_get(x)\n\n#' Attach supplementary data and levels for ggalign\n#'\n#' @param .data Input data for the layout.\n#' @param ... <[dyn-dots][rlang::dyn-dots]> A list of data to be attached.\n#' @param .lvls A character vector representing the attached levels.\n#' @note Used by developers in [`fortify_matrix()`], [`fortify_data_frame()`],\n#' and other related methods.\n#' @seealso [`ggalign_attr()`]/[`ggalign_lvls()`]\n#' @importFrom rlang list2\n#' @export\nggalign_data_set <- function(.data, ..., .lvls = NULL) {\n if (...length() > 0L) {\n .data <- ggalign_attr_set(.data, list2(...))\n }\n if (!is.null(.lvls)) {\n .data <- ggalign_lvls_set(.data, .lvls)\n }\n # to prevent the print of attributes\n if (!is.null(ggalign_attr_get(.data)) ||\n !is.null(ggalign_lvls_get(.data))) {\n .data <- add_class(.data, \"ggalign_data\")\n }\n .data\n}\n\n#' @export\nprint.ggalign_data <- function(x, ...) {\n print(\n remove_class(\n ggalign_lvls_remove(ggalign_attr_remove(x)),\n \"ggalign_data\"\n )\n )\n invisible(x)\n}\n\nggalign_attr_set <- function(x, values) {\n attr(x, \".__ggalign_attr__\") <- values\n x\n}\n\nggalign_attr_get <- function(x) attr(x, \".__ggalign_attr__\", exact = TRUE)\n\nggalign_attr_remove <- function(x) ggalign_attr_set(x, NULL)\n\nggalign_lvls_set <- function(x, lvls) {\n attr(x, \".__ggalign_levels__\") <- lvls\n x\n}\n\nggalign_lvls_get <- function(x) attr(x, \".__ggalign_levels__\", exact = TRUE)\n\nggalign_lvls_remove <- function(x) ggalign_lvls_set(x, NULL)\n\n# we keep a special attribute across all data\n# this is used to pass additional annotation informations\nggalign_data_restore <- function(data, original) {\n if (is.null(data) || is.waive(data)) return(data) # styler: off\n if (is.null(ggalign_attr_get(data)) && # no attached attribute\n # the original has attached attribute\n !is.null(value <- ggalign_attr_get(original))) {\n data <- ggalign_attr_set(data, value)\n }\n\n if (is.null(ggalign_lvls_get(data)) && # no attached levels\n # the original has attached levels\n !is.null(value <- ggalign_lvls_get(original))) {\n data <- ggalign_lvls_set(data, value)\n }\n # to prevent the print of attributes\n if (!is.null(ggalign_attr_get(data)) ||\n !is.null(ggalign_lvls_get(data))) {\n data <- add_class(data, \"ggalign_data\")\n }\n data\n}\n"], ["/ggalign/R/ggplot-utils.R", "#' @importFrom ggplot2 .pt\nggfun <- function(fn, mode = \"any\") from_namespace(\"ggplot2\", fn, mode = mode)\n\nallow_lambda <- function(x) {\n if (rlang::is_formula(x)) rlang::as_function(x) else x\n}\n\nis.waive <- function(x) inherits(x, \"waiver\")\n\n`%|w|%` <- function(x, y) if (inherits(x, \"waiver\")) y else x\n\nsnake_class <- function(x) ggfun(\"snake_class\")(x)\n\nggadd_default <- function(plot, mapping = NULL, theme = NULL) {\n if (!is.null(mapping)) {\n plot <- plot + mapping + plot$mapping\n }\n if (!is.null(theme)) plot$theme <- theme + plot$theme\n plot\n}\n\nis_palette_unset <- function(type, aes) {\n type <- match.arg(type, c(\"discrete\", \"continuous\", \"binned\"))\n aes <- match.arg(aes, c(\"fill\", \"colour\"))\n is.null(getOption(sprintf(\"ggplot2.%s.%s\", type, aes)))\n}\n\n# A guide-box should be a `zeroGrob()` or a `gtable` object\n#' @importFrom gtable is.gtable\nmaybe_guide_box <- function(x) inherits(x, \"zeroGrob\") || is.gtable(x)\n\n######################################################\ngguse_data <- function(plot, data) {\n # ggplot use waiver() to indicate no data\n plot[\"data\"] <- list(data %||% waiver())\n plot\n}\n\nggremove_margin <- function(plot, direction) {\n if (!is.null(direction) && packageVersion(\"ggplot2\") > \"3.5.2\") {\n plot <- plot + switch_direction(\n direction,\n theme(plot.margin = margin(t = 0, r = NA, b = 0, l = NA)),\n theme(plot.margin = margin(t = NA, r = 0, b = NA, l = 0))\n )\n }\n plot\n}\n\n######################################################\ndefault_expansion <- function(x = NULL, y = NULL) {\n structure(list(x = x, y = y), class = c(\"ggalign_default_expansion\"))\n}\n\n#' @importFrom ggplot2 ggplot_add ggproto ggproto_parent\n#' @export\nggplot_add.ggalign_default_expansion <- function(object, plot, object_name,\n ...) {\n if (is.null(.subset2(object, \"x\")) && is.null(.subset2(object, \"y\"))) {\n return(plot)\n }\n ParentFacet <- plot$facet\n plot$facet <- ggproto(\n NULL,\n ParentFacet,\n init_scales = function(self, layout, x_scale = NULL, y_scale = NULL,\n params) {\n if (!is.null(x_scale) && !is.null(.subset2(object, \"x\"))) {\n x_scale$expand <- x_scale$expand %|w|% .subset2(object, \"x\")\n }\n if (!is.null(y_scale) && !is.null(.subset2(object, \"y\"))) {\n y_scale$expand <- y_scale$expand %|w|% .subset2(object, \"y\")\n }\n ggproto_parent(ParentFacet, self)$init_scales(\n layout = layout,\n x_scale = x_scale,\n y_scale = y_scale,\n params = params\n )\n }\n )\n plot\n}\n\n######################################################\nreverse_continuous_axis <- function(plot, axis) {\n if (plot$scales$has_scale(axis)) {\n # modify scale in place\n scale <- plot$scales$get_scales(axis)\n if (!scale$is_discrete()) {\n if (identical(scale$trans$name, \"identity\")) {\n scale$trans <- scales::as.transform(\"reverse\")\n } else if (identical(scale$trans$name, \"reverse\")) {\n scale$trans <- scales::as.transform(\"identity\")\n }\n }\n } else {\n plot <- plot +\n switch(axis,\n x = ggplot2::scale_x_reverse(),\n y = ggplot2::scale_y_reverse()\n )\n }\n plot\n}\n"], ["/ggalign/R/import-standalone-pkg.R", "# Standalone file: do not edit by hand\n# Source: https://github.com/Yunuuuu/standalone/blob/HEAD/R/standalone-pkg.R\n# Generated by: usethis::use_standalone(\"Yunuuuu/standalone\", \"pkg\")\n# ----------------------------------------------------------------------\n#\n# ---\n# repo: Yunuuuu/standalone\n# file: standalone-pkg.R\n# last-updated: 2025-04-10\n# license: https://unlicense.org\n# imports: [utils]\n# ---\n\n# This file contains various helper utilities, including common functions\n# used across multiple packages I have developed. Some functions depend on\n# other packages that are not listed in Imports, so use them with caution.\n\n# ## Changelog\n# 2025-04-10\n# - simplify `from_namespace`\n#\n# 2025-03-30\n# - Add `use_github_release`\n#\n# 2025-03-12\n# - Add `from_namespace`\n#\n# 2025-03-10:\n# - Add `on_exit`\n#\n# 2025-03-08:\n# - Add `pkg_extdata`\n# - Add `defer`\n#\n# 2025-03-04:\n# - Add `%||%`\n#\n# 2025-03-03:\n# - Add `rd_collect_family`\n# - Add `oxford_and`\n# - Add `oxford_or`\n# - Add `code_quote`\n# - Add `oxford_comma`\n#\n# 2025-02-26:\n# - Add `is_installed`\n# - Add `install_pkgs`\n# - Add `pkg_nm`\n# - Add `pkg_namespace`\n#\n# nocov start\n\n`%||%` <- function(x, y) if (is.null(x)) y else x\n\nis_installed <- local({\n cache <- new.env(parent = emptyenv())\n function(pkg, version = NULL) {\n id <- if (is.null(version)) pkg else paste(pkg, version, sep = \":\")\n out <- cache[[id]]\n if (is.null(out)) {\n if (is.null(version)) {\n out <- requireNamespace(pkg, quietly = TRUE)\n } else {\n out <- requireNamespace(pkg, quietly = TRUE) &&\n utils::packageVersion(pkg) >= version\n }\n assign(id, out, envir = cache, inherits = FALSE)\n }\n out\n }\n})\n\ninstall_pkgs <- function(pkgs) {\n if (is_installed(\"pak\")) {\n getExportedValue(\"pak\", \"pkg_install\")(pkgs, ask = FALSE)\n } else {\n utils::install.packages(pkgs)\n }\n}\n\npkg_nm <- function() utils::packageName(environment())\n\npkg_namespace <- function() topenv(environment())\n\npkg_extdata <- function(..., mustWork = TRUE) {\n system.file(\"extdata\", ..., package = pkg_nm(), mustWork = mustWork)\n}\n\n############################################################\n# I’m having trouble connecting to GitHub, and it seems that `gert` does not\n# respect the proxy settings in my Git config. To work around this, I modified\n# `usethis::use_github_release()` to skip the check that relies on the `gert`\n# package.\nuse_github_release <- function(publish = TRUE) {\n usethis_ns <- getNamespace(\"usethis\")\n usethis <- function(fun, ...) {\n get(x = fun, envir = usethis_ns, inherits = FALSE, ...)\n }\n usethis(\"check_is_package\")(\"use_github_release()\")\n tr <- usethis(\"target_repo\")(\n github_get = TRUE,\n ok_configs = c(\"ours\", \"fork\")\n )\n usethis(\"check_can_push\")(tr = tr, \"to create a release\")\n dat <- usethis(\"get_release_data\")(tr)\n release_name <- paste(dat$Package, dat$Version)\n tag_name <- sprintf(\"v%s\", dat$Version)\n usethis(\"kv_line\")(\"Release name\", release_name)\n usethis(\"kv_line\")(\"Tag name\", tag_name)\n usethis(\"kv_line\")(\"SHA\", dat$SHA)\n usethis(\"check_github_has_SHA\")(SHA = dat$SHA, tr = tr)\n on_cran <- !is.null(usethis(\"cran_version\")())\n news <- usethis(\"get_release_news\")(\n SHA = dat$SHA, tr = tr, on_cran = on_cran\n )\n gh <- usethis(\"gh_tr\")(tr)\n usethis(\"ui_bullets\")(\"Publishing {tag_name} release to GitHub\")\n release <- gh( # nolint\n \"POST /repos/{owner}/{repo}/releases\",\n name = release_name,\n tag_name = tag_name,\n target_commitish = dat$SHA,\n body = news,\n draft = !publish\n )\n usethis(\"ui_bullets\")(\"Release at {.url {release$html_url}}\")\n if (!is.null(dat$file)) {\n usethis(\"ui_bullets\")(\"Deleting {.path {dat$file}}\")\n getExportedValue(\"fs\", \"file_delete\")(dat$file)\n }\n invisible()\n}\n\n############################################################\nfrom_namespace <- local({\n namespace <- NULL\n function(package, name, mode = \"any\") {\n if (is.null(namespace)) namespace <<- getNamespace(package)\n get(x = name, envir = namespace, inherits = FALSE, mode = mode)\n }\n})\n\n# Need `rlang` package, can support `quosure`\non_exit <- function(expr, envir = parent.frame(), after = TRUE, add = TRUE) {\n expr <- getExportedValue(\"rlang\", \"enquo\")(expr)\n defer(\n getExportedValue(\"rlang\", \"eval_tidy\")(expr),\n envir = envir,\n after = after,\n add\n )\n}\n\n# Just like `withr::defer()`, don't depend on `rlang` package\ndefer <- function(expr, envir = parent.frame(), after = TRUE, add = TRUE) {\n thunk <- as.call(list(function() expr))\n do.call(base::on.exit, list(thunk, add = add, after = after), envir = envir)\n}\n\n# utils function to collapse characters ---------------------------\noxford_and <- function(x, code = TRUE, quote = TRUE, sep = \", \") {\n oxford_comma(code_quote(x, code, quote), sep = sep, final = \"and\")\n}\n\noxford_or <- function(x, code = TRUE, quote = TRUE, sep = \", \") {\n oxford_comma(code_quote(x, code, quote), sep = sep, final = \"or\")\n}\n\ncode_quote <- function(x, code = TRUE, quote = TRUE) {\n if (quote) x <- paste0(\"\\\"\", x, \"\\\"\")\n if (code) x <- paste0(\"`\", x, \"`\")\n x\n}\n\noxford_comma <- function(x, sep = \", \", final = \"and\") {\n n <- length(x)\n\n if (n < 2L) return(x) # styler: off\n\n head <- x[seq_len(n - 1L)]\n last <- x[n]\n\n head <- paste(head, collapse = sep)\n\n # Write a or b. But a, b, or c.\n if (n > 2L) {\n paste0(head, sep, final, \" \", last)\n } else {\n paste0(head, \" \", final, \" \", last)\n }\n}\n\n# Need `roxygen2` package\n#' @description add `@eval rd_collect_family(\"myfamily\")` to the functions in\n#' your package. This will automatically generate a section listing all\n#' functions tagged with `@family myfamily`.\n#' @param family A string specifying the family name.\n#' @param section_title A string specifying the section title.\n#' @param code_style A boolean indicating whether to apply code formatting\n#' to function names.\n#' @noRd\nrd_collect_family <- function(\n family,\n section_title = paste(family, \"family\"),\n code_style = TRUE) {\n # get blocks objects from the roxygenize function\n blocks <- NULL\n pos <- sys.nframe()\n while (pos > 0L) {\n if (!is.null(call <- sys.call(-pos))) {\n fn <- eval(.subset2(call, 1L), sys.frame(-(pos + 1L)))\n env <- sys.frame(-pos)\n if (\n identical(fn, getExportedValue(\"roxygen2\", \"roxygenize\")) &&\n exists(\"blocks\", envir = env, inherits = FALSE)\n ) {\n blocks <- get(\"blocks\", envir = env, inherits = FALSE)\n break\n }\n }\n pos <- pos - 1L\n }\n\n # identify the blocks with family of the same tag specified in `family`\n blocks <- blocks[\n vapply(\n blocks,\n function(block) {\n getExportedValue(\"roxygen2\", \"block_has_tags\")(\n block,\n \"family\"\n ) &&\n identical(\n getExportedValue(\"roxygen2\", \"block_get_tag_value\")(\n block,\n \"family\"\n ),\n family\n )\n },\n logical(1L),\n USE.NAMES = FALSE\n )\n ]\n if (length(blocks) == 0L) return(character()) # styler: off\n\n # extracted the function name\n funs <- vapply(\n blocks,\n function(block) {\n as.character(.subset2(block$call, 2L))\n },\n character(1L),\n USE.NAMES = FALSE\n )\n if (code_style) {\n items <- sprintf(\"\\\\code{\\\\link[=%s]{%s()}}\", funs, funs)\n } else {\n items <- sprintf(\"\\\\link[=%s]{%s()}\", funs, funs)\n }\n c(\n sprintf(\"@section %s:\", section_title),\n \"\\\\itemize{\",\n sprintf(\" \\\\item %s\", items),\n \"}\"\n )\n}\n\n# nocov end\n"], ["/ggalign/R/alignpatch-free-lab.R", "#' @param labs Which axis labs to be free? A string containing one or more of\n#' `r oxford_and(.tlbr)`.\n#' @return\n#' - `free_lab`: A modified version of `plot` with a `free_lab` class.\n#' @export\n#' @rdname free\nfree_lab <- function(plot, labs = \"tlbr\") {\n UseMethod(\"free_lab\")\n}\n\n#' @export\nfree_lab.ggplot <- function(plot, labs = \"tlbr\") {\n assert_position(labs)\n attr(plot, \"free_labs\") <- labs\n add_class(plot, \"free_lab\")\n}\n\n#' @export\nfree_lab.alignpatches <- free_lab.ggplot\n\n#' @export\nfree_lab.free_align <- function(plot, labs = \"tlbr\") {\n assert_position(labs)\n labs <- setdiff_position(labs, attr(plot, \"free_axes\"))\n if (!nzchar(labs)) return(plot) # styler: off\n NextMethod()\n}\n\n#' @export\nfree_lab.free_borders <- function(plot, labs = \"tlbr\") {\n assert_position(labs)\n labs <- setdiff_position(labs, attr(plot, \"free_borders\"))\n if (!nzchar(labs)) return(plot) # styler: off\n NextMethod()\n}\n\n#' @export\nfree_lab.free_lab <- function(plot, labs = \"tlbr\") {\n assert_position(labs)\n attr(plot, \"free_labs\") <- union_position(attr(plot, \"free_labs\"), labs)\n plot\n}\n\n#' @export\nfree_lab.default <- function(plot, labs = \"tlbr\") {\n cli_abort(\"Cannot use with {.obj_type_friendly {plot}}\")\n}\n\n####################################################\n#' @importFrom ggplot2 ggproto ggproto_parent\n#' @export\nalignpatch.free_lab <- function(x) {\n Parent <- NextMethod()\n ggproto(\n \"PatchFreeLab\", Parent,\n free_labs = setup_pos(attr(x, \"free_labs\")),\n collect_guides = function(self, guides, gt = self$gt) {\n ans <- ggproto_parent(Parent, self)$collect_guides(\n guides = guides, gt = gt\n )\n self$gt <- ggproto_parent(Parent, self)$free_lab(\n labs = self$free_labs, gt = self$gt\n )\n ans\n },\n free_lab = function(self, labs, gt = self$gt) {\n if (length(labs <- vec_set_difference(labs, self$free_labs))) {\n gt <- ggproto_parent(Parent, self)$free_lab(\n labs = labs, gt = gt\n )\n }\n gt\n }\n )\n}\n"], ["/ggalign/R/layer-order.R", "#' Change the layer adding order\n#'\n#' @description\n#' This function allows you to change the order in which layers are added to a\n#' ggplot.\n#'\n#' @param layer A [`layer geometry`][ggplot2::layer_geoms] object to be added.\n#' @param order An integer indicating the position at which the layer should be\n#' added. If `<= 0`, the layer will be added at the beginning. If greater than\n#' the number of plot layers, it will be added at the end.\n#' @return A `layer_order` object.\n#' @examples\n#' ggplot(faithfuld, aes(waiting, eruptions)) +\n#' geom_raster(aes(fill = density)) +\n#' geom_point(color = \"red\", size = 1)\n#' ggplot(faithfuld, aes(waiting, eruptions)) +\n#' geom_raster(aes(fill = density)) +\n#' layer_order(geom_point(color = \"red\", size = 1))\n#' @export\nlayer_order <- function(layer, order = 0) {\n assert_number_decimal(order)\n UseMethod(\"layer_order\")\n}\n\n#' @export\nlayer_order.default <- function(layer, order = 0) {\n cli_abort(\"{.arg layer} must be a {.fn geom_*} object\")\n}\n\n#' @export\nlayer_order.Layer <- function(layer, order = 0) {\n if (!is.infinite(order)) order <- vec_cast(order, integer())\n structure(\n list(\n object = layer,\n order = order,\n # used for `ggplot_add`\n object_name = paste(deparse(substitute(layer)), collapse = \" \")\n ),\n class = \"ggalign_layer_order\"\n )\n}\n\n#' @export\nlayer_order.ggalign_layer_order <- function(layer, order = 0) {\n if (!is.infinite(order)) order <- vec_cast(order, integer())\n layer$order <- order\n layer\n}\n\n#' @importFrom ggplot2 ggplot_add\n#' @export\nggplot_add.ggalign_layer_order <- function(object, plot, object_name, ...) {\n # ggplot2 will do something special for the layer\n # add layer_name, we re-call the method for the layer\n ans <- ggplot_add(\n .subset2(object, \"object\"),\n plot, .subset2(object, \"object_name\")\n )\n if ((cur <- length(layers <- ans$layers)) == 1L) {\n return(ans)\n }\n order <- .subset2(object, \"order\")\n layer <- .subset2(layers, cur)\n if (order >= length(layers)) return(ans) # styler: off\n if (order <= 0L) {\n layers <- append(vec_slice(layers, -cur), layer, 0L)\n } else {\n layers <- append(vec_slice(layers, -cur), layer, order)\n }\n ans$layers <- layers\n ans\n}\n"], ["/ggalign/R/scheme-.R", "new_schemes <- function(...) {\n default <- list(\n new_scheme_data(),\n new_scheme_align(),\n new_scheme_theme()\n )\n names(default) <- vapply(default, ggalign_scheme_name,\n character(1L),\n USE.NAMES = FALSE\n )\n for (i in seq_len(...length())) {\n scheme <- ...elt(i)\n default[[ggalign_scheme_name(scheme)]] <- scheme\n }\n default\n}\n\nnew_scheme <- function(name, data, ..., class = character()) {\n structure(data,\n `__ggalign.scheme_name__` = name, ...,\n class = c(class, \"ggalign_scheme\")\n )\n}\n\nggalign_scheme_name <- function(x) {\n attr(x, \"__ggalign.scheme_name__\", exact = TRUE)\n}\n\n#' @importFrom ggplot2 theme\ndefault_schemes <- function(data = NULL, th = theme()) {\n if (!is.waive(data)) data <- NULL\n new_schemes(\n new_scheme_data(data),\n new_scheme_theme(th)\n )\n}\n\n###############################################################\n#' Used to update global data\n#' @noRd\nupdate_scheme <- function(new, old, object_name) {\n UseMethod(\"update_scheme\", old)\n}\n\n#' @export\nupdate_scheme.default <- function(new, old, object_name) new\n\nupdate_layout_scheme <- function(object, layout, object_name) {\n name <- ggalign_scheme_name(object)\n layout@schemes[name] <- list(update_scheme(\n object, .subset2(layout@schemes, name), object_name\n ))\n layout\n}\n\n###############################################################\ninherit_scheme <- function(scheme, pscheme) {\n UseMethod(\"inherit_scheme\", pscheme)\n}\n\n# If no parent scheme, use child scheme directly\n#' @export\ninherit_scheme.NULL <- function(scheme, pscheme) scheme\n\ninherit_schemes <- function(schemes, pschemes) {\n nms <- vapply(pschemes,\n ggalign_scheme_name, character(1L),\n USE.NAMES = FALSE\n )\n ans <- lapply(nms, function(opt) {\n inherit_scheme(.subset2(schemes, opt), .subset2(pschemes, opt))\n })\n names(ans) <- nms\n ans\n}\n\n###############################################################\nplot_add_scheme <- function(plot, scheme) UseMethod(\"plot_add_scheme\", scheme)\n\n#' @export\nplot_add_scheme.NULL <- function(plot, scheme) plot\n\nplot_add_schemes <- function(plot, schemes) {\n for (i in seq_along(schemes)) {\n plot <- plot_add_scheme(plot, scheme = .subset2(schemes, i))\n }\n plot\n}\n"], ["/ggalign/R/layout-heatmap-build.R", "#' @export\nquad_build.HeatmapLayout <- function(quad, schemes = NULL, theme = NULL,\n direction = NULL) {\n ans <- NextMethod()\n\n # add heatmap filling in the first layer --------------\n if (!is.null(filling <- quad@filling)) {\n # we always ensure the filling layer has a fill mapping\n if (is.null(.subset2(ans$plots$main$mapping, \"fill\"))) {\n mapping <- aes(.data$.x, .data$.y, fill = .data$value)\n } else {\n mapping <- aes(.data$.x, .data$.y)\n }\n if (is.waive(filling)) {\n if (nrow(quad@data) * ncol(quad@data) > 20000L) {\n cli_inform(c(\">\" = \"heatmap built with {.fn geom_raster}\"))\n filling <- \"raster\"\n } else {\n cli_inform(c(\">\" = \"heatmap built with {.fn geom_tile}\"))\n filling <- \"tile\"\n }\n }\n ans$plots$main <- ans$plots$main + layer_order(switch(filling,\n raster = ggplot2::geom_raster(mapping = mapping),\n tile = ggplot2::geom_tile(mapping = mapping)\n ))\n }\n # add class to set the default color mapping --------\n ans$plots$main <- add_class(ans$plots$main, \"ggalign_heatmap\")\n ans\n}\n\n#' @importFrom ggplot2 ggplot_build\n#' @export\nggplot_build.ggalign_heatmap <- function(plot, ...) {\n with_options(\n NextMethod(),\n ggplot2.discrete.fill = heatmap_fill(\"discrete\"),\n ggplot2.continuous.fill = heatmap_fill(\"continuous\")\n )\n}\n\nheatmap_fill <- function(type) {\n opt <- sprintf(\"%s.heatmap_%s_fill\", pkg_nm(), type)\n if (is.null(ans <- getOption(opt, default = NULL))) {\n if (type == \"continuous\") {\n ans <- function(...) {\n ggplot2::scale_fill_gradient2(low = \"blue\", high = \"red\")\n }\n } else {\n ans <- getOption(\"ggplot2.discrete.fill\")\n }\n }\n ans\n}\n"], ["/ggalign/R/import-standalone-assert.R", "# Standalone file: do not edit by hand\n# Source: https://github.com/Yunuuuu/standalone/blob/HEAD/R/standalone-assert.R\n# Generated by: usethis::use_standalone(\"Yunuuuu/standalone\", \"assert\")\n# ----------------------------------------------------------------------\n#\n# ---\n# repo: Yunuuuu/standalone\n# file: standalone-assert.R\n# last-updated: 2025-04-16\n# license: https://unlicense.org\n# dependencies: [standalone-obj-type.R]\n# imports: rlang\n# ---\n\n# ## Changelog\n# 2025-04-16:\n# - `assert_number_whole` gains `allow_infinite` argument\n#\n# 2025-04-11:\n# - new `.rlang_allow_number`\n# - new `.rlang_check_number`\n# - new `.rlang_check_bool`\n# - new `.rlang_check_string`\n#\n# 2024-11-10:\n# - Added support for S3 object\n#\n# nocov start\n# Following codes were modified from `rlang` package\n\n#' Report if an argument is a specific class\n#'\n#' @param x The object type which does not conform to `what`. Its\n#' `obj_type_friendly()` is taken and mentioned in the error message.\n#' @param what The friendly expected type as a string. Can be a\n#' character vector of expected types, in which case the error\n#' message mentions all of them in an \"or\" enumeration.\n#' @param show_value Passed to `value` argument of `obj_type_friendly()`.\n#' @param show_length Passed to `length` argument of `obj_type_friendly()`.\n#' @param ... Arguments passed to [rlang::abort()].\n#' @importFrom rlang is_missing\n#' @noRd\nassert_ <- function(x, check, what,\n allow_null = FALSE,\n allow_na = FALSE,\n show_value = TRUE,\n show_length = FALSE,\n ...,\n arg = caller_arg(x),\n call = caller_env()) {\n if (!is_missing(x) && (\n (allow_null && is.null(x)) || check(x)\n )) {\n return(invisible(NULL))\n }\n stop_input_type(x, what,\n allow_na = allow_na,\n allow_null = allow_null,\n show_value = show_value,\n show_length = show_length,\n ...,\n arg = arg, call = call\n )\n}\n\nIS_NUMBER_true <- 0\nIS_NUMBER_false <- 1\nIS_NUMBER_oob <- 2\n\n.standalone_types_check_assert_call <- .Call\n\n#' @importFrom rlang ffi_standalone_check_number_1.0.7\n.rlang_check_number <- function(x, allow_decimal,\n min = NULL,\n max = NULL,\n allow_infinite = allow_decimal,\n allow_na = FALSE,\n allow_null = FALSE) {\n .standalone_types_check_assert_call(\n ffi_standalone_check_number_1.0.7,\n x,\n allow_decimal,\n min,\n max,\n allow_infinite,\n allow_na,\n allow_null\n )\n}\n\n#' @importFrom rlang ffi_standalone_is_bool_1.0.7\n.rlang_check_bool <- function(x, allow_na = FALSE, allow_null = FALSE) {\n .standalone_types_check_assert_call(\n ffi_standalone_is_bool_1.0.7,\n x,\n allow_na,\n allow_null\n )\n}\n\n#' @importFrom rlang is_string\n.rlang_check_string <- function(x, allow_empty = TRUE,\n allow_na = FALSE, allow_null = FALSE) {\n if (is_string(x) && !is.na(x)) {\n if (allow_empty || x != \"\") {\n return(TRUE)\n }\n }\n\n if (allow_null && is.null(x)) {\n return(TRUE)\n }\n\n if (allow_na && (identical(x, NA) || identical(x, NA_character_))) {\n return(TRUE)\n }\n\n FALSE\n}\n\n#' @importFrom rlang abort\n.rlang_allow_number <- function(x, exit_code, allow_decimal,\n min = NULL,\n max = NULL,\n allow_na = FALSE,\n allow_null = FALSE) {\n if (allow_decimal) {\n what <- \"a number\"\n } else {\n what <- \"a whole number\"\n }\n if (exit_code == IS_NUMBER_oob) {\n min <- min %||% -Inf\n max <- max %||% Inf\n\n if (min > -Inf && max < Inf) {\n what <- sprintf(\"%s between %s and %s\", what, min, max)\n } else if (x < min) {\n what <- sprintf(\"%s larger than or equal to %s\", what, min)\n } else if (x > max) {\n what <- sprintf(\"%s smaller than or equal to %s\", what, max)\n } else {\n abort(\"Unexpected state in OOB check\", .internal = TRUE)\n }\n }\n allow_what_type(what, allow_na = allow_na, allow_null = allow_null)\n}\n\n# scalar object ----------------------------------\nassert_string <- function(x,\n ...,\n allow_empty = TRUE,\n allow_na = FALSE,\n allow_null = FALSE,\n arg = caller_arg(x),\n call = caller_env()) {\n assert_(\n x = x,\n check = function(x) {\n .rlang_check_string(\n x,\n allow_empty = allow_empty,\n allow_na = allow_na,\n allow_null = allow_null\n )\n },\n what = \"a single string\",\n ...,\n allow_na = allow_na,\n allow_null = allow_null,\n arg = arg,\n call = call\n )\n}\n\n#' @importFrom rlang abort\n.stop_not_number <- function(x,\n exit_code,\n allow_decimal,\n ...,\n min = NULL,\n max = NULL,\n allow_na = FALSE,\n allow_null = FALSE,\n show_value = TRUE,\n show_length = FALSE,\n arg = caller_arg(x),\n call = caller_env()) {\n what <- .rlang_allow_number(\n x = x,\n exit_code = exit_code,\n allow_decimal = allow_decimal,\n min = min, max = max,\n allow_na = allow_na,\n allow_null = allow_null\n )\n if (inherits(arg, \"AsIs\")) {\n format_arg <- identity\n } else {\n format_arg <- function(x) sprintf(\"`%s`\", x)\n }\n message <- sprintf(\n \"%s must be %s, not %s.\",\n format_arg(arg), what,\n obj_type_friendly(x, value = show_value, length = show_length)\n )\n abort(message, ..., call = call, arg = arg)\n}\n\n#' @importFrom rlang is_missing\nassert_number_decimal <- function(x,\n ...,\n min = NULL,\n max = NULL,\n allow_infinite = TRUE,\n allow_na = FALSE,\n allow_null = FALSE,\n arg = caller_arg(x),\n call = caller_env()) {\n if (is_missing(x)) {\n exit_code <- IS_NUMBER_false\n } else if (0 == (exit_code <- .rlang_check_number(\n x,\n allow_decimal = TRUE,\n min = min,\n max = max,\n allow_infinite = allow_infinite,\n allow_na = allow_na,\n allow_null = allow_null\n ))) {\n return(invisible(NULL))\n }\n\n .stop_not_number(\n x,\n ...,\n exit_code = exit_code,\n allow_decimal = TRUE,\n min = min,\n max = max,\n allow_na = allow_na,\n allow_null = allow_null,\n arg = arg,\n call = call\n )\n}\n\n#' @importFrom rlang is_missing\nassert_number_whole <- function(x,\n ...,\n min = NULL,\n max = NULL,\n allow_infinite = FALSE,\n allow_na = FALSE,\n allow_null = FALSE,\n arg = caller_arg(x),\n call = caller_env()) {\n if (is_missing(x)) {\n exit_code <- IS_NUMBER_false\n } else if (0 == (exit_code <- .rlang_check_number(\n x,\n allow_decimal = FALSE,\n min = min,\n max = max,\n allow_infinite = allow_infinite,\n allow_na = allow_na,\n allow_null = allow_null\n ))) {\n return(invisible(NULL))\n }\n\n .stop_not_number(\n x,\n ...,\n exit_code = exit_code,\n allow_decimal = FALSE,\n min = min,\n max = max,\n allow_na = allow_na,\n allow_null = allow_null,\n arg = arg,\n call = call\n )\n}\n\n#' @importFrom rlang ffi_standalone_is_bool_1.0.7\nassert_bool <- function(x,\n ...,\n allow_na = FALSE,\n allow_null = FALSE,\n arg = caller_arg(x),\n call = caller_env()) {\n if (!missing(x) && .rlang_check_bool(x, allow_na, allow_null)) {\n return(invisible(NULL))\n }\n\n stop_input_type(\n x,\n c(\"`TRUE`\", \"`FALSE`\"),\n ...,\n allow_na = allow_na,\n allow_null = allow_null,\n arg = arg,\n call = call\n )\n}\n\n# atomic vector ------------------------------------\n#' @importFrom rlang abort\nassert_character <- function(x,\n ...,\n allow_na = TRUE,\n allow_null = FALSE,\n arg = caller_arg(x),\n call = caller_env()) {\n if (!missing(x)) {\n if (is.character(x)) {\n if (!allow_na && anyNA(x)) {\n abort(\n sprintf(\"`%s` can't contain NA values.\", arg),\n arg = arg, call = call\n )\n }\n return(invisible(NULL))\n }\n\n if (allow_null && is.null(x)) {\n return(invisible(NULL))\n }\n }\n stop_input_type(\n x,\n \"a character vector\",\n ...,\n allow_na = FALSE,\n allow_null = allow_null,\n arg = arg,\n call = call\n )\n}\n\n#' @importFrom rlang abort\nassert_logical <- function(x,\n ...,\n allow_na = TRUE,\n allow_null = FALSE,\n arg = caller_arg(x),\n call = caller_env()) {\n if (!missing(x)) {\n if (is.logical(x)) {\n if (!allow_na && anyNA(x)) {\n abort(\n sprintf(\"`%s` can't contain NA values.\", arg),\n arg = arg, call = call\n )\n }\n return(invisible(NULL))\n }\n if (allow_null && is.null(x)) {\n return(invisible(NULL))\n }\n }\n\n stop_input_type(\n x,\n \"a logical vector\",\n ...,\n allow_na = FALSE,\n allow_null = allow_null,\n arg = arg,\n call = call\n )\n}\n\n# S3 object ----------------------------------------\n#' @importFrom rlang is_string is_missing\nassert_s3_class <- function(x, is_class, what, ...,\n arg = caller_arg(x),\n call = caller_env()) {\n if (is.character(is_class)) {\n class <- is_class\n is_class <- function(x) inherits(x, what = class)\n if (is_missing(what)) what <- sprintf(\"a <%s>\", class)\n }\n assert_(\n x = x, check = is_class,\n what = what,\n ...,\n arg = arg, call = call\n )\n}\n\n# nocov end\n"], ["/ggalign/R/alignpatch-free-space.R", "#' @param spaces Which border spaces should be removed? A string containing one\n#' or more of `r oxford_and(.tlbr)`.\n#' @return\n#' - `free_space`: A modified version of `plot` with a `free_space` class.\n#' @export\n#' @rdname free\nfree_space <- function(plot, spaces = \"tlbr\") {\n UseMethod(\"free_space\")\n}\n\n#' @export\nfree_space.default <- function(plot, spaces = \"tlbr\") {\n cli_abort(\"Cannot use with {.obj_type_friendly {plot}}\")\n}\n\n#' @export\nfree_space.ggplot <- function(plot, spaces = \"tlbr\") {\n assert_position(spaces)\n attr(plot, \"free_spaces\") <- spaces\n add_class(plot, \"free_space\")\n}\n\n#' @export\nfree_space.alignpatches <- free_space.ggplot\n\n#' @export\nfree_space.free_align <- function(plot, spaces = \"tlbr\") {\n assert_position(spaces)\n spaces <- setdiff_position(spaces, attr(plot, \"free_axes\"))\n if (!nzchar(spaces)) {\n return(plot)\n }\n NextMethod()\n}\n\n#' @export\nfree_space.free_space <- function(plot, spaces = \"tlbr\") {\n assert_position(spaces)\n attr(plot, \"free_spaces\") <- union_position(\n attr(plot, \"free_spaces\"), spaces\n )\n plot\n}\n\n##########################################################\n#' @importFrom ggplot2 ggproto ggproto_parent\n#' @importFrom grid unit\n#' @export\nalignpatch.free_space <- function(x) {\n Parent <- NextMethod()\n ggproto(\n \"PatchFreeSpace\", Parent,\n free_spaces = split_position(attr(x, \"free_spaces\")),\n get_sizes = function(self, free = NULL, gt = self$gt) {\n ggproto_parent(Parent, self)$get_sizes(\n union(free, self$free_spaces),\n gt = gt\n )\n }\n )\n}\n"], ["/ggalign/R/grid-grob-magick.R", "#' Rasterize a grob object with magick\n#'\n#' @param grob A [`grob()`][grid::grob]. Use [`patch()`] to convert any objects\n#' into a `grob`.\n#' @param magick A function (purrr-style formula is accepted) that takes an\n#' [`image_read()`][magick::image_read] object as input and returns an object\n#' compatible with [`as.raster()`][grDevices::as.raster]. You can use any of\n#' the `image_*()` functions from the **magick** package to process the raster\n#' image.\n#' @param res An integer sets the desired resolution in pixels.\n#' @inheritParams rlang::args_dots_empty\n#' @inheritParams grid::rasterGrob\n#' @return A `magickGrob` object.\n#' @export\nmagickGrob <- function(grob, magick = NULL, ...,\n res = NULL, interpolate = FALSE,\n name = NULL, vp = NULL) {\n rlang::check_installed(\"magick\", \"to use `magickGrob()`\")\n if (!is.null(magick) && !is.function(magick <- allow_lambda(magick))) {\n cli_abort(\"{.arg magick} must be a function\")\n }\n assert_number_whole(res, min = 1, allow_null = TRUE)\n assert_bool(interpolate)\n magickGrob0(\n grob = grob, magick = magick, ..., res = res,\n interpolate = interpolate, name = name, vp = vp\n )\n}\n\nmagickGrob0 <- function(grob, ...) UseMethod(\"magickGrob0\")\n\n#' @importFrom grid gTree\n#' @export\nmagickGrob0.grob <- function(grob, magick = NULL, ...,\n res = NULL, interpolate = FALSE,\n name = NULL, vp = NULL) {\n rlang::check_dots_empty()\n gTree(\n grob = grob, magick = magick, res = res,\n interpolate = interpolate, name = name, vp = vp,\n cl = \"magickGrob\"\n )\n}\n\n#' @importFrom grid gTree\n#' @export\nmagickGrob0.gList <- function(grob, ...) {\n magickGrob0(grob = gTree(children = grob), ...)\n}\n\n#' @importFrom grid editGrob\n#' @importFrom rlang inject\n#' @export\nmagickGrob0.magickGrob <- function(grob, magick = waiver(), ...,\n res = waiver(), interpolate = waiver(),\n name = waiver(), vp = waiver()) {\n rlang::check_dots_empty()\n params <- list(\n magick = magick, res = res,\n interpolate = interpolate, name = name, vp = vp\n )\n params <- params[!vapply(params, is.waive, logical(1L), USE.NAMES = FALSE)]\n inject(editGrob(grob, !!!params))\n}\n\n#' @export\nmagickGrob0.default <- function(grob, ...) {\n cli_abort(\"{.arg grob} must be a {.cls grob} object\")\n}\n\n# preDraw:\n# - makeContext\n# - pushvpgp\n# - preDrawDetails: by default, do noting\n# makeContent:\n# drawDetails:\n# postDraw:\n# - postDrawDetails: by default, do noting\n# - popgrobvp\n#' @importFrom grid makeContent unit convertHeight convertWidth viewport gList\n#' @export\nmakeContent.magickGrob <- function(x) {\n # Grab viewport information\n width <- convertWidth(unit(1, \"npc\"), \"pt\", valueOnly = TRUE)\n height <- convertHeight(unit(1, \"npc\"), \"pt\", valueOnly = TRUE)\n\n # Grab grob metadata\n plot_res <- convertWidth(unit(1, \"inch\"), \"pt\", valueOnly = TRUE)\n res <- .subset2(x, \"res\") %||% plot_res\n\n magick <- .subset2(x, \"magick\")\n interpolate <- .subset2(x, \"interpolate\")\n\n # Track current device\n old_dev <- grDevices::dev.cur()\n\n # Reset current device upon function exit\n on.exit(grDevices::dev.set(old_dev), add = TRUE)\n\n # open the magick raster device\n image <- magick::image_graph(\n width = width * res / plot_res,\n height = height * res / plot_res,\n bg = NA_character_, res = res,\n clip = FALSE, antialias = FALSE\n )\n\n # Render the grob\n grid::pushViewport(viewport())\n\n # Clean up the grob for rendering\n grid::grid.draw(.subset2(x, \"grob\")) # should respect the viewport of `x`\n grid::popViewport()\n grDevices::dev.off()\n on.exit(magick::image_destroy(image), add = TRUE)\n\n # run `magick` when necessary\n if (!is.null(magick)) image <- magick(image)\n\n # Use native raster instead\n raster <- grDevices::as.raster(image, native = TRUE)\n\n # Forward raster grob\n setChildren(x, children = gList(\n grid::rasterGrob(\n raster, # should contain current area of full viewport\n x = 0.5, y = 0.5,\n height = unit(height, \"pt\"),\n width = unit(width, \"pt\"),\n default.units = \"npc\",\n just = \"center\",\n interpolate = interpolate\n )\n ))\n}\n"], ["/ggalign/R/fortify-matrix-.R", "#' Build a Matrix\n#'\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' This function converts various objects into a matrix format. By default, it\n#' calls [`as.matrix()`] to build a matrix.\n#'\n#' @param data An object to be converted into a matrix.\n#' @param ... Additional arguments passed to methods.\n#' @param data_arg The argument name for `data`. Developers can use it to\n#' improve messages. Not used by the user.\n#' @param call The execution environment where `data` and other arguments for\n#' the method are collected. Developers can use it to improve messages. Not\n#' used by the user.\n#' @return A matrix.\n#' @eval\n#' rd_collect_family(\"fortify_matrix\", \"`fortify_matrix` method collections\")\n#' @export\nfortify_matrix <- function(data, ..., data_arg = NULL,\n call = NULL) {\n UseMethod(\"fortify_matrix\")\n}\n\n#' @inheritParams rlang::args_dots_empty\n#' @inherit fortify_matrix title return\n#' @description\n#' By default, it calls [`as.matrix()`] to build a matrix.\n#' @inheritParams fortify_matrix\n#' @family fortify_matrix\n#' @importFrom rlang try_fetch\n#' @export\nfortify_matrix.default <- function(data, ..., data_arg = NULL,\n call = NULL) {\n call <- call %||% current_call()\n data_arg <- data_arg %||% \"data\"\n rlang::check_dots_empty(call = call)\n try_fetch(\n as.matrix(data),\n error = function(cnd) {\n cli_abort(\n paste0(\n \"{.arg {data_arg}} must be a {.cls matrix}, \",\n \"or an object coercible by {.fn fortify_matrix}, or a valid \",\n \"{.cls matrix}-like object coercible by {.fn as.matrix}\"\n ),\n call = call\n )\n }\n )\n}\n\n#' @export\nfortify_matrix.waiver <- function(data, ..., data_arg = NULL,\n call = NULL) {\n call <- call %||% current_call()\n rlang::check_dots_empty(call = call)\n data\n}\n\n#' @export\nfortify_matrix.NULL <- fortify_matrix.waiver\n\n#' @export\nfortify_matrix.function <- fortify_matrix.waiver\n\n#' @export\nfortify_matrix.formula <- function(data, ..., data_arg = NULL,\n call = NULL) {\n call <- call %||% current_call()\n rlang::check_dots_empty(call = call)\n rlang::as_function(data)\n}\n"], ["/ggalign/R/alignpatch-free-guide.R", "#' @param guides A string containing one or more of\n#' `r oxford_and(c(.tlbr, \"i\"))` indicates which side of guide legends should be\n#' collected for the plot. If `NULL`, no guide legends will be collected.\n#' @return\n#' - `free_guide`: A modified version of `plot` with a `free_guide` class.\n#' @export\n#' @rdname free\nfree_guide <- function(plot, guides = \"tlbr\") {\n UseMethod(\"free_guide\")\n}\n\n#' @export\nfree_guide.ggplot <- function(plot, guides = \"tlbr\") {\n if (!is.null(guides)) assert_guides(guides)\n attr(plot, \"free_guides\") <- guides\n add_class(plot, \"free_guide\")\n}\n\n#' @export\nfree_guide.alignpatches <- free_guide.ggplot\n\n#' @export\nfree_guide.free_guide <- function(plot, guides = \"tlbr\") {\n if (is.null(guides)) {\n attr(plot, \"free_guides\") <- NULL\n } else {\n assert_guides(guides)\n if (is.null(old <- attr(plot, \"free_guides\", exact = TRUE))) {\n attr(plot, \"free_guides\") <- guides\n } else {\n attr(plot, \"free_guides\") <- union_position(old, guides)\n }\n }\n plot\n}\n\n################################################################\n#' @importFrom ggplot2 ggproto ggproto_parent\n#' @export\nalignpatch.free_guide <- function(x) {\n Parent <- NextMethod()\n if (!is.null(free_guides <- attr(x, \"free_guides\", exact = TRUE))) {\n free_guides <- setup_guides(free_guides)\n }\n ggproto(\"PatchFreeGuide\", Parent,\n set_guides = function(self, guides) free_guides\n )\n}\n"], ["/ggalign/R/alignpatch-patch.R", "#' Convert Object into a Grob\n#'\n#' The `patch()` function is used by [`ggwrap()`] and [inset()] to convert\n#' objects into a [`grob`][grid::grob].\n#'\n#' @param x An object to be converted into a [`grob`][grid::grob].\n#' @param ... Additional arguments passed to specific methods.\n#' @return A [`grob`][grid::grob] object.\n#' @eval rd_collect_family(\"patch\", \"`patch` method collections\")\n#' @export\n#' @keywords internal\npatch <- function(x, ...) {\n UseMethod(\"patch\")\n}\n\n# Following methods much are copied from `cowplot` or `ggplotify`\n#' @export\npatch.default <- function(x, ...) {\n cli_abort(\"Cannot make grob from {.obj_type_friendly {x}}\")\n}\n\n#' @inherit patch title description return\n#' @inheritParams patch\n#' @param ... Not used currently.\n#' @family patch\n#' @export\npatch.grob <- function(x, ...) {\n rlang::check_dots_empty()\n x\n}\n\n#' @importFrom grid gTree\n#' @export\n#' @rdname patch.grob\npatch.gList <- function(x, ...) {\n rlang::check_dots_empty()\n # gLists need to be wrapped in a gTree\n gTree(children = x)\n}\n\n#' @importFrom ggplot2 ggplotGrob\n#' @inherit patch.grob\n#' @seealso [ggplot][ggplot2::ggplot]\n#' @family patch\n#' @export\npatch.ggplot <- function(x, ...) {\n ggplotGrob(x, ...)\n}\n\n#' @inherit patch.grob\n#' @seealso\n#' - [`patch_titles()`]\n#' - [`inset()`]\n#' - [`ggwrap()`]\n#' @family patch\n#' @export\npatch.patch_ggplot <- function(x, ...) {\n ggalignGrob(x, ...)\n}\n\n#' @inherit patch.grob\n#' @seealso [`alignpatches`][align_plots]\n#' @family patch\n#' @export\npatch.alignpatches <- function(x, ...) {\n ggalignGrob(x, ...)\n}\n\n#' @inherit patch.grob\n#' @seealso [`patchwork`][patchwork::patchworkGrob]\n#' @family patch\n#' @export\npatch.patchwork <- function(x, ...) {\n rlang::check_installed(\"patchwork\", \"to make grob from patchwork\")\n patchwork::patchworkGrob(x, ...)\n}\n\n#' @inherit patch.grob\n#' @seealso [`patch`][patchwork::patchGrob]\n#' @family patch\n#' @export\npatch.patch <- function(x, ...) {\n rlang::check_installed(\"patchwork\", \"to make grob from patch\")\n patchwork::patchGrob(x, ...)\n}\n\n#' @inherit patch.grob\n#' @param ... Graphical Parameters passed on to [par()][graphics::par].\n#' @inheritParams gridGraphics::echoGrob\n#' @seealso [`plot()`]\n#' @family patch\n#' @export\npatch.formula <- function(x, ..., device = NULL, name = NULL) {\n rlang::check_installed(\"gridGraphics\", \"to make grob from base plot\")\n gp <- graphics::par(..., no.readonly = TRUE)\n gridGraphics::echoGrob(\n function() {\n old_gp <- graphics::par(no.readonly = TRUE)\n graphics::par(gp)\n on.exit(try(graphics::par(old_gp)))\n suppressMessages(eval(x[[2]], attr(x, \".Environment\")))\n invisible(NULL)\n },\n name = name,\n device = device %||% offscreen\n )\n}\n\n#' @export\n#' @rdname patch.formula\npatch.function <- function(x, ..., device = NULL, name = NULL) {\n rlang::check_installed(\"gridGraphics\", \"to make grob from base plot\")\n gp <- graphics::par(..., no.readonly = TRUE)\n gridGraphics::echoGrob(\n function() {\n old_gp <- graphics::par(no.readonly = TRUE)\n graphics::par(gp)\n on.exit(try(graphics::par(old_gp)))\n suppressMessages(x())\n invisible(NULL)\n },\n name = name,\n device = device %||% offscreen\n )\n}\n\n#' @inherit patch.grob\n#' @inheritParams gridGraphics::echoGrob\n#' @seealso [`recordPlot()`][grDevices::recordPlot]\n#' @family patch\n#' @export\npatch.recordedplot <- function(x, ..., device = NULL) {\n rlang::check_installed(\"gridGraphics\", \"to make grob from recordedplot\")\n rlang::check_dots_empty()\n gridGraphics::echoGrob(x, device = device %||% offscreen)\n}\n\noffscreen <- function(width, height) {\n if (requireNamespace(\"ragg\", quietly = TRUE)) {\n ragg::agg_capture(width = width, height = height, units = \"in\")\n grDevices::dev.control(\"enable\")\n } else {\n grDevices::pdf(NULL, width = width, height = height)\n grDevices::dev.control(\"enable\")\n }\n}\n\n#' @inherit patch.grob\n#' @inheritDotParams grid::grid.grabExpr -expr -device\n#' @inheritParams grid::grid.grabExpr\n#' @seealso [`trellis`][lattice::trellis.object]\n#' @family patch\n#' @export\npatch.trellis <- function(x, ..., device = NULL) {\n grid::grid.grabExpr(expr = print(x), ..., device = device %||% offscreen)\n}\n\n#' @inherit patch.grob\n#' @param ... Additional arguments passed to [draw()][ComplexHeatmap::draw].\n#' @inheritParams grid::grid.grabExpr\n#' @seealso\n#' - [`Heatmap()`][ComplexHeatmap::Heatmap]\n#' - [`HeatmapAnnotation()`][ComplexHeatmap::HeatmapAnnotation]\n#' @family patch\n#' @export\npatch.Heatmap <- function(x, ..., device = NULL) {\n rlang::check_installed(\n \"ComplexHeatmap\",\n sprintf(\"to make grob from %s plot\", obj_type_friendly(x))\n )\n draw <- getExportedValue(\"ComplexHeatmap\", \"draw\")\n grid::grid.grabExpr(\n expr = draw(object = x, ...),\n device = device %||% offscreen\n )\n}\n\n#' @export\n#' @rdname patch.Heatmap\npatch.HeatmapList <- patch.Heatmap\n\n#' @export\n#' @rdname patch.Heatmap\npatch.HeatmapAnnotation <- patch.HeatmapList\n\n#' @inherit patch.grob\n#' @seealso [`pheatmap()`][pheatmap::pheatmap]\n#' @family patch\n#' @export\npatch.pheatmap <- function(x, ...) {\n rlang::check_dots_empty()\n .subset2(x, \"gtable\")\n}\n"], ["/ggalign/R/import-standalone-purrr.R", "# Standalone file: do not edit by hand\n# Source: \n# ----------------------------------------------------------------------\n#\n# ---\n# repo: Yunuuuu/standalone\n# file: standalone-purrr.R\n# last-updated: 2024-11-13\n# license: https://unlicense.org\n# ---\n\n# This file provides a minimal shim to provide a purrr-like API on top of\n# base R functions. They are not drop-in replacements but allow a similar style\n# of programming.\n#\n# Note: these functions won't support lambda syntax.\n\n# ## Changelog\n# 2024-11-13:\n# rename `transpose()` to `list_transpose()`\n#\n# 2024-11-12:\n# First release\n#\n# nocov start\n\nmap <- function(.x, .f, ...) lapply(.x, .f, ...)\n\nwalk <- function(.x, .f, ...) {\n lapply(.x, .f, ...)\n invisible(.x)\n}\n\nmap_lgl <- function(.x, .f, ...) {\n vapply(X = .x, FUN = .f, logical(1L), ...)\n}\n\nmap_int <- function(.x, .f, ...) {\n vapply(X = .x, FUN = .f, integer(1L), ...)\n}\n\nmap_dbl <- function(.x, .f, ...) {\n vapply(X = .x, FUN = .f, double(1L), ...)\n}\n\nmap_chr <- function(.x, .f, ...) {\n vapply(X = .x, FUN = .f, character(1L), ...)\n}\n\npmap <- function(.l, .f, ...) {\n out <- .mapply(.f, .l, list(...))\n if (!is.null(nms <- names(.subset2(.l, 1L)))) names(out) <- nms\n out\n}\n\npmap_lgl <- function(.l, .f, ...) {\n .purrr_pmap_mold(.l, .f, ..., mold = logical(1L))\n}\n\npmap_int <- function(.l, .f, ...) {\n .purrr_pmap_mold(.l, .f, ..., mold = integer(1L))\n}\n\npmap_dbl <- function(.l, .f, ...) {\n .purrr_pmap_mold(.l, .f, ..., mold = double(1L))\n}\n\npmap_chr <- function(.l, .f, ...) {\n .purrr_pmap_mold(.l, .f, ..., mold = character(1L))\n}\n\n.purrr_pmap_mold <- function(.l, .f, ..., mold) {\n nms <- names(.subset2(.l, 1L))\n dots <- list(...)\n out <- vapply(seq_along(nms), function(i) {\n do.call(.f, args = c(lapply(.l, .subset2, i), dots))\n }, mold, USE.NAMES = FALSE)\n if (!is.null(nms)) names(out) <- nms\n out\n}\n\nmap2 <- function(.x, .y, .f, ...) pmap(list(.x, .y), .f, ...)\n\nmap2_lgl <- function(.x, .y, .f, ...) {\n .purrr_pmap_mold(list(.x, .y), .f, ..., mold = logical(1L))\n}\n\nmap2_int <- function(.x, .y, .f, ...) {\n .purrr_pmap_mold(list(.x, .y), .f, ..., mold = integer(1L))\n}\n\nmap2_dbl <- function(.x, .y, .f, ...) {\n .purrr_pmap_mold(list(.x, .y), .f, ..., mold = double(1L))\n}\n\nmap2_chr <- function(.x, .y, .f, ...) {\n .purrr_pmap_mold(list(.x, .y), .f, ..., mold = character(1L))\n}\n\nimap <- function(.x, .f, ...) {\n nms <- names(.x)\n if (is.null(nms)) {\n .l <- list(.x, seq_along(.x))\n } else {\n .l <- list(.x, nms)\n }\n pmap(.l, .f, ...)\n}\n\n.purrr_imap_mold <- function(.x, .f, ..., mold) {\n if (is.null(nms <- names(.x))) {\n .l <- list(.x, seq_along(.x))\n } else {\n .l <- list(.x, nms)\n }\n .purrr_pmap_mold(.l, .f, ..., mold = mold)\n}\n\nimap_lgl <- function(.l, .f, ...) {\n .purrr_imap_mold(.l, .f, ..., mold = logical(1L))\n}\n\nimap_int <- function(.l, .f, ...) {\n .purrr_imap_mold(.l, .f, ..., mold = integer(1L))\n}\n\nimap_dbl <- function(.l, .f, ...) {\n .purrr_imap_mold(.l, .f, ..., mold = double(1L))\n}\n\nimap_chr <- function(.l, .f, ...) {\n .purrr_imap_mold(.l, .f, ..., mold = character(1L))\n}\n\nlist_transpose <- function(.l) {\n if (!length(.l)) return(.l) # styler: off\n inner_names <- names(.subset2(.l, 1L))\n if (is.null(inner_names)) {\n fields <- seq_along(.subset2(.l, 1L))\n } else {\n fields <- inner_names\n names(fields) <- fields\n .l <- lapply(.l, function(x) {\n if (is.null(names(x))) names(x) <- inner_names # styler: off\n x\n })\n }\n\n # This way missing fields are subsetted as `NULL` instead of causing\n # an error\n .l <- lapply(.l, as.list)\n\n lapply(fields, function(i) lapply(.l, .subset2, i))\n}\n\n# nocov end\n"], ["/ggalign/R/utils-rd.R", "rd_layout <- function() {\n sprintf(\"%s or [`stack_layout()`] object\", rd_quad())\n}\n\nrd_quad <- function() \"[`quad_layout()`]/[`ggheatmap()`]\"\n\nrd_chain_what <- function() {\n paste(\n \"A single number or string of the plot elements in the layout.\",\n \"If `NULL`, will remove any active context\"\n )\n}\n\nrd_quad_position <- function(action) {\n sprintf(\n \"A string of %s indicates which annotation stack should be %s\",\n oxford_or(.TLBR),\n action\n )\n}\n\nrd_layout_data <- function() {\n paste(\n \"Default dataset to use for the layout. If not specified, it must be\",\n \"supplied in each plot added to the layout\"\n )\n}\n\nrd_gg_aesthetics <- function(...) {\n ans <- ggfun(\"rd_aesthetics\")(...)\n ans <- sub(\"link[=\", \"link[ggplot2:\", ans, fixed = TRUE)\n sub(\"(vignette\\\\([^)]+)\\\\)\", \"\\\\1, package = \\\"ggplot2\\\")\", ans)\n}\n"], ["/ggalign/R/tune.R", "#' Change the shape of the input object\n#'\n#' @param data An R object.\n#' @param shape Usually `NULL` or a string, specifying the new shape for the\n#' object. Refer to the detailed method for allowed values.\n#' @details\n#' In most cases, [`fortify_matrix()`] or [`fortify_data_frame()`] provide full\n#' support for transforming objects. However, some objects may require two\n#' completely different approaches to be fortified. The `tune` function acts as\n#' a helper to create a new class tailored for these objects.\n#' @eval rd_collect_family(\"tune\", \"`tune` method collections\")\n#' @export\ntune <- function(data, shape = NULL) UseMethod(\"tune\")\n\n#' @inherit tune title\n#' @description\n#' - `new_tune`: Creates a new object by wrapping it in a scalar list with\n#' the specified attributes and class.\n#' - `tune_data`: Retrieves the original input data.\n#'\n#' @param x An R object.\n#' @param ... Additional attributes passed to [`structure()`].\n#' @param class A character vector specifying the class name to be added.\n#' @export\nnew_tune <- function(x, ..., class = character()) {\n structure(list(x), ..., class = c(class, \"ggalign_tune\"))\n}\n\n#' @export\n#' @rdname new_tune\ntune_data <- function(x) .subset2(x, 1L)\n\n#' @export\nprint.ggalign_tune <- function(x, ...) {\n print(tune_data(x))\n invisible(x)\n}\n\n#' @export\nfortify_matrix.ggalign_tune <- function(data, ...) {\n cli_abort(\"No {.fn fortify_matrix} method for {.obj_type_friendly {data}}\")\n}\n\n#' @export\nfortify_data_frame.ggalign_tune <- function(data, ...) {\n cli_abort(\n \"No {.fn fortify_data_frame} method for {.obj_type_friendly {data}}\"\n )\n}\n"], ["/ggalign/R/object-name.R", "format_object_name <- function(name, format = NULL) {\n if (is.null(format)) {\n name\n } else {\n sprintf(\"{.%s %s}\", format, name)\n }\n}\n\nobject_name <- function(object, format) UseMethod(\"object_name\")\n\n#' @export\nobject_name.StackLayout <- function(object, format = \"fn\") {\n ans <- format_object_name(object@name, format)\n if (!is.null(position <- .subset2(object@heatmap, \"position\"))) {\n ans <- sprintf(\"the %s annotation %s\", position, ans)\n } else {\n ans <- sprintf(\"the %s %s\", object@direction, ans)\n }\n ans\n}\n\n#' @export\nobject_name.CircleLayout <- function(object, format = \"fn\") {\n format_object_name(object@name, format)\n}\n\n#' @export\nobject_name.QuadLayout <- function(object, format = \"fn\") {\n format_object_name(object@name, format)\n}\n\n#' @export\nobject_name.CraftBox <- function(object, format = \"fn\") {\n object_name(object@craftsman, format)\n}\n\n#' @export\nobject_name.Craftsman <- function(object, format = \"fn\") {\n format_object_name(snake_class(object), format)\n}\n\n#' @export\nobject_name.AlignGg <- function(object, format = \"fn\") {\n format_object_name(\"ggalign\", format)\n}\n\n#' @export\nobject_name.CrossGg <- function(object, format = \"fn\") {\n format_object_name(\"ggcross\", format)\n}\n\n#' @export\nobject_name.FreeGg <- function(object, format = \"fn\") {\n format_object_name(\"ggfree\", format)\n}\n\n#' @export\nobject_name.MarkGg <- function(object, format = \"fn\") {\n format_object_name(\"ggmark\", format)\n}\n"], ["/ggalign/R/rasterise.R", "rasterise.QuadLayout <- function(input, ...) {\n input@plot <- ggrastr::rasterise(input = input@plot, ...)\n for (position in .TLBR) {\n stack <- slot(input, position)\n if (is.null(stack)) next\n slot(input, position) <- ggrastr::rasterise(input = stack, ...)\n }\n input\n}\n\nrasterise.ChainLayout <- function(input, ...) {\n input@plot_list <- lapply(input@plot_list, ggrastr::rasterise, ...)\n input\n}\n\nrasterise.CraftBox <- function(input, ...) {\n if (!is.null(plot <- input@plot)) {\n input@plot <- ggrastr::rasterise(input = plot, ...)\n }\n input\n}\n\n##########################################################\n#' @export\nraster_magick0.QuadLayout <- function(x, ...) {\n x@plot <- raster_magick0(x = x@plot, ...)\n for (position in .TLBR) {\n stack <- slot(x, position)\n if (is.null(stack)) next\n slot(x, position) <- raster_magick0(x = stack, ...)\n }\n x\n}\n\n#' @export\nraster_magick0.ChainLayout <- function(x, ...) {\n x@plot_list <- lapply(x@plot_list, raster_magick0, ...)\n x\n}\n\n\n#' @export\nraster_magick0.CraftBox <- function(x, ...) {\n if (!is.null(plot <- input@plot)) {\n input@plot <- raster_magick0(x = plot, ...)\n }\n input\n}\n"], ["/ggalign/R/ggalign-package.R", "#' @keywords internal\n\"_PACKAGE\"\n\n## usethis namespace: start\n#' @import vctrs\n#' @importFrom lifecycle deprecated\n#' @importFrom rlang .data .env\n#' @importFrom cli cli_abort cli_warn cli_inform\n## usethis namespace: end\nNULL\n\n# enable usage of @name in package code\n#' @rawNamespace if (getRversion() < \"4.3.0\") importFrom(\"S7\", \"@\")\nNULL\n"], ["/ggalign/R/zzz.R", "#' @importFrom S7 methods_register\n.onLoad <- function(libname, pkgname) {\n # register ggplot2 theme elements\n theme_elements()\n\n # register method for\n s3_register(\"ggrastr::rasterise\", \"CraftBox\")\n s3_register(\"ggrastr::rasterise\", \"QuadLayout\")\n s3_register(\"ggrastr::rasterise\", \"ChainLayout\")\n\n methods_register()\n invisible()\n}\n"]], "task_instance_info": {"created_time": "2025-08-21 01:14:24", "created_task_model": "DeepSeek-R1", "function_skeleton": "function(self, layout) {}", "code_description": "This code segment functions to: Synchronize group configuration with visualization layout by validating observation counts and ensuring data structure compatibility through size matching checks and dynamic property assignment."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```r\n[TASK_BEGIN]\nfunction(self, layout) {\n group_fct <- factor(self$group, levels = unique(self$group))\n layout <- dplyr::mutate(layout, .group = group_fct[COL])\n layout <- dplyr::arrange(layout, PANEL, .group, COL)\n layout <- dplyr::select(layout, -.group)\n layout\n}\n[TASK_END]\n```", "inference_time": "2025-08-21 01-15-18"}, "editdistance_info": {"edit_distance": 14.1414, "calculate_time": "2025-08-21 01:15:18", "true_code_clean": "function(self, layout) {\n layout <- ggproto_parent(CraftAlign, self)$interact_layout(layout)\n if (is.null(layout_nobs <- .subset2(layout@design, \"nobs\"))) {\n layout@design[\"nobs\"] <- list(vec_size(self$group))\n } else {\n assert_mismatch_nobs(\n self, layout_nobs, vec_size(self$group),\n arg = \"group\"\n )\n }\n layout\n }", "predict_code_clean": "function(self, layout) {\n group_fct <- factor(self$group, levels = unique(self$group))\n layout <- dplyr::mutate(layout, .group = group_fct[COL])\n layout <- dplyr::arrange(layout, PANEL, .group, COL)\n layout <- dplyr::select(layout, -.group)\n layout\n}"}} {"repo_name": "ggalign", "file_name": "/ggalign/R/import-standalone-purrr.R", "inference_info": {"prefix_code": "# Standalone file: do not edit by hand\n# Source: \n# ----------------------------------------------------------------------\n#\n# ---\n# repo: Yunuuuu/standalone\n# file: standalone-purrr.R\n# last-updated: 2024-11-13\n# license: https://unlicense.org\n# ---\n\n# This file provides a minimal shim to provide a purrr-like API on top of\n# base R functions. They are not drop-in replacements but allow a similar style\n# of programming.\n#\n# Note: these functions won't support lambda syntax.\n\n# ## Changelog\n# 2024-11-13:\n# rename `transpose()` to `list_transpose()`\n#\n# 2024-11-12:\n# First release\n#\n# nocov start\n\nmap <- function(.x, .f, ...) lapply(.x, .f, ...)\n\nwalk <- function(.x, .f, ...) {\n lapply(.x, .f, ...)\n invisible(.x)\n}\n\nmap_lgl <- function(.x, .f, ...) {\n vapply(X = .x, FUN = .f, logical(1L), ...)\n}\n\nmap_int <- function(.x, .f, ...) {\n vapply(X = .x, FUN = .f, integer(1L), ...)\n}\n\nmap_dbl <- function(.x, .f, ...) {\n vapply(X = .x, FUN = .f, double(1L), ...)\n}\n\nmap_chr <- function(.x, .f, ...) {\n vapply(X = .x, FUN = .f, character(1L), ...)\n}\n\npmap <- function(.l, .f, ...) {\n out <- .mapply(.f, .l, list(...))\n if (!is.null(nms <- names(.subset2(.l, 1L)))) names(out) <- nms\n out\n}\n\npmap_lgl <- function(.l, .f, ...) {\n .purrr_pmap_mold(.l, .f, ..., mold = logical(1L))\n}\n\npmap_int <- function(.l, .f, ...) {\n .purrr_pmap_mold(.l, .f, ..., mold = integer(1L))\n}\n\npmap_dbl <- function(.l, .f, ...) {\n .purrr_pmap_mold(.l, .f, ..., mold = double(1L))\n}\n\npmap_chr <- function(.l, .f, ...) {\n .purrr_pmap_mold(.l, .f, ..., mold = character(1L))\n}\n\n.purrr_pmap_mold <- function(.l, .f, ..., mold) {\n nms <- names(.subset2(.l, 1L))\n dots <- list(...)\n out <- vapply(seq_along(nms), function(i) {\n do.call(.f, args = c(lapply(.l, .subset2, i), dots))\n }, mold, USE.NAMES = FALSE)\n if (!is.null(nms)) names(out) <- nms\n out\n}\n\nmap2 <- function(.x, .y, .f, ...) pmap(list(.x, .y), .f, ...)\n\nmap2_lgl <- function(.x, .y, .f, ...) {\n .purrr_pmap_mold(list(.x, .y), .f, ..., mold = logical(1L))\n}\n\nmap2_int <- function(.x, .y, .f, ...) {\n .purrr_pmap_mold(list(.x, .y), .f, ..., mold = integer(1L))\n}\n\nmap2_dbl <- function(.x, .y, .f, ...) {\n .purrr_pmap_mold(list(.x, .y), .f, ..., mold = double(1L))\n}\n\nmap2_chr <- function(.x, .y, .f, ...) {\n .purrr_pmap_mold(list(.x, .y), .f, ..., mold = character(1L))\n}\n\nimap <- function(.x, .f, ...) {\n nms <- names(.x)\n if (is.null(nms)) {\n .l <- list(.x, seq_along(.x))\n } else {\n .l <- list(.x, nms)\n }\n pmap(.l, .f, ...)\n}\n\n.purrr_imap_mold <- function(.x, .f, ..., mold) {\n if (is.null(nms <- names(.x))) {\n .l <- list(.x, seq_along(.x))\n } else {\n .l <- list(.x, nms)\n }\n .purrr_pmap_mold(.l, .f, ..., mold = mold)\n}\n\nimap_lgl <- function(.l, .f, ...) {\n .purrr_imap_mold(.l, .f, ..., mold = logical(1L))\n}\n\nimap_int <- function(.l, .f, ...) {\n .purrr_imap_mold(.l, .f, ..., mold = integer(1L))\n}\n\nimap_dbl <- function(.l, .f, ...) {\n .purrr_imap_mold(.l, .f, ..., mold = double(1L))\n}\n\nimap_chr <- function(.l, .f, ...) {\n .purrr_imap_mold(.l, .f, ..., mold = character(1L))\n}\n\nlist_transpose <- ", "suffix_code": "\n\n# nocov end\n", "middle_code": "function(.l) {\n if (!length(.l)) return(.l) \n inner_names <- names(.subset2(.l, 1L))\n if (is.null(inner_names)) {\n fields <- seq_along(.subset2(.l, 1L))\n } else {\n fields <- inner_names\n names(fields) <- fields\n .l <- lapply(.l, function(x) {\n if (is.null(names(x))) names(x) <- inner_names \n x\n })\n }\n .l <- lapply(.l, as.list)\n lapply(fields, function(i) lapply(.l, .subset2, i))\n}", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "r", "sub_task_type": null}, "context_code": [["/ggalign/R/import-standalone-tibble.R", "# Standalone file: do not edit by hand\n# Source: https://github.com/Yunuuuu/standalone/blob/HEAD/R/standalone-tibble.R\n# Generated by: usethis::use_standalone(\"Yunuuuu/standalone\", \"tibble\")\n# ----------------------------------------------------------------------\n#\n# ---\n# repo: Yunuuuu/standalone\n# file: standalone-tibble.R\n# last-updated: 2024-11-14\n# license: https://unlicense.org\n# imports: [vctrs (>= 0.5.0), rlang]\n# ---\n\n# when developing R package, instead of depending on `dplyr`, `tidyr`, `tibble`.\n# we prefer use the basic function from `vctrs`\n#\n# Note: these functions won't check arguments\n#\n# Since `vctrs` also depends on `rlang` and `cli`, it has no harm to use\n# function from `rlang` and `cli`.\n#\n# Please initialize the package docs and import vctrs\n# 1. run `usethis::use_package_doc()`\n# 2. in package docs, please add #' @import vctrs\n\n# ## Changelog\n# 2025-03-12\n# - Added `case_when()`\n#\n# 2024-11-14\n# - Added `column_to_rownames()`\n#\n# 2024-11-13\n# - fix wrong results in `coalesce()`: we should assign value in the missing\n# index\n#\n# 2024-11-12\n# - Added `rename`\n# - coalesce() now will return value immediately when no missing value exists.\n#\n# 2024-11-11:\n# - Added `inner_join`\n# - Added `left_join`\n# - Added `right_join`\n# - Added `cross_join`\n# - Added `replace_na`\n# - Added `coalesce`\n# - Added `deframe`\n# - Added `enframe`\n# - Added `remove_rownames`\n# - Added `rownames_to_column`\n#\n# 2024-11-10:\n# - Added `full_join`\n# - Added `if_else`\n#\n# nocov start\n\n#' @importFrom rlang set_names\nfull_join <- function(\n x,\n y,\n by = vec_set_intersect(names(x), names(y)),\n by.x = by,\n by.y = by,\n suffix = c(\".x\", \".y\")\n) {\n loc <- vec_locate_matches(x[by.x], set_names(y[by.y], by.x), remaining = NA)\n x_slicer <- .subset2(loc, \"needles\")\n y_slicer <- .subset2(loc, \"haystack\")\n ans <- join_bind(\n vec_slice(x, x_slicer),\n # drop duplicated join column\n vec_slice(y[vec_set_difference(names(y), by.y)], y_slicer),\n suffix = suffix\n )\n new_rows <- which(vec_detect_missing(x_slicer)) # should come from `y`\n if (length(new_rows)) {\n ans[new_rows, by.x] <- vec_slice(y[by.y], y_slicer[new_rows])\n }\n ans\n}\n\n#' @importFrom rlang set_names\ninner_join <- function(\n x,\n y,\n by = vec_set_intersect(names(x), names(y)),\n by.x = by,\n by.y = by,\n suffix = c(\".x\", \".y\")\n) {\n loc <- vec_locate_matches(\n x[by.x],\n set_names(y[by.y], by.x),\n no_match = \"drop\"\n )\n x_slicer <- .subset2(loc, \"needles\")\n y_slicer <- .subset2(loc, \"haystack\")\n join_bind(\n vec_slice(x, x_slicer),\n # drop duplicated join column\n vec_slice(y[vec_set_difference(names(y), by.y)], y_slicer),\n suffix = suffix\n )\n}\n\n#' @importFrom rlang set_names\nleft_join <- function(\n x,\n y,\n by = vec_set_intersect(names(x), names(y)),\n by.x = by,\n by.y = by,\n suffix = c(\".x\", \".y\")\n) {\n loc <- vec_locate_matches(x[by.x], set_names(y[by.y], by.x))\n x_slicer <- .subset2(loc, \"needles\")\n y_slicer <- .subset2(loc, \"haystack\") # can have NA value\n join_bind(\n vec_slice(x, x_slicer),\n # drop duplicated join column\n vec_slice(y[vec_set_difference(names(y), by.y)], y_slicer),\n suffix = suffix\n )\n}\n\n#' @importFrom rlang set_names\nright_join <- function(\n x,\n y,\n by = vec_set_intersect(names(x), names(y)),\n by.x = by,\n by.y = by,\n suffix = c(\".x\", \".y\")\n) {\n loc <- vec_locate_matches(\n x[by.x],\n set_names(y[by.y], by.x),\n no_match = \"drop\",\n remaining = NA\n )\n x_slicer <- .subset2(loc, \"needles\") # can have NA value\n y_slicer <- .subset2(loc, \"haystack\")\n join_bind(\n # drop duplicated join column\n vec_slice(x[vec_set_difference(names(x), by.x)], x_slicer),\n vec_slice(y, y_slicer),\n suffix = suffix\n )\n}\n\ncross_join <- function(x, y, suffix = c(\".x\", \".y\")) {\n x_size <- vec_size(x)\n y_size <- vec_size(y)\n x_out <- vec_rep_each(x, times = y_size)\n y_out <- vec_rep(y, times = x_size)\n join_bind(x_out, y_out, suffix)\n}\n\njoin_bind <- function(x, y, suffix) {\n x_names <- names(x)\n y_names <- names(y)\n common <- vec_set_intersect(x_names, y_names)\n if (length(common)) {\n # add suffix to duplicated names\n index <- vec_match(common, x_names)\n names(x)[index] <- paste0(x_names[index], .subset(suffix, 1L))\n index <- vec_match(common, y_names)\n names(y)[index] <- paste0(y_names[index], .subset(suffix, 2L))\n }\n vec_cbind(x, y, .name_repair = \"check_unique\")\n}\n\n#' Rename elements in a list, data.frame or vector\n#'\n#' This is akin to `dplyr::rename` and `plyr::rename`. It renames elements given\n#' as names in the `replace` vector to the values in the `replace` vector\n#' without touching elements not referenced.\n#'\n#' @param x A data.frame or a named vector or list\n#' @param replace A named character vector. The names identifies the elements in\n#' `x` that should be renamed and the values gives the new names.\n#'\n#' @return `x`, with new names according to `replace`\n#' @noRd\nrename <- function(x, replace) {\n nms <- names(x)\n names(x) <- vec_assign(nms, match(names(replace), nms), replace)\n x\n}\n\nif_else <- function(condition, true, false, na = NULL) {\n # output size from `condition`\n size <- vec_size(condition)\n\n # output type from `true`/`false`/`na`\n ptype <- vec_ptype_common(true = true, false = false, na = na)\n\n args <- vec_recycle_common(\n true = true,\n false = false,\n na = na,\n .size = size\n )\n args <- vec_cast_common(!!!args, .to = ptype)\n\n out <- vec_init(ptype, size)\n\n loc_true <- condition\n loc_false <- !condition\n\n out <- vec_assign(out, loc_true, vec_slice(args$true, loc_true))\n out <- vec_assign(out, loc_false, vec_slice(args$false, loc_false))\n\n if (!is.null(na)) {\n loc_na <- vec_detect_missing(condition)\n out <- vec_assign(out, loc_na, vec_slice(args$na, loc_na))\n }\n\n out\n}\n\ncase_when <- function(.default, ..., .ptype = NULL) {\n if (is.null(.ptype)) {\n .ptype <- vec_ptype(.default)\n } else {\n .default <- vec_cast(.default, .ptype)\n }\n env <- rlang::caller_env()\n dots <- rlang::list2(...)\n unused <- vec_rep(TRUE, times = vec_size(.default))\n for (i in seq_along(dots)) {\n if (!any(unused)) {\n break\n }\n dot <- .subset2(dots, i)\n loc <- unused & rlang::eval_tidy(rlang::f_lhs(dot), env = env)\n value <- rlang::eval_tidy(rlang::f_rhs(dot), env = env)\n value <- vec_cast(value, .ptype, x_arg = sprintf(\"`...` (%d)\", i))\n if (length(value) > 1L) value <- vec_slice(value, loc)\n .default <- vec_assign(\n .default,\n loc,\n value,\n value_arg = sprintf(\"`...` (%d)\", i)\n )\n unused[loc] <- FALSE\n }\n .default\n}\n\n\n#' Replace NAs with specified values\n#' @param value A single value.\n#' @noRd\nreplace_na <- function(x, value) {\n value <- vec_cast(x = value, to = x, x_arg = \"value\", to_arg = \"x\")\n vec_assign(x, vec_detect_missing(x), value)\n}\n\n#' Find the first non-missing element\n#' @param ... A list of atomic vector (You shouldn't input `NULL`).\n#' @noRd\ncoalesce <- function(...) {\n dots <- vec_recycle_common(...)\n out <- .subset2(dots, 1L)\n for (i in 2:length(dots)) {\n if (vec_any_missing(out)) {\n missing <- vec_detect_missing(out)\n out <- vec_assign(\n out,\n missing,\n vec_slice(.subset2(dots, i), missing)\n )\n } else {\n return(out)\n }\n }\n out\n}\n\n#' Convert values to `NA`\n#' @noRd\nna_if <- function(x, y) {\n y <- vec_cast(x = y, to = x, x_arg = \"y\", to_arg = \"x\")\n y <- vec_recycle(y, size = vec_size(x), x_arg = \"y\")\n na <- vec_init(x)\n vec_assign(x, vec_equal(x, y, na_equal = TRUE), na)\n}\n\ndeframe <- function(x) {\n if (ncol(x) == 1L) {\n return(x[[1]])\n }\n vec_set_names(x[[1L]], x[[2]])\n}\n\nenframe <- function(x, name = \"name\", value = \"value\") {\n if (!is.null(names(x))) {\n data <- list(names(x), unname(x))\n } else {\n data <- list(seq_along(x), unname(x))\n }\n new_data_frame(vec_set_names(data, c(name, value)))\n}\n\nremove_rownames <- function(.data) {\n rownames(.data) <- NULL\n .data\n}\n\nrownames_to_column <- function(.data, var = \"rowname\") {\n if (!is.null(var_col <- rownames(.data))) {\n nms <- names(.data)\n .data[[var]] <- var_col\n .data <- .data[c(var, nms)]\n }\n .data\n}\n\ncolumn_to_rownames <- function(.data, var = 1L) {\n rownames(.data) <- .subset2(.data, var)\n .data[[var]] <- NULL\n .data\n}\n\n# nocov end\n"], ["/ggalign/R/pair-links.R", "#' Helper function to create pairs of observation groups\n#'\n#' @description\n#' [`ggmark()`] and [`cross_link()`] allow users to add links between\n#' observations. These functions help define the linked observations. The\n#' selected pairs will either be linked together, or each group in the pair will\n#' be linked separately to the same plot area.\n#'\n#' - `pair_links`: Helper function to create pairs of observation groups.\n#' - `range_link`: Helper function to create a range of observations.\n#'\n#' @param ... <[dyn-dots][rlang::dyn-dots]> A list of formulas, where each side\n#' of the formula should be an `integer` or `character` index of the original\n#' data, or a `range_link()` object defining the linked observations. Use\n#' `NULL` to indicate no link on that side. You can also combine these by\n#' wrapping them into a single `list()`. If only the left-hand side of the\n#' formula exists, you can input it directly. For integer indices, wrap them\n#' with [`I()`] to use the ordering from the layout. You can also use\n#' [`waiver()`][ggplot2::waiver()] to inherit values from the other group.\n#' @param .handle_missing A string of `r oxford_or(c(\"error\", \"remove\"))`\n#' indicates the action for handling missing observations.\n#' @param .reorder A string of `r oxford_or(c(\"hand1\", \"hand2\"))` indicating\n#' whether to reorder the input links to follow the specified layout ordering.\n#' @examples\n#' x <- pair_links(\n#' # group on the left hand only\n#' c(\"a\", \"b\"),\n#' # normally, integer index will be interpreted as the index of the\n#' # origianl data\n#' 1:2,\n#' # wrapped with `I()` indicate` the integer index is ordering of the\n#' # layout\n#' I(1:2),\n#' range_link(1, 6),\n#' range_link(\"a\", \"b\"),\n#' # group on the right hand only\n#' ~ 1:2,\n#' ~ c(\"a\", \"b\"),\n#' ~ range_link(1, 6),\n#' # group on the both side\n#' range_link(1, 6) ~ c(\"a\", \"b\"),\n#' # waiver() indicates the right hand is the same of the left hand\n#' range_link(1, 6) ~ waiver(),\n#' # the same for the left hand\n#' waiver() ~ 1:2,\n#' ~NULL # an empty link\n#' )\n#' x\n#'\n#' # we can modify it as usual list\n#' x[[1]] <- NULL # remove the first link\n#' x$a <- ~LETTERS\n#' x\n#'\n#' # modify with a list\n#' x[1:2] <- list(~ c(\"a\", \"b\"), ~ range_link(\"a\", \"b\"))\n#' x\n#' @export\npair_links <- function(..., .handle_missing = \"error\", .reorder = NULL) {\n .handle_missing <- arg_match0(.handle_missing, c(\"error\", \"remove\"))\n if (!is.null(.reorder)) {\n .reorder <- arg_match0(.reorder, c(\"hand1\", \"hand2\"))\n }\n pairs <- rlang::dots_list(..., .ignore_empty = \"all\", .named = NULL)\n new_pair_links(\n lapply(pairs, as_pair_link, x_arg = \"...\", call = current_call()),\n handle_missing = .handle_missing, reorder = .reorder\n )\n}\n\nnew_pair_links <- function(x = list(), ..., class = character()) {\n new_vctr(x, ..., class = c(class, \"ggalign_pair_links\"))\n}\n\n#' @export\nobj_print_header.ggalign_pair_links <- function(x, ...) {\n cat(\"<\", vec_ptype_full(x), \">\", \"\\n\", sep = \"\")\n cat(\n sprintf(\n \"A total of %d pair%s of link groups\",\n vec_size(x), if (vec_size(x) > 1L) \"s\" else \"\"\n ),\n \"\\n\",\n sep = \"\"\n )\n invisible(x)\n}\n\n#' @export\nobj_print_data.ggalign_pair_links <- function(x, ...) {\n if (vec_size(x) > 0L) {\n hand1 <- vapply(x, function(hand) {\n deparse_link(hand, ..., hand = \"hand1\")\n }, character(1L), USE.NAMES = FALSE)\n hand2 <- vapply(x, function(hand) {\n deparse_link(hand, ..., hand = \"hand2\")\n }, character(1L), USE.NAMES = FALSE)\n nms <- c(\"\", paste0(names_or_index(x), \": \"))\n nms <- format(nms, justify = \"right\")\n empty <- character(vec_size(hand2))\n empty[hand1 == \"\" & hand2 == \"\"] <- \" \"\n empty <- format(c(\"\", empty), justify = \"left\")\n hand1 <- format(c(\"hand1\", hand1), justify = \"right\")\n hand2 <- format(c(\"hand2\", hand2), justify = \"left\")\n cat(\"\\n\")\n cat(paste0(\" \", nms, hand1, \" ~ \", hand2, empty), sep = \"\\n\")\n cat(\"\\n\")\n }\n invisible(x)\n}\n\n#' @export\nobj_print_footer.ggalign_pair_links <- function(x, ...) {\n NextMethod()\n # `lengths`: will call `length.ggalign_pair_link()` method\n n <- sum(lengths(x, use.names = FALSE))\n cat(\n sprintf(\n \"A total of %d link group%s\", n,\n if (n > 1L) \"s\" else \"\"\n ),\n \"\\n\",\n sep = \"\"\n )\n invisible(x)\n}\n\n#' @export\n`[<-.ggalign_pair_links` <- function(x, i, value) {\n value <- lapply(value, as_pair_link, x_arg = \"value\", call = current_call())\n NextMethod()\n}\n\n#' @export\n`[[<-.ggalign_pair_links` <- function(x, i, value) {\n # let `NULL` to remove the link\n if (!is.null(value)) value <- as_pair_link(value)\n NextMethod()\n}\n\n#' @export\n`$<-.ggalign_pair_links` <- function(x, i, value) {\n # let `NULL` to remove the link\n if (!is.null(value)) value <- as_pair_link(value)\n NextMethod()\n}\n\n#' @export\nvec_ptype2.ggalign_pair_links.list <- function(x, y, ...) {\n x\n}\n\n#' @export\nvec_ptype2.list.ggalign_pair_links <- function(x, y, ...) {\n y\n}\n\n#' @export\nvec_cast.ggalign_pair_links.list <- function(x, to, ...,\n x_arg = caller_arg(x),\n to_arg = \"\",\n call = caller_env()) {\n new_pair_links(lapply(x, as_pair_link, x_arg = x_arg, call = call))\n}\n\n#########################################################\n#' @param point1,point2 A single integer or character index, defining the lower\n#' and higher bounds of the range. For integer indices, wrap them with [`I()`]\n#' to indicate the ordered index by the layout.\n#' @export\n#' @rdname pair_links\nrange_link <- function(point1, point2) {\n if (!is_scalar(point1) ||\n (!is.character(point1) && !is.numeric(point1))) {\n cli_abort(\"{.arg point1} must be a single numeric or character index\")\n }\n if (!is_scalar(point2) ||\n (!is.character(point2) && !is.numeric(point2))) {\n cli_abort(\"{.arg point2} must be a single numeric or character index\")\n }\n point1 <- as_obs_link(point1)\n point2 <- as_obs_link(point2)\n structure(list(point1 = point1, point2 = point2),\n class = \"ggalign_range_link\"\n )\n}\n\nis_range_link <- function(x) inherits(x, \"ggalign_range_link\")\n\n########################################################\nnew_pair_link <- function(hand1 = NULL, hand2 = NULL,\n ..., class = character()) {\n structure(\n .Data = list(hand1 = hand1, hand2 = hand2),\n ...,\n class = c(class, \"ggalign_pair_link\")\n )\n}\n\n#' @export\nvec_proxy.ggalign_pair_link <- function(x, ...) x\n\n#' @export\nprint.ggalign_pair_link <- function(x, ...) obj_print(x, ...)\n\n#' @export\nobj_print_header.ggalign_pair_link <- function(x, ...) {\n cat(sprintf(\"<%s>\", vec_ptype_full(x)), \"\\n\", sep = \"\")\n invisible(x)\n}\n\n#' @export\nobj_print_data.ggalign_pair_link <- function(x, ...) {\n if (length(x) > 0L) {\n cat(c(\n sprintf(\" hand1: %s\", deparse_link(.subset2(x, \"hand1\"), ...)),\n sprintf(\" hand2: %s\", deparse_link(.subset2(x, \"hand2\"), ...))\n ), sep = \"\\n\")\n }\n invisible(x)\n}\n\n#' @param x A `ggalign_pair_link` object.\n#' @noRd\n#' @export\nlength.ggalign_pair_link <- function(x) {\n sum(!vapply(x, is.null, logical(1L), USE.NAMES = FALSE))\n}\n\n##################################################\n#' @export\nvec_ptype2.ggalign_pair_link.ggalign_pair_link <- function(x, y, ...) {\n x\n}\n\n#' @export\nvec_ptype2.ggalign_pair_link.NULL <- function(x, y, ...) {\n x\n}\n\n#' @export\nvec_ptype2.NULL.ggalign_pair_link <- function(x, y, ...) {\n y\n}\n\n#' @export\nvec_ptype2.ggalign_pair_link.numeric <- function(x, y, ...) {\n x\n}\n\n#' @export\nvec_ptype2.numeric.ggalign_pair_link <- function(x, y, ...) {\n y\n}\n\n#' @export\nvec_ptype2.ggalign_pair_link.integer <- function(x, y, ...) {\n x\n}\n\n#' @export\nvec_ptype2.integer.ggalign_pair_link <- function(x, y, ...) {\n y\n}\n\n#' @export\nvec_ptype2.ggalign_pair_link.double <- function(x, y, ...) {\n x\n}\n\n#' @export\nvec_ptype2.double.ggalign_pair_link <- function(x, y, ...) {\n y\n}\n\n#' @export\nvec_ptype2.ggalign_pair_link.character <- function(x, y, ...) {\n x\n}\n\n#' @export\nvec_ptype2.character.ggalign_pair_link <- function(x, y, ...) {\n y\n}\n\n#' @export\nvec_ptype2.ggalign_pair_link.formula <- function(x, y, ...) {\n x\n}\n\n#' @export\nvec_ptype2.formula.ggalign_pair_link <- function(x, y, ...) {\n y\n}\n\n#' @export\nvec_ptype2.ggalign_pair_link.waiver <- function(x, y, ...) {\n x\n}\n\n#' @export\nvec_ptype2.waiver.ggalign_pair_link <- function(x, y, ...) {\n y\n}\n\n#' @export\nvec_ptype2.ggalign_pair_link.ggalign_range_link <- function(x, y, ...) {\n x\n}\n\n#' @export\nvec_ptype2.ggalign_range_link.ggalign_pair_link <- function(x, y, ...) {\n y\n}\n\n#' @export\nvec_ptype2.ggalign_pair_link.AsIs <- function(x, y, ...) {\n vec_ptype2(x, remove_class(y, \"AsIs\"), ...)\n}\n\n#' @export\nvec_ptype2.AsIs.ggalign_pair_link <- function(x, y, ...) {\n vec_ptype2(remove_class(x, \"AsIs\"), y, ...)\n}\n\n#' @export\nvec_ptype2.ggalign_pair_link.list <- function(x, y, ...) {\n x\n}\n\n#' @export\nvec_ptype2.list.ggalign_pair_link <- function(x, y, ...) {\n y\n}\n\n#############################################################\n#' @export\nvec_cast.ggalign_pair_link.numeric <- function(x, to, ...,\n x_arg = caller_arg(x),\n to_arg = \"\",\n call = caller_env()) {\n new_pair_link(as_obs_link(x, arg = x_arg, call = call))\n}\n\n#' @export\nvec_cast.ggalign_pair_link.double <- vec_cast.ggalign_pair_link.numeric\n\n#' @export\nvec_cast.ggalign_pair_link.integer <- vec_cast.ggalign_pair_link.numeric\n\n#' @export\nvec_cast.ggalign_pair_link.character <- vec_cast.ggalign_pair_link.numeric\n\n#' @export\nvec_cast.ggalign_pair_link.ggalign_range_link <-\n vec_cast.ggalign_pair_link.integer\n\n#' @export\nvec_cast.ggalign_pair_link.list <- vec_cast.ggalign_pair_link.numeric\n\n#' @export\nvec_cast.ggalign_pair_link.AsIs <- function(x, to, ...,\n x_arg = caller_arg(x),\n to_arg = \"\",\n call = caller_env()) {\n I(vec_cast(\n remove_class(x, \"AsIs\"),\n to = to, ...,\n x_arg = x_arg, call = call\n ))\n}\n\n#' @export\nvec_cast.ggalign_pair_link.formula <- function(x, to, ...,\n x_arg = caller_arg(x),\n to_arg = \"\",\n call = caller_env()) {\n hand1 <- rlang::eval_tidy(rlang::f_lhs(x), env = rlang::f_env(x))\n hand1 <- as_obs_link(hand1, arg = x_arg, call = call)\n hand2 <- rlang::eval_tidy(rlang::f_rhs(x), env = rlang::f_env(x))\n hand2 <- as_obs_link(hand2, arg = x_arg, call = call)\n new_pair_link(hand1, hand2)\n}\n\nas_pair_link <- function(x, ...) {\n if (is.null(x)) { # vec_cast() cannot convert `NULL`\n new_pair_link()\n } else {\n vec_cast(x, to = new_pair_link(), ...)\n }\n}\n\n########################################################\nas_obs_link <- function(x, ..., arg = caller_arg(x), call = caller_env()) {\n UseMethod(\"as_obs_link\")\n}\n\n#' @export\nas_obs_link.NULL <- function(x, ...) x\n\n#' @export\nas_obs_link.AsIs <- function(x, ...) {\n I(as_obs_link(remove_class(x, \"AsIs\"), ...))\n}\n\n#' @export\nas_obs_link.numeric <- function(x, ..., arg = caller_arg(x),\n call = caller_env()) {\n vec_cast(x, integer(), x_arg = arg, call = call)\n}\n\n#' @export\nas_obs_link.integer <- as_obs_link.NULL\n\n#' @export\nas_obs_link.double <- as_obs_link.numeric\n\n#' @export\nas_obs_link.character <- function(x, ..., arg = caller_arg(x),\n call = caller_env()) {\n if (any(x == \"\")) {\n cli_abort(\"empty string is not allowed\", call = call)\n }\n x\n}\n\n#' @export\nas_obs_link.waiver <- as_obs_link.NULL\n\n#' @export\nas_obs_link.list <- function(x, ..., arg = caller_arg(x),\n call = caller_env()) {\n x <- x[!vapply(x, is.null, logical(1L), USE.NAMES = FALSE)]\n if (is_empty(x)) return(NULL) # styler: off\n lapply(x, as_obs_link, arg = arg, call = call)\n}\n\n#' @export\nas_obs_link.ggalign_range_link <- as_obs_link.NULL\n\n#' @export\nas_obs_link.default <- function(x, ..., arg = caller_arg(x),\n call = caller_env()) {\n stop_incompatible_cast(\n x, new_pair_link(),\n x_arg = arg, to_arg = \"\",\n call = call\n )\n}\n\n#' @export\nprint.ggalign_range_link <- function(x, ...) {\n cat(deparse_link(x))\n invisible(x)\n}\n\n###########################################################\n#' @return A single string\n#' @noRd\ndeparse_link <- function(x, ...) deparse_link2(x, ...) %||% \"\"\n\n#' @return A single string or `NULL`\n#' @noRd\ndeparse_link2 <- function(x, ...) UseMethod(\"deparse_link2\")\n\n# Basic object\n#' @export\ndeparse_link2.integer <- function(x, trunc = 3L, head = trunc - 1L,\n tail = 1L, ...) {\n l <- length(x)\n ans <- paste(\n deparse(x, control = c(\"keepNA\", \"niceNames\", \"showAttributes\")),\n collapse = \" \"\n )\n if (l > trunc && startsWith(ans, \"c\")) {\n ans <- sprintf(\"c(%s)\", paste(c(\n x[seq_len(head)], \"...\", x[seq.int(l - tail + 1L, l)]\n ), collapse = \", \"))\n }\n ans\n}\n\n#' @export\ndeparse_link2.character <- function(x, trunc = 3L, head = trunc - 1L,\n tail = 1L, ...) {\n l <- length(x)\n if (l <= trunc) {\n ans <- paste(deparse(x), collapse = \" \")\n } else {\n ans <- sprintf(\"c(%s)\", paste(c(\n x[seq_len(head)], \"...\", x[seq.int(l - tail + 1L, l)]\n ), collapse = \", \"))\n }\n ans\n}\n\n#' @export\ndeparse_link2.waiver <- function(x, ...) \"waiver()\"\n\n#' @export\ndeparse_link2.NULL <- function(x, ...) NULL\n\n# To allow `I()` to be used to the whole formula, we must define the method for\n# this, though `ggalign_pair_link` shouldn't be considered as an observation\n#' @export\ndeparse_link2.ggalign_pair_link <- function(x, ..., hand) {\n deparse_link2(.subset2(x, hand), ...)\n}\n\n#' @export\ndeparse_link2.AsIs <- function(x, ...) {\n ans <- deparse_link2(remove_class(x, \"AsIs\"), ...)\n if (!is.null(ans)) ans <- sprintf(\"I(%s)\", ans)\n ans\n}\n\n# Recurse version\n#' @export\ndeparse_link2.ggalign_range_link <- function(x, ...) {\n sprintf(\n \"range_link(%s, %s)\",\n deparse_link(.subset2(x, \"point1\"), ...),\n deparse_link(.subset2(x, \"point2\"), ...)\n )\n}\n\n#' @export\ndeparse_link2.list <- function(x, trunc = 3L, head = trunc - 1L,\n tail = 1L, ...) {\n l <- length(x)\n if (l <= trunc) {\n ans <- vapply(x, deparse_link, character(1L), ...,\n trunc = trunc, head = head, tail = tail,\n USE.NAMES = FALSE\n )\n } else {\n ans <- c(\n vapply(x[seq_len(head)],\n deparse_link, character(1L), ...,\n trunc = trunc, head = head, tail = tail,\n USE.NAMES = FALSE\n ),\n \"...\",\n vapply(x[seq.int(l - tail + 1L, l)],\n deparse_link, character(1L), ...,\n trunc = trunc, head = head, tail = tail,\n USE.NAMES = FALSE\n )\n )\n }\n sprintf(\"list(%s)\", paste(ans, collapse = \", \"))\n}\n\n###################################################\nmake_links_data <- function(links, design1, design2,\n labels1, labels2) {\n link_index_list <- lapply(\n links, make_pair_link_index,\n design1 = design1, design2 = design2,\n labels1 = labels1, labels2 = labels2,\n handle_missing = attr(links, \"handle_missing\")\n )\n names(link_index_list) <- names_or_index(links)\n if (!is.null(reorder <- attr(links, \"reorder\"))) {\n index <- vapply(link_index_list, function(link_index) {\n if (is.null(link_index) ||\n is.null(index <- .subset2(link_index, reorder))) {\n NA_integer_\n } else {\n vec_slice(index, 1L)\n }\n }, integer(1L), USE.NAMES = FALSE)\n link_index_list <- link_index_list[order(index)]\n }\n link_index_list\n}\n\nmake_pair_link_index <- function(pair_link, design1, design2,\n labels1, labels2, handle_missing) {\n input1 <- .subset2(pair_link, 1L)\n input2 <- .subset2(pair_link, 2L)\n\n # make the data\n hand1 <- make_link_index(input1,\n design = design1, labels = labels1,\n other = input2, data_index = !inherits(pair_link, \"AsIs\"),\n handle_missing = handle_missing\n )\n hand2 <- make_link_index(input2,\n design = design2, labels = labels2,\n other = input1, data_index = !inherits(pair_link, \"AsIs\"),\n handle_missing = handle_missing\n )\n if (is.null(hand1) && is.null(hand2)) {\n return(NULL)\n }\n list(hand1 = hand1, hand2 = hand2)\n}\n\nmake_link_index <- function(link, design, labels, other, data_index,\n handle_missing, arg = caller_arg(link),\n call = caller_call()) {\n link <- link_to_location(\n link,\n n = .subset2(design, \"nobs\"),\n labels = labels,\n index = .subset2(design, \"index\"),\n other = other,\n data_index = data_index,\n handle_missing = handle_missing,\n arg = arg, call = call\n )\n if (is_empty(link)) {\n return(NULL)\n }\n # always use integer, otherwise, will cause error when drawing\n # due to loss of precision, I don't know why, it should be integer already?\n vec_unique(vec_cast(link, integer()))\n}\n\nlink_to_location <- function(x, ...) UseMethod(\"link_to_location\")\n\n#' @export\nlink_to_location.AsIs <- function(x, ..., data_index) {\n link_to_location(remove_class(x, \"AsIs\"), ..., data_index = FALSE)\n}\n\n#' @export\nlink_to_location.character <- function(x, ..., n, labels, index, handle_missing,\n arg = caller_arg(x),\n call = caller_call()) {\n if (identical(handle_missing, \"remove\") && !is.null(labels)) {\n x <- x[x %in% labels]\n }\n ans <- vec_as_location(x, n = n, names = labels, arg = arg, call = call)\n match(ans, index) # character always match the original data\n}\n\n#' @export\nlink_to_location.integer <- function(x, ..., n, index, data_index,\n handle_missing, arg = caller_arg(x),\n call = caller_call()) {\n ans <- num_as_location(x,\n n = n,\n arg = arg, call = call,\n negative = \"error\",\n zero = \"error\",\n oob = handle_missing\n )\n # integer index by default match the original data\n if (isTRUE(data_index)) match(ans, index) else ans\n}\n\n#' @export\nlink_to_location.ggalign_range_link <- function(x, ..., arg = caller_arg(x),\n call = caller_call()) {\n point1 <- link_to_location(\n .subset2(x, \"point1\"),\n ...,\n arg = \"point1\",\n call = quote(range_link())\n )\n point2 <- link_to_location(\n .subset2(x, \"point2\"),\n ...,\n arg = \"point2\",\n call = quote(range_link())\n )\n point1:point2\n}\n\n#' @export\nlink_to_location.list <- function(x, ...) {\n unlist(lapply(x, link_to_location, ...), FALSE, FALSE)\n}\n\n#' @export\nlink_to_location.waiver <- function(x, ..., other) {\n link_to_location(other %|w|% NULL, ...)\n}\n\n#' @export\nlink_to_location.NULL <- function(x, ...) NULL\n"], ["/ggalign/R/utils.R", "# `vec_rep`\nrecycle_whole <- function(x, len) {\n out <- x %% len\n if (out == 0L) len else out\n}\n\n# `vec_rep_each`\nrecycle_each <- function(x, len) {\n (x - 1L) %/% len + 1L\n}\n\n#' @importFrom utils modifyList\nupdate_non_waive <- function(old, new, keep_null = TRUE) {\n modifyList(old,\n new[!vapply(new, is.waive, logical(1L), USE.NAMES = FALSE)],\n keep.null = keep_null\n )\n}\n\nis_s3 <- function(x) is.object(x) && !isS4(x) && !inherits(x, \"R6\")\n\n#' @importFrom rlang names2\nnames_or_index <- function(x) {\n nms <- names2(x)\n empty <- nms == \"\"\n nms[empty] <- seq_along(x)[empty]\n nms\n}\n\n#################################################################\n#' Read Example Data\n#'\n#' This function reads example data from the file. If no file is specified, it\n#' returns a list of available example files.\n#'\n#' @param file A string representing the name of the example file to be read. If\n#' `NULL`, the function will return a list of available example file names.\n#' @return If `file` is `NULL`, returns a character vector of available example\n#' file names. Otherwise, returns the contents of the specified example file,\n#' read as an R object.\n#' @examples\n#' read_example()\n#' @export\nread_example <- function(file = NULL) {\n if (is.null(file)) {\n dir(pkg_extdata())\n } else {\n readRDS(pkg_extdata(file, mustWork = TRUE))\n }\n}\n\nwith_options <- function(code, ...) {\n opts <- options(...)\n on.exit(options(opts))\n force(code)\n}\n\n#' @param ans Whether to assign the final results into the 'ans' variable.\n#' @noRd\nfn_body_append <- function(fn, ..., ans = FALSE) {\n args <- rlang::fn_fmls(fn)\n body <- rlang::fn_body(fn)\n body <- as.list(body)\n if (ans) body[[length(body)]] <- rlang::expr(ans <- !!body[[length(body)]])\n body <- as.call(c(body, rlang::enexprs(...)))\n rlang::new_function(args, body)\n}\n\n# This will work with most things but be aware that it might fail with some\n# complex objects. For example, according to `?S3Methods`, calling foo on\n# matrix(1:4, 2, 2) would try `foo.matrix`, then `foo.numeric`, then\n# `foo.default`; whereas this code will just look for `foo.matrix` and\n# `foo.default`.\n#' @importFrom utils getS3method\n#' @importFrom methods extends\nhas_method <- function(x, f, inherit = TRUE, default = inherit) {\n x_class <- class(x)\n if (inherit) {\n if (isS4(x)) x_class <- extends(x_class)\n if (default) x_class <- c(x_class, \"default\")\n } else {\n x_class <- .subset(x_class, 1L)\n }\n for (cls in x_class) {\n if (!is.null(getS3method(f, cls, optional = TRUE))) {\n return(TRUE)\n }\n }\n return(FALSE)\n}\n\n#' For functions with a `call` argument, we check if the call originates from\n#' the current package. If it does, we use the caller's call; if not, we use the\n#' current call directly. Used by `align()` and `free()`\n#' @noRd\n#' @importFrom utils packageName\noverride_call <- function(call = NULL) {\n # if no caller call\n if (is.null(call) || is.function(f <- .subset2(call, 1L))) {\n return(TRUE)\n }\n # if call from the current package\n !identical(\n packageName(environment(eval(f))),\n pkg_nm()\n )\n}\n\n# library(data.table)\n# library(vctrs)\n# `%nest_unique%` <- function(x, y) {\n# ans <- new_data_frame(list(x = x, y = y))\n# ans <- unique(ans)\n# !anyDuplicated(ans$x)\n# }\n# `%nest_vctrs%` <- function(x, y) {\n# ans <- new_data_frame(list(x = x, y = y))\n# ans <- vec_unique(ans)\n# !vec_duplicate_any(.subset2(ans, \"x\"))\n# }\n# `%nest_vctrs_loc%` <- function(x, y) {\n# # we don't check the inputs for performance\n# loc <- vec_unique_loc(new_data_frame(list(x = x, y = y)))\n# !vec_duplicate_any(vec_slice(x, loc))\n# }\n# `%nest_data_table%` <- function(x, y) {\n# ans <- data.table(x = x, y = y)\n# ans <- unique(ans)\n# !anyDuplicated(.subset2(ans, \"x\"))\n# }\n# `%nest_split%` <- function(x, y) {\n# all(lengths(lapply(split(y, x), unique)) == 1L)\n# }\n# `%nest_table%` <- function(x, y) {\n# all(rowSums(table(x, y) > 0L) == 1L)\n# }\n# foo <- rep(seq(10^4L / 2L), each = 4)\n# bar <- rep(seq(10^4L), each = 2)\n# bench::mark(\n# nest_unique = bar %nest_unique% foo,\n# nest_vctrs = bar %nest_vctrs% foo,\n# nest_vctrs_loc = bar %nest_vctrs_loc% foo,\n# nest_data_table = bar %nest_data_table% foo,\n# nest_split = bar %nest_split% foo,\n# nest_table = bar %nest_table% foo,\n# )\n#> Warning: Some expressions had a GC in every iteration; so filtering is\n#> disabled.\n#> # A tibble: 6 x 6\n#> expression min median `itr/sec` mem_alloc `gc/sec`\n#> \n#> 1 nest_unique 5.37ms 7.49ms 134. 1.33MB 69.2\n#> 2 nest_vctrs 200.3us 214.57us 3591. 754.7KB 6.00\n#> 3 nest_vctrs_loc 193.99us 207.29us 4490. 706.95KB 6.00\n#> 4 nest_data_table 402.71us 459.55us 1918. 985.25KB 4.00\n#> 5 nest_split 11.87ms 14.08ms 69.8 1.15MB 54.3\n#> 6 nest_table 183.52ms 189.87ms 5.20 576.35MB 8.67\n`%nest%` <- function(x, y) {\n # we don't check the inputs for performance\n loc <- vec_unique_loc(new_data_frame(list(x = x, y = y)))\n !vec_duplicate_any(vec_slice(x, loc))\n}\n\nsave_png <- function(code, width = 400L, height = 400L) {\n path <- tempfile(fileext = \".png\")\n grDevices::png(path, width = width, height = height)\n on.exit(grDevices::dev.off())\n print(code)\n path\n}\n\nadd_class <- function(x, ...) {\n if (is.null(x)) return(x) # styler: off\n class(x) <- vec_unique(c(..., class(x)))\n x\n}\n\nremove_class <- function(x, ...) {\n oldClass(x) <- vec_set_difference(oldClass(x), c(...))\n x\n}\n\n###########################################################\nswitch_position <- function(position, x, y) {\n switch(position,\n top = ,\n bottom = x,\n left = ,\n right = y\n )\n}\n\nto_direction <- function(position) {\n switch_position(position, \"vertical\", \"horizontal\")\n}\n\nis_vertical <- function(direction) direction == \"vertical\"\n\nis_horizontal <- function(direction) direction == \"horizontal\"\n\nswitch_direction <- function(direction, h, v) {\n if (is_horizontal(direction)) {\n h\n } else {\n v\n }\n}\n\nto_coord_axis <- function(direction) {\n switch_direction(direction, \"y\", \"x\")\n}\n\nto_matrix_axis <- function(direction) {\n switch_direction(direction, \"row\", \"column\")\n}\n\n##########################################################\ndata_frame0 <- function(...) data_frame(..., .name_repair = \"minimal\")\n\nas_data_frame0 <- function(data, ...) {\n as.data.frame(\n x = data, ...,\n make.names = FALSE,\n stringsAsFactors = FALSE,\n fix.empty.names = FALSE\n )\n}\n\nquickdf <- function(x) {\n class(x) <- \"data.frame\"\n attr(x, \"row.names\") <- .set_row_names(length(.subset2(x, 1L)))\n x\n}\n\nfct_rev <- function(x) {\n ans <- as.factor(x)\n factor(ans, levels = rev(levels(ans)))\n}\n\nreverse_trans <- function(x) sum(range(x, na.rm = TRUE)) - x\n\nfclass <- function(x) .subset(class(x), 1L)\n\nis_scalar <- function(x) length(x) == 1L\n\nis_scalar_numeric <- function(x) length(x) == 1L && is.numeric(x)\n"], ["/ggalign/R/import-standalone-obj-type.R", "# Standalone file: do not edit by hand\n# Source: https://github.com/Yunuuuu/standalone/blob/HEAD/R/standalone-obj-type.R\n# Generated by: usethis::use_standalone(\"Yunuuuu/standalone\", \"obj-type\")\n# ----------------------------------------------------------------------\n#\n# ---\n# repo: Yunuuuu/standalone\n# file: standalone-obj-type.R\n# last-updated: 2025-04-11\n# license: https://unlicense.org\n# imports: rlang (>= 1.1.0)\n# ---\n#\n# ## Changelog\n# 2025-04-11:\n# - new `allow_what_type`\n#\n# 2024-11-10:\n# - `obj_type_friendly()` gains a `length` argument to control whether to show\n# the length of the vector.\n# - `stop_input_type()` gains a `show_length` argument passed to\n# `obj_type_friendly`.\n#\n# 2024-02-14:\n# - `obj_type_friendly()` now works for S7 objects.\n#\n# 2023-05-01:\n# - `obj_type_friendly()` now only displays the first class of S3 objects.\n#\n# 2023-03-30:\n# - `stop_input_type()` now handles `I()` input literally in `arg`.\n#\n# 2022-10-04:\n# - `obj_type_friendly(value = TRUE)` now shows numeric scalars\n# literally.\n# - `stop_friendly_type()` now takes `show_value`, passed to\n# `obj_type_friendly()` as the `value` argument.\n#\n# 2022-10-03:\n# - Added `allow_na` and `allow_null` arguments.\n# - `NULL` is now backticked.\n# - Better friendly type for infinities and `NaN`.\n#\n# 2022-09-16:\n# - Unprefixed usage of rlang functions with `rlang::` to\n# avoid onLoad issues when called from rlang (#1482).\n#\n# 2022-08-11:\n# - Prefixed usage of rlang functions with `rlang::`.\n#\n# 2022-06-22:\n# - `friendly_type_of()` is now `obj_type_friendly()`.\n# - Added `obj_type_oo()`.\n#\n# 2021-12-20:\n# - Added support for scalar values and empty vectors.\n# - Added `stop_input_type()`\n#\n# 2021-06-30:\n# - Added support for missing arguments.\n#\n# 2021-04-19:\n# - Added support for matrices and arrays (#141).\n# - Added documentation.\n# - Added changelog.\n#\n# nocov start\n# Following codes were modified from `rlang` package\n\n#' @param x The object type which does not conform to `what`. Its\n#' `obj_type_friendly()` is taken and mentioned in the error message.\n#' @param show_value Passed to `value` argument of `obj_type_friendly()`.\n#' @param show_length Passed to `length` argument of `obj_type_friendly()`.\n#' @param ... Arguments passed to [abort()].\n#' @inheritParams args_error_context\n#' @importFrom rlang caller_arg caller_env abort\n#' @noRd\nstop_input_type <- function(x,\n what,\n ...,\n allow_na = FALSE,\n allow_null = FALSE,\n show_value = TRUE,\n show_length = FALSE,\n arg = caller_arg(x),\n call = caller_env()) {\n what <- allow_what_type(\n what,\n allow_na = allow_na,\n allow_null = allow_null\n )\n if (inherits(arg, \"AsIs\")) {\n format_arg <- identity\n } else {\n format_arg <- function(x) sprintf(\"`%s`\", x)\n }\n message <- sprintf(\n \"%s must be %s, not %s.\",\n format_arg(arg), what,\n obj_type_friendly(x, value = show_value, length = show_length)\n )\n abort(message, ..., call = call, arg = arg)\n}\n\n#' @param what The friendly expected type as a string. Can be a\n#' character vector of expected types, in which case the error\n#' message mentions all of them in an \"or\" enumeration.\n#' @noRd\nallow_what_type <- function(what, allow_na = FALSE, allow_null = FALSE) {\n if (allow_na) {\n what <- c(what, \"`NA`\")\n }\n if (allow_null) {\n what <- c(what, \"`NULL`\")\n }\n if (length(what)) {\n what <- .standalone_oxford_comma(what, final = \"or\")\n }\n what\n}\n\n#' Return English-friendly type\n#' @param x Any R object.\n#' @param value Whether to describe the value of `x`. Special values\n#' like `NA` or `\"\"` are always described.\n#' @param length Whether to mention the length of vectors and lists.\n#' @return A string describing the type. Starts with an indefinite\n#' article, e.g. \"an integer vector\".\n#' @importFrom rlang is_missing is_vector\n#' @noRd\nobj_type_friendly <- function(x, value = TRUE, length = FALSE) {\n if (is_missing(x)) {\n return(\"absent\")\n }\n\n if (is.object(x)) {\n if (inherits(x, \"quosure\")) {\n type <- \"quosure\"\n } else {\n type <- class(x)[[1L]]\n }\n return(sprintf(\"a <%s> object\", type))\n }\n\n if (!is_vector(x)) {\n return(.rlang_as_friendly_type(typeof(x)))\n }\n\n n_dim <- length(dim(x))\n\n if (!n_dim) {\n if (!is.list(x) && length(x) == 1) {\n if (is.na(x)) {\n return(switch(typeof(x),\n logical = \"`NA`\",\n integer = \"an integer `NA`\",\n double =\n if (is.nan(x)) {\n \"`NaN`\"\n } else {\n \"a numeric `NA`\"\n },\n complex = \"a complex `NA`\",\n character = \"a character `NA`\",\n .rlang_stop_unexpected_typeof(x)\n ))\n }\n\n show_infinites <- function(x) {\n if (x > 0) {\n \"`Inf`\"\n } else {\n \"`-Inf`\"\n }\n }\n str_encode <- function(x, width = 30, ...) {\n if (nchar(x) > width) {\n x <- substr(x, 1, width - 3)\n x <- paste0(x, \"...\")\n }\n encodeString(x, ...)\n }\n\n if (value) {\n if (is.numeric(x) && is.infinite(x)) {\n return(show_infinites(x))\n }\n\n if (is.numeric(x) || is.complex(x)) {\n number <- as.character(round(x, 2))\n what <- if (is.complex(x)) {\n \"the complex number\"\n } else {\n \"the number\"\n }\n return(paste(what, number))\n }\n\n return(switch(typeof(x),\n logical = if (x) \"`TRUE`\" else \"`FALSE`\",\n character = {\n what <- if (nzchar(x)) {\n \"the string\"\n } else {\n \"the empty string\"\n }\n paste(what, str_encode(x, quote = \"\\\"\"))\n },\n raw = paste(\"the raw value\", as.character(x)),\n .rlang_stop_unexpected_typeof(x)\n ))\n }\n\n return(switch(typeof(x),\n logical = \"a logical value\",\n integer = \"an integer\",\n double = if (is.infinite(x)) show_infinites(x) else \"a number\",\n complex = \"a complex number\",\n character = if (nzchar(x)) \"a string\" else \"\\\"\\\"\",\n raw = \"a raw value\",\n .rlang_stop_unexpected_typeof(x)\n ))\n }\n\n if (length(x) == 0) {\n return(switch(typeof(x),\n logical = \"an empty logical vector\",\n integer = \"an empty integer vector\",\n double = \"an empty numeric vector\",\n complex = \"an empty complex vector\",\n character = \"an empty character vector\",\n raw = \"an empty raw vector\",\n list = \"an empty list\",\n .rlang_stop_unexpected_typeof(x)\n ))\n }\n }\n\n vec_type_friendly(x, length = length)\n}\n\n#' @importFrom rlang is_vector abort\nvec_type_friendly <- function(x, length = FALSE) {\n if (!is_vector(x)) {\n abort(\"`x` must be a vector.\")\n }\n type <- typeof(x)\n n_dim <- length(dim(x))\n\n add_length <- function(type) {\n if (length && !n_dim) {\n paste0(type, sprintf(\" of length %s\", length(x)))\n } else {\n type\n }\n }\n\n if (type == \"list\") {\n if (n_dim < 2) {\n return(add_length(\"a list\"))\n } else if (is.data.frame(x)) {\n return(\"a data frame\")\n } else if (n_dim == 2) {\n return(\"a list matrix\")\n } else {\n return(\"a list array\")\n }\n }\n\n type <- switch(type,\n logical = \"a logical %s\",\n integer = \"an integer %s\",\n numeric = ,\n double = \"a double %s\",\n complex = \"a complex %s\",\n character = \"a character %s\",\n raw = \"a raw %s\",\n type = paste0(\"a \", type, \" %s\")\n )\n\n if (n_dim < 2) {\n kind <- \"vector\"\n } else if (n_dim == 2) {\n kind <- \"matrix\"\n } else {\n kind <- \"array\"\n }\n out <- sprintf(type, kind)\n\n if (n_dim >= 2) {\n out\n } else {\n add_length(out)\n }\n}\n\n.rlang_as_friendly_type <- function(type) {\n switch(type,\n list = \"a list\",\n NULL = \"`NULL`\",\n environment = \"an environment\",\n externalptr = \"a pointer\",\n weakref = \"a weak reference\",\n S4 = \"an S4 object\",\n name = ,\n symbol = \"a symbol\",\n language = \"a call\",\n pairlist = \"a pairlist node\",\n expression = \"an expression vector\",\n char = \"an internal string\",\n promise = \"an internal promise\",\n ... = \"an internal dots object\",\n any = \"an internal `any` object\",\n bytecode = \"an internal bytecode object\",\n primitive = ,\n builtin = ,\n special = \"a primitive function\",\n closure = \"a function\",\n type\n )\n}\n\n#' @importFrom rlang abort caller_env\n.rlang_stop_unexpected_typeof <- function(x, call = caller_env()) {\n abort(sprintf(\"Unexpected type <%s>.\", typeof(x)), call = call)\n}\n\n#' Return OO type\n#' @param x Any R object.\n#' @return One of `\"bare\"` (for non-OO objects), `\"S3\"`, `\"S4\"`,\n#' `\"R6\"`, or `\"S7\"`.\n#' @noRd\nobj_type_oo <- function(x) {\n if (!is.object(x)) {\n return(\"bare\")\n }\n\n class <- inherits(x, c(\"R6\", \"S7_object\"), which = TRUE)\n\n if (class[[1]]) {\n \"R6\"\n } else if (class[[2]]) {\n \"S7\"\n } else if (isS4(x)) {\n \"S4\"\n } else {\n \"S3\"\n }\n}\n\n.standalone_oxford_comma <- function(x, sep = \", \", final = \"and\") {\n n <- length(x)\n\n if (n < 2L) return(x) # styler: off\n\n head <- x[seq_len(n - 1L)]\n last <- x[n]\n\n head <- paste(head, collapse = sep)\n\n # Write a or b. But a, b, or c.\n if (n > 2L) {\n paste0(head, sep, final, \" \", last)\n } else {\n paste0(head, \" \", final, \" \", last)\n }\n}\n\n# nocov end\n"], ["/ggalign/R/import-standalone-pkg.R", "# Standalone file: do not edit by hand\n# Source: https://github.com/Yunuuuu/standalone/blob/HEAD/R/standalone-pkg.R\n# Generated by: usethis::use_standalone(\"Yunuuuu/standalone\", \"pkg\")\n# ----------------------------------------------------------------------\n#\n# ---\n# repo: Yunuuuu/standalone\n# file: standalone-pkg.R\n# last-updated: 2025-04-10\n# license: https://unlicense.org\n# imports: [utils]\n# ---\n\n# This file contains various helper utilities, including common functions\n# used across multiple packages I have developed. Some functions depend on\n# other packages that are not listed in Imports, so use them with caution.\n\n# ## Changelog\n# 2025-04-10\n# - simplify `from_namespace`\n#\n# 2025-03-30\n# - Add `use_github_release`\n#\n# 2025-03-12\n# - Add `from_namespace`\n#\n# 2025-03-10:\n# - Add `on_exit`\n#\n# 2025-03-08:\n# - Add `pkg_extdata`\n# - Add `defer`\n#\n# 2025-03-04:\n# - Add `%||%`\n#\n# 2025-03-03:\n# - Add `rd_collect_family`\n# - Add `oxford_and`\n# - Add `oxford_or`\n# - Add `code_quote`\n# - Add `oxford_comma`\n#\n# 2025-02-26:\n# - Add `is_installed`\n# - Add `install_pkgs`\n# - Add `pkg_nm`\n# - Add `pkg_namespace`\n#\n# nocov start\n\n`%||%` <- function(x, y) if (is.null(x)) y else x\n\nis_installed <- local({\n cache <- new.env(parent = emptyenv())\n function(pkg, version = NULL) {\n id <- if (is.null(version)) pkg else paste(pkg, version, sep = \":\")\n out <- cache[[id]]\n if (is.null(out)) {\n if (is.null(version)) {\n out <- requireNamespace(pkg, quietly = TRUE)\n } else {\n out <- requireNamespace(pkg, quietly = TRUE) &&\n utils::packageVersion(pkg) >= version\n }\n assign(id, out, envir = cache, inherits = FALSE)\n }\n out\n }\n})\n\ninstall_pkgs <- function(pkgs) {\n if (is_installed(\"pak\")) {\n getExportedValue(\"pak\", \"pkg_install\")(pkgs, ask = FALSE)\n } else {\n utils::install.packages(pkgs)\n }\n}\n\npkg_nm <- function() utils::packageName(environment())\n\npkg_namespace <- function() topenv(environment())\n\npkg_extdata <- function(..., mustWork = TRUE) {\n system.file(\"extdata\", ..., package = pkg_nm(), mustWork = mustWork)\n}\n\n############################################################\n# I’m having trouble connecting to GitHub, and it seems that `gert` does not\n# respect the proxy settings in my Git config. To work around this, I modified\n# `usethis::use_github_release()` to skip the check that relies on the `gert`\n# package.\nuse_github_release <- function(publish = TRUE) {\n usethis_ns <- getNamespace(\"usethis\")\n usethis <- function(fun, ...) {\n get(x = fun, envir = usethis_ns, inherits = FALSE, ...)\n }\n usethis(\"check_is_package\")(\"use_github_release()\")\n tr <- usethis(\"target_repo\")(\n github_get = TRUE,\n ok_configs = c(\"ours\", \"fork\")\n )\n usethis(\"check_can_push\")(tr = tr, \"to create a release\")\n dat <- usethis(\"get_release_data\")(tr)\n release_name <- paste(dat$Package, dat$Version)\n tag_name <- sprintf(\"v%s\", dat$Version)\n usethis(\"kv_line\")(\"Release name\", release_name)\n usethis(\"kv_line\")(\"Tag name\", tag_name)\n usethis(\"kv_line\")(\"SHA\", dat$SHA)\n usethis(\"check_github_has_SHA\")(SHA = dat$SHA, tr = tr)\n on_cran <- !is.null(usethis(\"cran_version\")())\n news <- usethis(\"get_release_news\")(\n SHA = dat$SHA, tr = tr, on_cran = on_cran\n )\n gh <- usethis(\"gh_tr\")(tr)\n usethis(\"ui_bullets\")(\"Publishing {tag_name} release to GitHub\")\n release <- gh( # nolint\n \"POST /repos/{owner}/{repo}/releases\",\n name = release_name,\n tag_name = tag_name,\n target_commitish = dat$SHA,\n body = news,\n draft = !publish\n )\n usethis(\"ui_bullets\")(\"Release at {.url {release$html_url}}\")\n if (!is.null(dat$file)) {\n usethis(\"ui_bullets\")(\"Deleting {.path {dat$file}}\")\n getExportedValue(\"fs\", \"file_delete\")(dat$file)\n }\n invisible()\n}\n\n############################################################\nfrom_namespace <- local({\n namespace <- NULL\n function(package, name, mode = \"any\") {\n if (is.null(namespace)) namespace <<- getNamespace(package)\n get(x = name, envir = namespace, inherits = FALSE, mode = mode)\n }\n})\n\n# Need `rlang` package, can support `quosure`\non_exit <- function(expr, envir = parent.frame(), after = TRUE, add = TRUE) {\n expr <- getExportedValue(\"rlang\", \"enquo\")(expr)\n defer(\n getExportedValue(\"rlang\", \"eval_tidy\")(expr),\n envir = envir,\n after = after,\n add\n )\n}\n\n# Just like `withr::defer()`, don't depend on `rlang` package\ndefer <- function(expr, envir = parent.frame(), after = TRUE, add = TRUE) {\n thunk <- as.call(list(function() expr))\n do.call(base::on.exit, list(thunk, add = add, after = after), envir = envir)\n}\n\n# utils function to collapse characters ---------------------------\noxford_and <- function(x, code = TRUE, quote = TRUE, sep = \", \") {\n oxford_comma(code_quote(x, code, quote), sep = sep, final = \"and\")\n}\n\noxford_or <- function(x, code = TRUE, quote = TRUE, sep = \", \") {\n oxford_comma(code_quote(x, code, quote), sep = sep, final = \"or\")\n}\n\ncode_quote <- function(x, code = TRUE, quote = TRUE) {\n if (quote) x <- paste0(\"\\\"\", x, \"\\\"\")\n if (code) x <- paste0(\"`\", x, \"`\")\n x\n}\n\noxford_comma <- function(x, sep = \", \", final = \"and\") {\n n <- length(x)\n\n if (n < 2L) return(x) # styler: off\n\n head <- x[seq_len(n - 1L)]\n last <- x[n]\n\n head <- paste(head, collapse = sep)\n\n # Write a or b. But a, b, or c.\n if (n > 2L) {\n paste0(head, sep, final, \" \", last)\n } else {\n paste0(head, \" \", final, \" \", last)\n }\n}\n\n# Need `roxygen2` package\n#' @description add `@eval rd_collect_family(\"myfamily\")` to the functions in\n#' your package. This will automatically generate a section listing all\n#' functions tagged with `@family myfamily`.\n#' @param family A string specifying the family name.\n#' @param section_title A string specifying the section title.\n#' @param code_style A boolean indicating whether to apply code formatting\n#' to function names.\n#' @noRd\nrd_collect_family <- function(\n family,\n section_title = paste(family, \"family\"),\n code_style = TRUE) {\n # get blocks objects from the roxygenize function\n blocks <- NULL\n pos <- sys.nframe()\n while (pos > 0L) {\n if (!is.null(call <- sys.call(-pos))) {\n fn <- eval(.subset2(call, 1L), sys.frame(-(pos + 1L)))\n env <- sys.frame(-pos)\n if (\n identical(fn, getExportedValue(\"roxygen2\", \"roxygenize\")) &&\n exists(\"blocks\", envir = env, inherits = FALSE)\n ) {\n blocks <- get(\"blocks\", envir = env, inherits = FALSE)\n break\n }\n }\n pos <- pos - 1L\n }\n\n # identify the blocks with family of the same tag specified in `family`\n blocks <- blocks[\n vapply(\n blocks,\n function(block) {\n getExportedValue(\"roxygen2\", \"block_has_tags\")(\n block,\n \"family\"\n ) &&\n identical(\n getExportedValue(\"roxygen2\", \"block_get_tag_value\")(\n block,\n \"family\"\n ),\n family\n )\n },\n logical(1L),\n USE.NAMES = FALSE\n )\n ]\n if (length(blocks) == 0L) return(character()) # styler: off\n\n # extracted the function name\n funs <- vapply(\n blocks,\n function(block) {\n as.character(.subset2(block$call, 2L))\n },\n character(1L),\n USE.NAMES = FALSE\n )\n if (code_style) {\n items <- sprintf(\"\\\\code{\\\\link[=%s]{%s()}}\", funs, funs)\n } else {\n items <- sprintf(\"\\\\link[=%s]{%s()}\", funs, funs)\n }\n c(\n sprintf(\"@section %s:\", section_title),\n \"\\\\itemize{\",\n sprintf(\" \\\\item %s\", items),\n \"}\"\n )\n}\n\n# nocov end\n"], ["/ggalign/R/layout-align.R", "#' Set Expansion for the Layout\n#'\n#' @description\n#' To align axes, it is important to keep the expansion consistent across all\n#' plots in the layout. You can add a `layout_expand` object to the layout. For\n#' the `quad_layout()` function, you must specify `x` and `y` arguments. For\n#' other layouts, you can pass the expansion values using `...` directly.\n#'\n#' @param ... A list of range expansion constants, used to add padding around\n#' the data to ensure they are placed some distance away from the axes. Use the\n#' convenience function [`expansion()`][ggplot2::expansion()] to generate the\n#' values.\n#' @param x,y Same as `...`, but specifically for `quad_layout()`.\n#'\n#' @importFrom rlang list2\n#' @keywords internal\nlayout_expand <- function(..., x = waiver(), y = waiver()) {\n if (...length() > 0L && (!is.waive(x) || !is.waive(y))) {\n cli_abort(\n \"Cannot mix the usage of {.arg ...} with {.arg x}/{.arg y} argument\"\n )\n }\n if (...length() > 0L) {\n ans <- list2(...)\n names(ans) <- NULL\n } else {\n ans <- list(x = x, y = y)\n }\n structure(ans, class = \"ggalign_layout_expand\")\n}\n\n#' Set continuous limits for the layout\n#'\n#' @description\n#' To align continuous axes, it is important to keep the limits consistent\n#' across all plots in the layout. You can set the limits by passing a function\n#' directly to the `limits` or `xlim`/`ylim` argument, using `...` only.\n#' Alternatively, you can add a `continuous_limits()` object to the layout. For\n#' the `quad_layout()` function, you must specify `x`/`y` arguments. For other\n#' layouts, you should pass the limits using `...` directly.\n#'\n#' @param ... A list of two numeric values, specifying the left/lower limit and\n#' the right/upper limit of the scale.\n#' @inheritParams layout_expand\n#' @importFrom rlang list2\n#' @export\ncontinuous_limits <- function(..., x = waiver(), y = waiver()) {\n if (...length() > 0L && (!is.waive(x) || !is.waive(y))) {\n cli_abort(\n \"Cannot mix the usage of {.arg ...} with {.arg x}/{.arg y} argument\"\n )\n }\n if (...length() > 0L) {\n ans <- list2(...)\n names(ans) <- NULL\n } else {\n ans <- list(x = x, y = y)\n }\n structure(ans, class = c(\"continuous_limits\", \"layout_design\"))\n}\n\n# layout params are used to align the observations\ndiscrete_design <- function(panel = NULL, index = NULL, nobs = NULL) {\n structure(\n list(panel = panel, index = index, nobs = nobs),\n class = c(\"discrete_design\", \"layout_design\")\n )\n}\n\n################################################################\nis_continuous_design <- function(x) {\n is.null(x) || inherits(x, \"continuous_limits\")\n}\n\nis_discrete_design <- function(x) inherits(x, \"discrete_design\")\n\n#' Layout can align ordinal variable or continuous variable\n#'\n#' @param x A `LayoutProto` object.\n#' @noRd\nis_layout_discrete <- function(x, ...) UseMethod(\"is_layout_discrete\")\n\nis_layout_continuous <- function(x, ...) UseMethod(\"is_layout_continuous\")\n\n################################################################\n# Initialize the index and panel\n# Reorder the panel based the ordering index and\nsetup_design <- function(design) {\n # for continuous axis, do noting special\n if (is_continuous_design(design)) return(design) # styler: off\n # if `nobs` is not initialized, it means no `Align` object exist\n # it's not necessary to initialize the `panel` and `index`\n # this is for `stack_layout` which may have no data\n if (is.null(nobs <- .subset2(design, \"nobs\"))) {\n return(design)\n }\n panel <- .subset2(design, \"panel\") %||% factor(rep_len(1L, nobs))\n index <- .subset2(design, \"index\") %||% reorder_index(panel)\n discrete_design(panel[index], index, nobs)\n}\n\nreorder_index <- function(panel, index = NULL) {\n index <- index %||% seq_along(panel)\n unlist(split(index, panel[index]), recursive = FALSE, use.names = FALSE)\n}\n\n############################################################\n#' @keywords internal\nupdate_design <- function(layout, ..., design, object_name) {\n UseMethod(\"update_design\")\n}\n\n#' @importFrom methods slot slot<-\n#' @export\nupdate_design.QuadLayout <- function(layout, ..., direction, design,\n object_name) {\n slot(layout, direction) <- design\n if (is_horizontal(direction)) {\n if (!is.null(left <- layout@left)) {\n layout@left <- update_design(left,\n design = design, object_name = object_name\n )\n }\n if (!is.null(right <- layout@right)) {\n layout@right <- update_design(right,\n design = design, object_name = object_name,\n from_head = TRUE\n )\n }\n } else {\n if (!is.null(top <- layout@top)) {\n layout@top <- update_design(top,\n design = design, object_name = object_name\n )\n }\n if (!is.null(bottom <- layout@bottom)) {\n layout@bottom <- update_design(bottom,\n design = design, object_name = object_name,\n from_head = TRUE\n )\n }\n }\n layout\n}\n\n#' @importFrom methods slot slot<-\n#' @export\nupdate_design.StackLayout <- function(layout, ..., design, object_name) {\n layout@design <- design\n layout@plot_list <- lapply(layout@plot_list, function(plot) {\n if (is_craftbox(plot)) return(plot) # styler: off\n update_design(plot,\n direction = layout@direction,\n design = design\n )\n })\n layout\n}\n\n#' @export\nupdate_design.CircleLayout <- update_design.StackLayout\n\n#' @importFrom methods slot slot<-\n#' @export\nupdate_design.StackCross <- function(layout, ..., design, object_name,\n from_head = FALSE) {\n # `design` must be a discrete_design()\n design_list <- c(layout@odesign, list(layout@design))\n\n # for cross_points, the updating will span it, but only update the panel\n # information\n cross_points <- layout@cross_points\n\n # the break_points set breaks, updating won't span the break points\n break_points <- layout@break_points\n\n plot_list <- layout@plot_list\n n <- length(plot_list)\n points <- c(cross_points, n)\n point_index <- seq_along(points)\n if (!from_head) point_index <- rev(point_index)\n for (i in point_index) {\n cross_point <- .subset(points, i)\n\n # we first update the design in the updated tail\n # it means the first design when `from_head` is `TRUE`\n # the last design when `from_head` is `FALSE`\n if ((from_head && i == 1L) || (!from_head && cross_point == n)) {\n new_design <- design\n } else if (!from_head && any(cross_point == break_points)) {\n break\n } else {\n # for design not in updated tail, we'll only update `panel` and\n # `nobs`, we check the new panel doesn't break the original index\n new_nobs <- .subset2(design, \"nobs\")\n new_panel <- .subset2(design, \"panel\")\n new_design <- .subset2(design_list, i)\n # we check the new panel don't disrupt the ordering index\n if (!is.null(new_panel) &&\n !is.null(old_index <- .subset2(new_design, \"index\"))) {\n # we always prevent from reordering twice.\n new_index <- reorder_index(new_panel, old_index)\n if (!all(old_index == new_index)) {\n cli_abort(sprintf(\n \"%s disrupt the previously established ordering index of %s (%d)\",\n object_name, object_name(layout), i\n ))\n }\n new_design[\"index\"] <- list(new_index)\n }\n new_design[\"nobs\"] <- list(new_nobs)\n new_design[\"panel\"] <- list(new_panel)\n }\n design_list[i] <- list(new_design)\n\n # we then update the design for each plot\n if (i == 1L) {\n subset <- seq_len(cross_point)\n } else {\n subset <- (.subset(points, i - 1L) + 1L):cross_point\n }\n\n layout@plot_list[subset] <- lapply(\n plot_list[subset], function(plot) {\n if (is_craftbox(plot)) {\n return(plot)\n }\n update_design(plot,\n direction = layout@direction,\n design = new_design\n )\n }\n )\n if (from_head && any(cross_point == break_points)) break\n }\n layout@odesign <- vec_slice(design_list, seq_len(length(design_list) - 1L))\n layout@design <- design_list[[length(design_list)]]\n layout\n}\n\n############################################################\nmelt_discrete_design <- function(old, new, old_name, new_name,\n call = caller_call()) {\n old_nobs <- .subset2(old, \"nobs\")\n new_nobs <- .subset2(new, \"nobs\")\n if (is.null(new_nobs)) { # no `nobs` provided\n nobs <- old_nobs\n } else if (is.null(old_nobs)) {\n nobs <- new_nobs\n } else if (!identical(new_nobs, old_nobs)) {\n cli_abort(sprintf(\n \"%s (nobs: %d) is not compatible with the %s (nobs: %d)\",\n new_name, new_nobs, old_name, old_nobs\n ), call = call)\n } else {\n nobs <- new_nobs\n }\n\n # check panel\n old_panel <- .subset2(old, \"panel\")\n new_panel <- .subset2(new, \"panel\")\n\n if (is.null(new_panel)) { # no panel provided\n panel <- old_panel\n } else if (!is.null(old_panel) && !(new_panel %nest% old_panel)) {\n cli_abort(sprintf(\n \"%s disrupt the previously established panel groups of %s\",\n new_name, old_name\n ), call = call)\n } else {\n panel <- new_panel\n }\n\n # check index\n old_index <- .subset2(old, \"index\")\n new_index <- .subset2(new, \"index\")\n if (is.null(new_index)) {\n index <- old_index\n } else {\n index <- new_index\n }\n\n # we always make the index following the panel\n if (!is.null(panel) && !is.null(index)) {\n index <- reorder_index(panel, index)\n }\n\n # we always prevent from reordering twice.\n if (!is.null(old_index) && !all(old_index == index)) {\n cli_abort(sprintf(\n \"%s disrupt the previously established ordering index of %s\",\n new_name, old_name\n ), call = call)\n }\n discrete_design(panel, index, nobs)\n}\n\n#######################################################################\n# ggplot2 add default scales in `compute_aesthetics` process\n# then ggplot2 transform all scales\n# layout:\n# in ggplot_build\n# - `setup`:\n# - call `facet$setup_params`\n# - attach `plot_env`\n# - call `facet$setup_data`\n# - call `facet$compute_layout`\n# - call `coord$setup_layout`\n# - call `facet$map_data`\n# - `train_position`: (run twice)\n# - call `facet$init_scales`\n# - call `facet$train_scales`\n# - `setup_panel_params`\n# - call `coord$modify_scales`: we align scales here, since this step\n# scales have been trained\n# - call `coord$setup_panel_params`: `view_scales_from_scale()`\n# - `map_position`\n# - `setup_panel_guides`\n# - call `coord$setup_panel_guides`\n# - call `coord$train_panel_guides`\n# in ggplot_gtable\n# - `layout$render`:\n# - call `facet$draw_back`\n# - call `facet$draw_front`\n# - call `coord$draw_panel` for each panel\n# - call `facet$draw_panels`: only once\n# - call `facet$init_gtable`:\n# - call `facet$attach_axes`:\n# - call `coord$render_axis_h`:\n# - call `guide$draw`:\n# - call `coord$render_axis_v`:\n# - call `guide$draw`:\n# - call `facet$attach_strips`:\n\n#' Set `limits`, `breaks`, `labels` for each panel\n#'\n#' @param x,y design for the layout.\n#' @keywords internal\n#' @noRd\nggalign_design <- function(x = NULL, y = NULL,\n xlabels = NULL, ylabels = NULL,\n xlim = TRUE, ylim = TRUE) {\n structure(\n list(\n x = x, y = y,\n xlabels = xlabels, ylabels = ylabels,\n xlim = xlim, ylim = ylim\n ),\n class = \"ggalign_design\"\n )\n}\n\nsetup_discrete_limits <- function(axis, design, n_panels) {\n panel <- .subset2(design, \"panel\")\n index <- .subset2(design, \"index\")\n if (n_panels == 1L) {\n list(range(index) + c(-0.5, 0.5))\n } else {\n # For y-axis, ggplot arrange panel from top to bottom,\n # we always choose to reverse the panel order\n if (axis == \"y\") panel <- fct_rev(panel)\n lapply(split(seq_along(index), panel), function(plot_index) {\n range(plot_index) + c(-0.5, 0.5)\n })\n }\n}\n\n#' @importFrom ggplot2 ggplot_add ggproto ggproto_parent\n#' @export\nggplot_add.ggalign_design <- function(object, plot, object_name, ...) {\n x_design <- .subset2(object, \"x\")\n y_design <- .subset2(object, \"y\")\n if (is.null(x_design) && is.null(y_design)) {\n return(plot)\n }\n ParentCoord <- plot$coordinates\n plot$coordinates <- ggproto(\n NULL, ParentCoord,\n num_of_panels = NULL,\n panel_counter = NULL,\n n_row_panels = NULL, # should be the number of panels in y\n n_column_panels = NULL, # should be the number of panels in x\n setup_layout = function(self, layout, params) {\n # we always initialize the number of panels and a panel counter\n self$num_of_panels <- vec_unique_count(.subset2(layout, \"PANEL\"))\n self$panel_counter <- 0L\n self$n_column_panels <- vec_unique_count(.subset2(layout, \"COL\"))\n self$n_row_panels <- vec_unique_count(.subset2(layout, \"ROW\"))\n if (.subset2(object, \"xlim\") && !is.null(x_design)) {\n if (is_discrete_design(x_design)) {\n self$xlim_list <- setup_discrete_limits(\n \"x\", x_design, self$n_column_panels\n )\n } else {\n self$xlim_list <- x_design\n }\n }\n if (.subset2(object, \"ylim\") && !is.null(y_design)) {\n if (is_discrete_design(y_design)) {\n self$ylim_list <- setup_discrete_limits(\n \"y\", y_design, self$n_row_panels\n )\n } else {\n self$ylim_list <- y_design\n }\n }\n # call the parent method\n ggproto_parent(ParentCoord, self)$setup_layout(layout, params)\n },\n # take the tricks to modify scales in place\n modify_scales = function(self, scales_x, scales_y) {\n # for each scale, we set the `breaks` and `labels`\n if (is_discrete_design(x_design)) {\n align_discrete_scales(\n \"x\", scales_x, x_design,\n labels = .subset2(object, \"xlabels\"),\n n_panels = self$n_column_panels,\n circle_layout = inherits(ParentCoord, \"CoordRadial\")\n )\n }\n if (is_discrete_design(y_design)) {\n align_discrete_scales(\n \"y\", scales_y, y_design,\n labels = .subset2(object, \"ylabels\"),\n n_panels = self$n_row_panels,\n circle_layout = inherits(ParentCoord, \"CoordRadial\")\n )\n }\n ggproto_parent(ParentCoord, self)$modify_scales(scales_x, scales_y)\n },\n setup_panel_params = function(self, scale_x, scale_y, params = list()) {\n # `setup_panel_params()` will utilize the `limits`\n # set limits here to ensure each plot will have the same limits\n cur_panel <- self$panel_counter + 1L\n if (!is.null(self$xlim_list)) {\n xlim <- .subset2(\n self$xlim_list,\n recycle_whole(cur_panel, self$n_column_panels)\n )\n if (is_discrete_design(x_design) && scale_x$is_discrete() &&\n !is.null(scale_x$range$range)) {\n # for discrete scale, the limits starts from zero in each\n # panel\n xlim <- xlim - (min(xlim) - 0.5)\n }\n if (inherits(self, \"CoordRadial\")) {\n self$limits$theta <- xlim\n } else {\n self$limits$x <- xlim\n }\n }\n if (!is.null(self$ylim_list)) {\n ylim <- .subset2(\n self$ylim_list,\n recycle_each(cur_panel, self$n_column_panels)\n )\n if (is_discrete_design(y_design) && scale_y$is_discrete() &&\n !is.null(scale_y$range$range)) {\n # for discrete scale, the limits starts from zero in each\n # panel\n ylim <- ylim - (min(ylim) - 0.5)\n }\n if (inherits(self, \"CoordRadial\")) {\n self$limits$r <- ylim\n } else {\n self$limits$y <- ylim\n }\n }\n self$panel_counter <- cur_panel\n ggproto_parent(ParentCoord, self)$setup_panel_params(\n scale_x = scale_x, scale_y = scale_y, params = params\n )\n }\n )\n plot\n}\n\nalign_discrete_scales <- function(axis, scales, design, labels, n_panels,\n circle_layout) {\n panel <- .subset2(design, \"panel\")\n index <- .subset2(design, \"index\")\n\n if (n_panels == 1L) {\n panel <- factor(vec_rep(1L, length(index)))\n } else {\n # For y-axis, ggplot arrange panel from top to bottom,\n # we always choose to reverse the panel order\n if (axis == \"y\") panel <- fct_rev(panel)\n }\n if (is.null(labels)) {\n data_labels <- NULL\n } else {\n data_labels <- split(labels, panel)\n }\n data_index <- split(index, panel)\n plot_index <- split(seq_along(index), panel)\n default_expand <- ggplot2::expansion()\n for (i in seq_along(scales)) {\n scale <- .subset2(scales, i)\n # we always use the discrete scale to determine labels and breaks\n # https://github.com/tidyverse/ggplot2/blob/7fb4c382f9ea332844d469663a8047355a88dd7a/R/scale-.R#L927\n # setup breaks and labels --------------------\n if (is.null(data_labels) &&\n is.waive(scale$labels) &&\n is.waive(scale$breaks)) {\n # special case for data have no labels\n # By default we also remove the breaks\n scale$breaks <- NULL\n scale$labels <- NULL\n } else {\n dindex <- .subset2(data_index, i)\n pindex <- .subset2(plot_index, i)\n labels <- .subset2(data_labels, i)\n scale$breaks <- get_discrete_breaks(scale, pindex, dindex, labels)\n scale$labels <- get_discrete_labels(\n scale, scale$breaks, pindex, dindex, labels\n )\n }\n\n # by default we elways remove any expansion\n # we don't allow the set of expansion for discrete variables\n # otherwise, ggmark and `cross_mark` won't work properly\n if (!circle_layout) scale$expand <- default_expand\n\n # for continuous scale, we don't allow the trans\n # if (!scale$is_discrete() && !identical(scale$trans$name, \"identity\")) {\n # cli_warn(sprintf(\n # \"{.arg trans} must be {.field identity} in {.code %s}\",\n # deparse(scale$call)\n # ))\n # scale$trans <- scales::as.transform(\"identity\")\n # }\n }\n}\n\n#' @importFrom rlang is_empty\nget_discrete_breaks <- function(scale, pindex, dindex, labels) {\n if (scale$is_empty()) return(numeric()) # styler: off\n breaks <- scale$breaks\n if (identical(breaks, NA)) {\n cli_abort(c(\n \"Invalid {.arg breaks} specification.\",\n i = \"Use {.code NULL}, not {.code NA}.\"\n ), call = scale$call)\n }\n if (is.null(breaks)) {\n return(NULL)\n }\n if (is.waive(breaks)) {\n if (scale$is_discrete() &&\n !is.null(labels) &&\n !is.null(scale$range$range) &&\n all(scale$range$range %in% labels)) {\n ans <- labels\n } else {\n ans <- pindex\n }\n } else {\n if (is.null(labels)) {\n limits <- dindex\n } else {\n limits <- labels\n }\n if (is.function(breaks)) {\n breaks <- breaks(limits)\n }\n\n if (is.factor(breaks) || is.character(breaks)) {\n # we interpreted the character breaks as the names of the original\n # matrix data.\n pos <- match(\n as.character(limits),\n vec_cast(breaks, character(),\n x_arg = \"breaks\", call = scale$call\n )\n )\n } else {\n # By default, we interpreted the breaks as the data index\n # If wrapped with `I()`, we interpreted it as the plot index\n if (inherits(breaks, \"AsIs\")) { # plot index\n pos <- match(pindex, vec_cast(breaks, integer(),\n x_arg = \"breaks\", call = scale$call\n ))\n } else { # data index\n pos <- match(dindex, vec_cast(breaks, integer(),\n x_arg = \"breaks\", call = scale$call\n ))\n }\n }\n index <- which(!is.na(pos))\n if (is_empty(index)) {\n return(NULL)\n }\n pos <- pos[index]\n if (scale$is_discrete() &&\n !is.null(labels) &&\n !is.null(scale$range$range) &&\n all(scale$range$range %in% labels)) {\n ans <- structure(labels[index], index = index, pos = pos)\n } else {\n ans <- structure(pindex[index], index = index, pos = pos)\n }\n }\n ans\n}\n\n#' @importFrom rlang is_empty\nget_discrete_labels <- function(scale, breaks, pindex, dindex, labels) {\n scale_labels <- scale$labels\n if (is_empty(breaks) || is.null(scale_labels)) { # if no breaks, no labels\n return(NULL)\n }\n\n if (identical(scale_labels, NA)) {\n cli_abort(c(\n \"Invalid {.arg labels} specification.\",\n i = \"Use {.code NULL}, not {.code NA}.\"\n ), call = scale$call)\n }\n\n # Need to ensure that if breaks were dropped\n if (!is.null(index <- attr(breaks, \"index\"))) {\n dindex <- dindex[index]\n labels <- labels[index]\n }\n\n # if layout have no names, use the data index directly\n # re-defined the breaks, the plot use the coordinates index\n # we interpreted user input as the data index\n if (is.null(labels)) {\n user_breaks <- dindex\n } else {\n user_breaks <- labels\n }\n if (is.waive(scale_labels)) { # By default, use the breaks\n user_breaks\n } else if (is.function(scale_labels)) {\n scale_labels(user_breaks)\n } else if (!is.null(names(scale_labels))) {\n # If labels have names, use them to match with breaks\n map <- match(as.character(user_breaks), names(scale_labels))\n user_breaks[map] <- scale_labels[!is.na(map)]\n user_breaks\n } else {\n # Need to ensure that if breaks were dropped, corresponding labels\n # are too\n if (is.null(pos <- attr(breaks, \"pos\"))) {\n if (inherits(scale_labels, \"AsIs\")) { # already in the plot index\n # we sort the `pos` so labels ordering won't be changed\n scale_labels <- scale_labels[pindex]\n } else { # in the data index\n scale_labels <- scale_labels[dindex]\n }\n } else {\n if (inherits(scale_labels, \"AsIs\")) { # already in the plot index\n # we sort the `pos` so labels ordering won't be changed\n scale_labels <- scale_labels[sort(pos)]\n } else { # in the data index\n scale_labels <- scale_labels[pos]\n }\n }\n scale_labels\n }\n}\n\n######################################################\n# this will remove the old coordinate,\n# so always run firstly\ngguse_linear_coord <- function(plot, layout_name) {\n coord <- plot$coordinates\n if (!inherits(coord, \"CoordTrans\") && !coord$is_linear()) {\n cli_warn(c(\n sprintf(\n \"{.fn %s} is not supported in %s\",\n snake_class(coord), layout_name\n ),\n i = \"Will use {.fn coord_cartesian} instead\"\n ))\n plot$coordinates <- ggplot2::coord_cartesian()\n }\n plot\n}\n\ngguse_circle_coord <- function(plot, coord, ..., layout_name) {\n if (inherits(plot_coord <- plot$coordinates, \"CoordRadial\")) {\n out <- ggproto(\n NULL, plot_coord,\n theta = coord$theta,\n r = coord$r,\n arc = coord$arc,\n direction = coord$direction,\n r_axis_inside = coord$r_axis_inside,\n expand = coord$expand,\n ...,\n setup_panel_params = circle_panel_params\n )\n } else {\n if (!isTRUE(plot$coordinates$default)) {\n cli_warn(c(\n sprintf(\n \"{.fn %s} is not supported in %s\",\n snake_class(plot_coord), layout_name\n ),\n i = sprintf(\"Will use {.fn %s} instead\", snake_class(coord))\n ))\n }\n if (!inherits(coord, \"CoordCircle\")) {\n out <- ggproto(NULL, coord, ...,\n setup_panel_params = circle_panel_params\n )\n } else {\n out <- ggproto(NULL, coord, ...)\n }\n }\n out\n}\n\n######################################################\n#' @importFrom ggplot2 ggproto\nggfacet_modify <- function(plot, ...) {\n ParentFacet <- plot$facet\n plot$facet <- ggproto(NULL, ParentFacet, ...)\n plot\n}\n\ngguse_facet <- function(plot, facet) {\n plot$facet <- facet\n plot\n}\n\nggmelt_facet <- function(plot, facet, ...) {\n gguse_facet(plot, melt_facet(facet, plot$facet, ...))\n}\n\n#' @param use A template facet object which will be used.\n#' @param facet User provided facet object.\n#' @noRd\nmelt_facet <- function(use, facet, ...) UseMethod(\"melt_facet\")\n\n#' @export\nmelt_facet.NULL <- function(use, facet, ...) {\n facet\n}\n\n#' @importFrom ggplot2 ggproto\n#' @export\nmelt_facet.FacetGrid <- function(use, facet, ...,\n free_row = FALSE,\n free_column = FALSE) {\n if (inherits(facet, \"FacetGrid\")) {\n # re-dispatch parameters\n params <- facet$params\n if (length(use$params$rows) || !free_row) {\n params$rows <- use$params$rows\n }\n if (length(use$params$cols) || !free_column) {\n params$cols <- use$params$cols\n }\n if (!free_row) { # Don't allow user change the rows\n params$free$y <- use$params$free$y\n params$space_free$y <- use$params$space_free$y\n }\n if (!free_column) { # Don't allow user change the cols\n params$free$x <- use$params$free$x\n params$space_free$x <- use$params$space_free$x\n }\n\n params$drop <- use$params$drop\n params$as.table <- use$params$as.table\n\n # if the use is free, it must be free\n ggproto(NULL, facet, params = params)\n } else {\n use\n }\n}\n\n#' @importFrom ggplot2 ggproto\n#' @export\nmelt_facet.FacetWrap <- function(use, facet, ...) {\n if (inherits(facet, \"FacetWrap\")) {\n # re-dispatch parameters\n params <- facet$params\n\n # we always fix the grid rows and cols\n params$facets <- use$params$facets\n params$nrow <- use$params$nrow\n params$ncol <- use$params$ncol\n params$drop <- use$params$drop\n params$as.table <- use$params$as.table\n ggproto(NULL, facet, params = params)\n } else {\n use\n }\n}\n\n#' @export\nmelt_facet.FacetNull <- function(use, facet, ...) {\n if (inherits(facet, \"FacetNull\")) {\n facet\n } else {\n use\n }\n}\n\n#' @export\nmelt_facet.FacetStack <- function(use, facet, ...) {\n if (inherits(facet, \"FacetGrid\")) {\n params <- facet$params\n if (is_horizontal(.subset2(use, \"direction\"))) {\n # for horizontal stack, we cannot facet by rows\n if (!is.null(params$rows)) {\n cli_warn(sprintf(\n \"Cannot facet by rows in %s\",\n .subset2(use, \"object_name\")\n ))\n params$rows <- NULL\n }\n } else if (!is.null(params$cols)) {\n # for vertical stack, we cannot facet by cols\n cli_warn(sprintf(\n \"Cannot facet by cols in %s\",\n .subset2(use, \"object_name\")\n ))\n params$cols <- NULL\n }\n ggproto(NULL, facet, params = params)\n } else if (inherits(facet, \"FacetWrap\")) {\n params <- facet$params\n if (is_horizontal(.subset2(use, \"direction\"))) {\n # for horizontal stack, we cannot facet by rows\n if (is.null(params$nrow)) {\n params$nrow <- 1L\n } else if (params$nrow > 1L) {\n cli_warn(sprintf(\n \"Cannot wrap facet by rows in %s\",\n .subset2(use, \"object_name\")\n ))\n params$nrow <- 1L\n }\n } else if (!is.null(params$cols)) {\n # for vertical stack, we cannot facet by cols\n if (is.null(params$ncol)) {\n params$ncol <- 1L\n } else if (params$ncol > 1L) {\n cli_warn(sprintf(\n \"Cannot wrap facet by cols in %s\",\n .subset2(use, \"object_name\")\n ))\n params$ncol <- 1L\n }\n }\n } else if (inherits(facet, \"FacetNull\")) {\n facet\n } else {\n ggplot2::facet_null()\n }\n}\n\nfacet_stack <- function(direction, object_name) {\n structure(\n list(direction = direction, object_name = object_name),\n class = \"FacetStack\"\n )\n}\n\n#' @export\nmelt_facet.FacetQuad <- function(use, facet, ...,\n free_row = FALSE,\n free_column = FALSE) {\n if (inherits(facet, \"FacetGrid\")) {\n if (free_row || free_column) {\n params <- facet$params\n if (!free_row && !is.null(params$rows)) {\n cli_warn(sprintf(\n \"Cannot facet by rows in %s\",\n .subset2(use, \"layout_name\")\n ))\n params$rows <- NULL\n # for horizontal stack, we cannot facet by rows\n }\n if (!free_column && !is.null(params$cols)) {\n cli_warn(sprintf(\n \"Cannot facet by cols in %s\",\n .subset2(use, \"layout_name\")\n ))\n params$cols <- NULL\n }\n ggproto(NULL, facet, params = params)\n } else {\n ggplot2::facet_null()\n }\n } else if (inherits(facet, \"FacetNull\")) {\n facet\n } else {\n ggplot2::facet_null()\n }\n}\n\nfacet_quad <- function(layout_name) {\n structure(list(layout_name = layout_name), class = \"FacetQuad\")\n}\n"], ["/ggalign/R/alignpatch-area.R", "# We are removing the patchwork dependency by defining our own version of\n# patchwork::area, as some desired features won't be merged (see this\n# https://github.com/thomasp85/patchwork/issues/379). Therefore, ggalign will\n# retain `alignpatch-*` scripts.\n\n#' Define the plotting areas in `align_plots`\n#'\n#' @inherit patchwork::area\n#' @details\n#' The grid that the areas are specified in reference to enumerate rows from top\n#' to bottom, and coloumns from left to right. This means that `t` and `l`\n#' should always be less or equal to `b` and `r` respectively. Instead of\n#' specifying area placement with a combination of `area()` calls, it is\n#' possible to instead pass in a single string\n#'\n#' ```\n#' areas <- c(area(1, 1, 2, 1),\n#' area(2, 3, 3, 3))\n#' ```\n#'\n#' is equivalent to\n#'\n#' ```\n#' areas < -\"A##\n#' A#B\n#' ##B\"\n#' ```\n#' @return A `ggalign_area` object.\n#' @examples\n#' p1 <- ggplot(mtcars) +\n#' geom_point(aes(mpg, disp))\n#' p2 <- ggplot(mtcars) +\n#' geom_boxplot(aes(gear, disp, group = gear))\n#' p3 <- ggplot(mtcars) +\n#' geom_bar(aes(gear)) +\n#' facet_wrap(~cyl)\n#'\n#' layout <- c(\n#' area(1, 1),\n#' area(1, 3, 3),\n#' area(3, 1, 3, 2)\n#' )\n#'\n#' # Show the layout to make sure it looks as it should\n#' plot(layout)\n#'\n#' # Apply it to a alignpatches\n#' align_plots(p1, p2, p3, design = layout)\n#' @export\narea <- function(t, l, b = t, r = l) {\n if (missing(t) || missing(l)) {\n one_area <- list(\n t = integer(0L),\n l = integer(0L),\n b = integer(0L),\n r = integer(0L)\n )\n } else {\n one_area <- df_list(\n t = vec_cast(t, integer()),\n l = vec_cast(l, integer()),\n b = vec_cast(b, integer()),\n r = vec_cast(r, integer())\n )\n if (any(.subset2(one_area, \"t\") > .subset2(one_area, \"b\"))) {\n cli_abort(\"{.arg t} must be less than {.arg b}\")\n }\n if (any(.subset2(one_area, \"l\") > .subset2(one_area, \"r\"))) {\n cli_abort(\"{.arg l} must be less than {.arg r}\")\n }\n }\n new_areas(one_area)\n}\n\n# Define a custom S3 class `ggalign_area`, without using S7 directly\n# Patchwork expects traditional S3 classes, and S7 classes are not fully\n# interoperable with patchwork layouts.\nS3_area <- S7::new_S3_class(\"ggalign_area\")\n\nnew_areas <- function(x) new_rcrd(x, class = c(\"ggalign_area\", \"patch_area\"))\n\ncreate_area <- function(ncol, nrow, byrow) {\n mat <- matrix(seq_len(ncol * nrow),\n nrow = nrow, ncol = ncol, byrow = byrow\n )\n ind <- as.vector(mat)\n ind <- match(seq_along(ind), ind)\n area(t = row(mat)[ind], l = col(mat)[ind])\n}\n\n#' @export\nobj_print_data.ggalign_area <- function(x, ...) {\n x <- vec_data(x)\n if (vec_size(x) > 0) {\n x <- vec_set_names(x, paste0(vec_seq_along(x), \": \"))\n print(x = x, ..., quote = FALSE)\n } else {\n cat(\" \", names(x), \"\\n\", sep = \" \")\n }\n}\n\n#' @export\nobj_print_footer.ggalign_area <- function(x, ...) {\n if (vec_size(x) == 0) {\n ncols <- 0\n nrows <- 0\n } else {\n ncols <- max(field(x, \"r\"))\n nrows <- max(field(x, \"b\"))\n }\n cat(\"\\n\\n\")\n}\n\n#' @export\nvec_ptype_abbr.ggalign_area <- function(x, ...) \"areas\"\n\ntrim_area <- function(area) {\n area <- vec_data(area)\n w <- min(.subset2(area, \"l\"), .subset2(area, \"r\"))\n h <- min(.subset2(area, \"t\"), .subset2(area, \"b\"))\n area$l <- .subset2(area, \"l\") - w + 1L\n area$r <- .subset2(area, \"r\") - w + 1L\n area$t <- .subset2(area, \"t\") - h + 1L\n area$b <- .subset2(area, \"b\") - h + 1L\n new_areas(area)\n}\n\nas_areas <- function(x) UseMethod(\"as_areas\")\n\n#' @export\nas_areas.default <- function(x) {\n cli_abort(\"Cannot convert {.obj_type_friendly {x}} into a design area\")\n}\n\n#' @export\nas_areas.NULL <- function(x) NULL\n\n#' @export\nas_areas.ggalign_area <- function(x) x\n\n#' @export\nas_areas.character <- function(x) {\n call <- current_call() # used for message only\n # split into rows\n x <- .subset2(strsplit(x, split = \"\\n\"), 1L)\n x <- lapply(x, trimws)\n if (identical(x[[1L]], \"\")) x[[1L]] <- NULL\n if (identical(x[[length(x)]], \"\")) x[[length(x)]] <- NULL\n x <- lapply(x, function(x) .subset2(strsplit(x, split = \"\"), 1L))\n ncols <- list_sizes(x)\n ncol <- .subset(ncols, 1L)\n if (any(ncols != ncol)) {\n cli_abort(\"character layout must be rectangular\", call = call)\n }\n row <- rep(seq_along(x), each = ncol)\n col <- rep(seq_len(ncol), length(x))\n x <- unlist(x, use.names = FALSE)\n # here, area will be reordered by the levels of `x`\n area_list <- imap(split(seq_along(x), x), function(i, name) {\n if (identical(name, \"#\")) {\n return(area())\n }\n area_rows <- range(row[i])\n area_cols <- range(col[i])\n t <- .subset(area_rows, 1L)\n l <- .subset(area_cols, 1L)\n b <- .subset(area_rows, 2L)\n r <- .subset(area_cols, 2L)\n if (!all(x[row >= t & row <= b & col >= l & col <= r] ==\n x[.subset(i, 1L)])) {\n cli_abort(\"Patch areas must be rectangular\", call = call)\n }\n new_areas(list(t = t, l = l, b = b, r = r))\n })\n vec_c(!!!vec_set_names(area_list, NULL))\n}\n\n# For area from patchwork\n#' @export\nas_areas.patch_area <- function(x) add_class(x, \"ggalign_area\")\n\n#' @importFrom grid unit\n#' @importFrom ggplot2 aes margin theme ggplot\n#' @importFrom utils packageVersion\n#' @export\nplot.ggalign_area <- function(x, ...) {\n data <- vec_data(x)\n data$l <- data$l - 0.45\n data$r <- data$r + 0.45\n data$t <- data$t - 0.45\n data$b <- data$b + 0.45\n data$name <- as.factor(vec_seq_along(x))\n b_fun <- function(lim) {\n if (lim[1] < lim[2]) {\n lim <- seq(floor(lim[1]), ceiling(lim[2]), by = 1)\n } else {\n lim <- seq(ceiling(lim[1]), floor(lim[2]), by = -1)\n }\n lim[-c(1, length(lim))]\n }\n ggplot(data) +\n ggplot2::geom_rect(aes(\n xmin = .data$l, xmax = .data$r,\n ymin = .data$t, ymax = .data$b, fill = .data$name\n ), alpha = 0.3) +\n ggplot2::scale_y_reverse(breaks = b_fun, expand = c(0, 0.04)) +\n ggplot2::scale_x_continuous(\n breaks = b_fun, expand = c(0, 0.04), position = \"top\"\n ) +\n ggplot2::labs(fill = \"Patch\") +\n ggplot2::theme_void() +\n theme(\n panel.grid.minor = if (packageVersion(\"ggplot2\") >= \"3.4.0\") {\n ggplot2::element_line(linewidth = 0.5, colour = \"grey\")\n } else {\n ggplot2::element_line(size = 0.5, colour = \"grey\")\n },\n axis.text = ggplot2::element_text(),\n axis.ticks.length = unit(3, \"mm\"),\n plot.margin = margin(10, 10, 10, 10)\n )\n}\n"], ["/ggalign/R/mark.R", "#' Define the links to connect the marked observations\n#'\n#' @description\n#' This function allows users to define links between marked observations and\n#' plot panel (e.g., for creating visual connections for related data), which\n#' could help explain the observations.\n#'\n#' @param .draw A function used to draw the links. The function must return a\n#' [`grob()`][grid::grob] object. If the function does not return a valid\n#' `grob`, nothing will be drawn. The input data for the function must contain\n#' two arguments: a data frame for the panel side coordinates and a data frame\n#' for the marked observation coordinates.\n#' @inheritParams .mark_draw\n#' @seealso\n#' - [`mark_line()`]\n#' - [`mark_tetragon()`]\n#' - [`mark_triangle()`]\n#' - [`.mark_draw()`]\n#' @importFrom rlang is_empty inject\n#' @importFrom grid gTree gList\n#' @export\nmark_draw <- function(.draw, ...) {\n if (!is.function(draw <- allow_lambda(.draw))) {\n cli_abort(\"{.arg .draw} must be a function\")\n }\n new_draw <- function(data) {\n ans <- lapply(data, function(dd) {\n draw(.subset2(dd, \"panel\"), .subset2(dd, \"link\"))\n })\n ans <- ans[vapply(ans, is.grob, logical(1L), USE.NAMES = FALSE)]\n if (!is_empty(ans)) {\n gTree(children = inject(gList(!!!ans)))\n }\n }\n .mark_draw(new_draw, ...)\n}\n\n#' @inherit mark_draw title\n#'\n#' @description\n#' A base version of [`mark_draw`], designed for performance optimization. This\n#' function is used to build other `mark_*` functions that manage the drawing of\n#' links between marked observations.\n#'\n#' @param .draw A function used to draw the links. The function must return a\n#' [`grob()`][grid::grob] object. If the function does not return a valid\n#' `grob`, nothing will be drawn. The input data for the function contains a\n#' list, where each item is a list of two data frames: one for the panel side\n#' coordinates (`\"panel\"`) and one for the marked observations coordinates\n#' (`\"link\"`).\n#'\n#' @inheritParams pair_links\n#' @seealso [`mark_draw()`]\n#' @export\n.mark_draw <- function(.draw, ...) {\n if (override_call(call <- caller_call())) {\n call <- current_call()\n }\n if (!is.function(draw <- allow_lambda(.draw))) {\n cli_abort(\"{.arg .draw} must be a function\", call = call)\n }\n links <- pair_links(...)\n structure(list(draw = draw, links = links), class = \"ggalign_mark_draw\")\n}\n\n#' @export\nprint.ggalign_mark_draw <- function(x, ...) {\n header <- sprintf(\"<%s>\", vec_ptype_full(x))\n cat(header, sep = \"\\n\")\n obj_print_data(.subset2(x, \"links\"))\n invisible(x)\n}\n\n#' Link the observations and the panel with a line\n#'\n#' @inheritParams .mark_draw\n#' @param .element A [`element_line()`][ggplot2::element_line] object.\n#' Vectorized fields will be recycled to match the total number of groups, or\n#' you can wrap the element with [`I()`] to recycle to match the drawing\n#' groups. The drawing groups typically correspond to the number of\n#' observations, as each observation will be linked with the plot panel.\n#' @importFrom ggplot2 element_line\n#' @export\nmark_line <- function(..., .element = NULL) {\n assert_s3_class(.element, \"element_line\", allow_null = TRUE)\n default <- calc_element(\"ggalign.line\", complete_theme(theme_get()))\n if (is.null(.element)) {\n .element <- default\n } else {\n .element <- ggplot2::merge_element(.element, default)\n }\n .mark_draw(.draw = function(data) {\n data <- lapply(data, function(d) {\n panel <- .subset2(d, \"panel\")\n link <- .subset2(d, \"link\")\n data_frame0(\n # there is only one row for panel, it's safe to use\n # vec_interleave directly\n x = vec_interleave(\n (panel$x + panel$xend) / 2L,\n (link$x + link$xend) / 2L\n ),\n y = vec_interleave(\n (panel$y + panel$yend) / 2L,\n (link$y + link$yend) / 2L\n )\n )\n })\n if (inherits(.element, \"AsIs\")) {\n .element <- element_rep_len(.element,\n length.out = sum(list_sizes(data)) / 2L\n )\n } else {\n .element <- element_rep_len(.element, length.out = length(data))\n .element <- element_vec_rep_each(.element,\n times = list_sizes(data) / 2L\n )\n }\n data <- vec_rbind(!!!data)\n element_grob(\n .element,\n x = data$x, y = data$y,\n id.lengths = vec_rep(2L, vec_size(data) / 2L),\n default.units = \"native\"\n )\n }, ...)\n}\n\n#' Link the observations and the panel with a quadrilateral\n#'\n#' @inheritParams .mark_draw\n#' @param .element A [`element_polygon()`] object. Vectorized fields will be\n#' recycled to match the total number of groups, or you can wrap the element\n#' with [`I()`] to recycle to match the drawing groups. The drawing groups\n#' are usually the same as the defined groups, but they will differ when the\n#' defined group of observations is separated and cannot be linked with a\n#' single quadrilateral. In such cases, the number of drawing groups will be\n#' larger than the number of defined groups.\n#' @export\nmark_tetragon <- function(..., .element = NULL) {\n assert_s3_class(.element, \"element_polygon\", allow_null = TRUE)\n default <- calc_element(\"ggalign.polygon\", complete_theme(theme_get()))\n if (is.null(.element)) {\n .element <- default\n } else {\n .element <- ggplot2::merge_element(.element, default)\n }\n .mark_draw(.draw = function(data) {\n data <- lapply(data, function(d) {\n panel <- .subset2(d, \"panel\")\n link <- .subset2(d, \"link\")\n\n # find the consecutive groups\n index <- .subset2(link, \"link_index\")\n oindex <- order(index)\n group <- cumsum(c(0L, diff(index[oindex])) != 1L)\n\n # restore the order\n group <- group[order(oindex)]\n\n # split link into groups\n link <- vec_split(link, group)\n\n # for each group, we draw a quadrilateral\n vec_rbind(!!!lapply(.subset2(link, \"val\"), function(dd) {\n data_frame0(\n x = vec_c(panel$x, panel$xend, max(dd$xend), min(dd$x)),\n y = vec_c(panel$y, panel$yend, max(dd$yend), min(dd$y))\n )\n }))\n })\n if (inherits(.element, \"AsIs\")) {\n .element <- element_rep_len(.element,\n length.out = sum(list_sizes(data)) / 4L\n )\n } else {\n .element <- element_rep_len(.element, length.out = length(data))\n .element <- element_vec_rep_each(.element,\n times = list_sizes(data) / 4L\n )\n }\n data <- vec_rbind(!!!data)\n if (vec_size(data)) {\n element_grob(\n .element,\n x = data$x, y = data$y,\n id.lengths = vec_rep(4L, nrow(data) / 4L),\n default.units = \"native\"\n )\n }\n }, ...)\n}\n\n#' Link the observations and the panel with a triangle\n#'\n#' @inheritParams .mark_draw\n#' @param orientation A single string, either `\"plot\"` or `\"observation\"`,\n#' indicating the base of the triangle.\n#' @param .element An [`element_polygon()`] object. Vectorized fields will be\n#' recycled to match the total number of groups, or you can wrap the element\n#' with [`I()`] to recycle to match the drawing groups.\n#' - When `orientation` is `\"plot\"`, the drawing groups typically correspond\n#' to the number of observations.\n#' - When `orientation` is `\"observation\"`, the drawing groups usually match\n#' the defined groups, but will differ if the defined group of observations\n#' is separated and cannot be linked with a single triangle. In this case,\n#' the number of drawing groups will be larger than the number of defined\n#' groups.\n#' @importFrom rlang arg_match0\n#' @export\nmark_triangle <- function(..., orientation = \"plot\", .element = NULL) {\n assert_s3_class(.element, \"element_polygon\", allow_null = TRUE)\n default <- calc_element(\"ggalign.polygon\", complete_theme(theme_get()))\n if (is.null(.element)) {\n .element <- default\n } else {\n .element <- ggplot2::merge_element(.element, default)\n }\n orientation <- arg_match0(orientation, c(\"plot\", \"observation\"))\n .mark_draw(.draw = function(data) {\n data <- lapply(data, function(d) {\n panel <- .subset2(d, \"panel\")\n link <- .subset2(d, \"link\")\n if (identical(orientation, \"plot\")) {\n # for each link, we draw a triangle\n triangle_list <- lapply(vec_seq_along(link), function(i) {\n dd <- vec_slice(link, i)\n data_frame0(\n x = vec_c(panel$x, panel$xend, (dd$x + dd$xend) / 2L),\n y = vec_c(panel$y, panel$yend, (dd$y + dd$yend) / 2L),\n )\n })\n } else {\n # find the consecutive groups\n index <- .subset2(link, \"link_index\")\n oindex <- order(index)\n group <- cumsum(c(0L, diff(index[oindex])) != 1L)\n\n # restore the order\n group <- group[order(oindex)]\n\n # split link into groups\n link <- vec_split(link, group)\n\n # for each group, we draw a triangle\n triangle_list <- lapply(.subset2(link, \"val\"), function(dd) {\n data_frame0(\n x = vec_c(\n (panel$x + panel$xend) / 2L,\n max(dd$xend), min(dd$x)\n ),\n y = vec_c(\n (panel$y + panel$yend) / 2L,\n max(dd$yend), min(dd$y)\n )\n )\n })\n }\n vec_rbind(!!!triangle_list)\n })\n if (inherits(.element, \"AsIs\")) {\n .element <- element_rep_len(.element,\n length.out = sum(list_sizes(data)) / 3L\n )\n } else {\n .element <- element_rep_len(.element, length.out = length(data))\n .element <- element_vec_rep_each(.element,\n times = list_sizes(data) / 3L\n )\n }\n data <- vec_rbind(!!!data)\n if (vec_size(data)) {\n element_grob(\n .element,\n x = data$x, y = data$y,\n id.lengths = vec_rep(3L, nrow(data) / 3L),\n default.units = \"native\"\n )\n }\n }, ...)\n}\n\n#####################################################\n#' @export\n`[.ggalignMarkGtable` <- function(x, i, j) {\n # subset will violate the `ggalignMarkGtable` `shape`\n # we always use the next method\n x <- remove_class(x, \"ggalignMarkGtable\")\n x$ggalign_link_data <- NULL\n NextMethod()\n}\n\n#' @importFrom ggplot2 ggproto\n#' @export\nalignpatch.ggalign_mark_plot <- function(x) {\n ggproto(NULL, PatchAlignMark, plot = x)\n}\n\n#' @importFrom ggplot2 ggproto ggproto_parent\n#' @include alignpatch-ggplot2.R\nPatchAlignMark <- ggproto(\n \"PatchAlignMark\", PatchGgplot,\n patch_gtable = function(self, theme, guides, plot = self$plot) {\n ans <- ggproto_parent(PatchGgplot, self)$patch_gtable(plot = plot)\n # re-define the draw method, we assign new class\n ans <- add_class(ans, \"ggalignMarkGtable\")\n ans$ggalign_link_data <- plot$ggalign_link_data\n ans\n },\n add_plot = function(self, gt, plot, t, l, b, r, name, z = 2L) {\n gtable_add_grob(\n gt,\n grobs = plot,\n # t = 8, l = 6, b = 14, r = 12\n # t = t + 7L, l = l + 5L, b = b - 6L, r = r - 5L,\n t = t + TOP_BORDER, l = l + LEFT_BORDER,\n name = name, z = z\n )\n },\n add_background = function(self, gt, bg, t, l, b, r, name, z = 1L) {\n gtable_add_grob(\n gt,\n grobs = bg,\n t = t + TOP_BORDER, l = l + LEFT_BORDER,\n name = name, z = z\n )\n },\n get_sizes = function(self, free = NULL, gt = self$gt) {\n ggproto_parent(PatchGgplot, self)$get_sizes(.tlbr, gt = gt)\n },\n align_border = function(self, t = NULL, l = NULL, b = NULL, r = NULL,\n gt = self$gt) {\n gt # free from alignment\n }\n)\n\n# preDraw:\n# - makeContext\n# - pushvpgp\n# - preDrawDetails: by default, do noting\n# makeContent:\n# drawDetails:\n# postDraw:\n# - postDrawDetails: by default, do noting\n# - popgrobvp\n#' @importFrom grid makeContent unit convertHeight convertWidth viewport\n#' @importFrom stats reorder\n#' @export\nmakeContent.ggalignMarkGtable <- function(x) {\n # Grab viewport information\n width <- convertWidth(unit(1, \"npc\"), \"mm\", valueOnly = TRUE)\n height <- convertHeight(unit(1, \"npc\"), \"mm\", valueOnly = TRUE)\n\n # Grab grob metadata\n plot_widths <- compute_null_width(.subset2(x, \"widths\"),\n valueOnly = TRUE\n )\n plot_widths <- scales::rescale(plot_widths, c(0, 1), from = c(0, width))\n plot_heights <- compute_null_height(.subset2(x, \"heights\"),\n valueOnly = TRUE\n )\n plot_heights <- scales::rescale(plot_heights, c(0, 1), from = c(0, height))\n\n panel_loc <- find_panel(x)\n data <- .subset2(x, \"ggalign_link_data\")\n full_data1 <- .subset2(data, \"full_data1\")\n full_data2 <- .subset2(data, \"full_data2\")\n direction <- .subset2(data, \"direction\")\n link_index_list <- .subset2(data, \"link_index\")\n data_index_list <- .subset2(data, \"data_index\")\n obs_size <- .subset2(data, \"obs_size\")\n\n # prepare output for current for loop\n coords <- vector(\"list\", 2L)\n names(coords) <- c(\"hand1\", \"hand2\")\n for (link in names(coords)) {\n link_index <- lapply(link_index_list, .subset2, link)\n data_index <- lapply(data_index_list, .subset2, link)\n # early exit and step into next cycle if no link\n if (all(vapply(link_index, is.null, logical(1L), USE.NAMES = FALSE))) {\n coords[link] <- list(link_index)\n next\n }\n full_breaks <- switch(link,\n hand1 = full_data1,\n hand2 = full_data2\n )\n\n spacing <- .subset2(data, switch(link,\n hand1 = \"spacing1\",\n hand2 = \"spacing2\"\n ))\n\n # each value represent an `observation`, for panel space, we use `NA`\n # obs arranged from left to top, and from bottom to top\n points <- unlist(vec_interleave(full_breaks, list(NA)), FALSE, FALSE)\n # remove the last panel space, shouldn't exist\n points <- points[-length(points)]\n sizes <- numeric(length(points))\n n_spacing <- length(full_breaks) - 1L\n\n # then, we define the link grobs\n if (is_horizontal(direction)) { # the link should be in left or right\n spacing <- convertHeight(spacing, \"mm\", valueOnly = TRUE)\n spacing <- scales::rescale(spacing, c(0, 1), from = c(0, height))\n sizes[is.na(points)] <- spacing\n obs_height <- (1 - spacing * n_spacing) / sum(!is.na(points))\n sizes[!is.na(points)] <- obs_height # nobs\n yend <- cumsum(sizes)\n link_x <- switch(link,\n hand1 = 0,\n hand2 = 1\n )\n # by default, the height for each observation is `1`,\n # if we define obs size, we just re-scale it\n removed <- (1 - obs_size) * obs_height\n link_coord <- data_frame0(\n x = link_x, xend = link_x,\n y = yend - sizes + removed / 2L,\n yend = yend - removed / 2L\n )\n link_coord <- vec_slice(link_coord, !is.na(points))\n\n # from bottom to the top, following the ordering of the `breaks`\n panel_index <- seq(\n from = .subset2(panel_loc, \"b\"),\n to = .subset2(panel_loc, \"t\"),\n length.out = length(link_index)\n )\n l_border <- plot_widths[seq_len(.subset2(panel_loc, \"l\") - 1L)]\n r_border <- plot_widths[-seq_len(.subset2(panel_loc, \"r\"))]\n\n # for a gtable, heights are from top to the bottom,\n # we reverse the heights\n # we have reversed the `plot_cum_heights`, so the ordering index\n # should also be reversed\n panel_index <- nrow(x) - panel_index + 1L\n panel_yend <- cumsum(rev(plot_heights))\n panel_x <- switch(link,\n hand1 = sum(l_border),\n hand2 = 1 - sum(r_border)\n )\n panel_coord <- data_frame0(\n x = panel_x,\n xend = panel_x,\n y = (panel_yend - rev(plot_heights))[panel_index],\n yend = panel_yend[panel_index]\n )\n } else { # the link should be in top or bottom\n spacing <- convertWidth(spacing, \"mm\", valueOnly = TRUE)\n spacing <- scales::rescale(spacing, c(0, 1), from = c(0, width))\n sizes[is.na(points)] <- spacing\n obs_width <- (1 - spacing * n_spacing) / sum(!is.na(points))\n sizes[!is.na(points)] <- obs_width\n xend <- cumsum(sizes)\n link_y <- switch(link,\n hand1 = 1,\n hand2 = 0\n )\n # by default, the width for each observation is `1`,\n # if we define obs size, we just re-scale it\n removed <- (1 - obs_size) * obs_width\n link_coord <- data_frame0(\n x = xend - sizes + removed / 2L,\n xend = xend - removed / 2L,\n y = link_y, yend = link_y\n )\n link_coord <- vec_slice(link_coord, !is.na(points))\n\n panel_index <- seq(\n from = .subset2(panel_loc, \"l\"),\n to = .subset2(panel_loc, \"r\"),\n length.out = length(link_index)\n )\n t_border <- plot_heights[seq_len(.subset2(panel_loc, \"t\") - 1L)]\n b_border <- plot_heights[-seq_len(.subset2(panel_loc, \"b\"))]\n panel_xend <- cumsum(plot_widths)\n panel_y <- switch(link,\n hand1 = 1 - sum(t_border),\n hand2 = sum(b_border)\n )\n panel_coord <- data_frame0(\n x = (panel_xend - plot_widths)[panel_index],\n xend = panel_xend[panel_index],\n y = panel_y, yend = panel_y\n )\n }\n hand <- switch(link,\n hand1 = switch_direction(direction, \"left\", \"top\"),\n hand2 = switch_direction(direction, \"right\", \"bottom\")\n )\n nms <- names(link_index)\n link_panels <- vec_rep_each(names(full_breaks), list_sizes(full_breaks))\n coords[[link]] <- lapply(seq_along(link_index), function(i) {\n l_index <- .subset2(link_index, i)\n if (is.null(l_index)) return(NULL) # styler: off\n d_index <- .subset2(data_index, i)\n link <- vec_slice(link_coord, l_index)\n link$link_id <- nms[i]\n link$link_panel <- reorder(\n vec_slice(link_panels, l_index), l_index,\n order = FALSE\n )\n link$link_index <- l_index\n link$.hand <- hand\n link$.index <- d_index\n panel <- vec_slice(panel_coord, i)\n list(panel = panel, link = link)\n })\n }\n coords <- vec_interleave(\n .subset2(coords, \"hand1\"),\n .subset2(coords, \"hand2\")\n )\n coords <- list_drop_empty(coords)\n draw <- .subset2(data, \"draw\")\n if (is.gList(grob <- draw(coords))) {\n grob <- gTree(children = grob)\n }\n\n if (is.grob(grob)) {\n layout <- .subset2(x, \"layout\")\n panels <- layout[\n grepl(\"^panel\", .subset2(layout, \"name\")), ,\n drop = FALSE\n ]\n x <- gtable_add_grob(\n x,\n grobs = grob,\n t = 1L, l = 1L, b = -1L, r = -1L,\n # always draw with panel area\n z = min(panels$z)\n )\n }\n NextMethod()\n}\n"], ["/ggalign/R/ggplot-helper.R", "# Exported function for ggplot2\n# Usually a quick shortcuts to define something\n#\n#' Remove axis elements\n#'\n#' @param axes Which axes elements should be removed? A string containing\n#' one or more of `r oxford_and(c(.tlbr, \"x\", \"y\"))`.\n#' @param text If `TRUE`, will remove the axis labels.\n#' @param ticks If `TRUE`, will remove the axis ticks.\n#' @param title If `TRUE`, will remove the axis title.\n#' @param line If `TRUE`, will remove the axis line.\n#' @return A [`theme()`][ggplot2::theme] object.\n#' @examples\n#' p <- ggplot() +\n#' geom_point(aes(x = wt, y = qsec), data = mtcars)\n#' p + theme_no_axes()\n#' p + theme_no_axes(\"b\")\n#' p + theme_no_axes(\"l\")\n#' @importFrom rlang inject\n#' @importFrom ggplot2 theme element_blank\n#' @export\ntheme_no_axes <- function(axes = \"xy\", text = TRUE, ticks = TRUE,\n title = TRUE, line = FALSE) {\n assert_string(axes, empty_ok = FALSE)\n if (grepl(\"[^tlbrxy]\", axes)) {\n cli_abort(sprintf(\n \"{.arg axes} can only contain the %s characters\",\n oxford_and(c(.tlbr, \"x\", \"y\"))\n ))\n }\n axes <- split_position(axes)\n el <- list(text = text, ticks = ticks, title = title, line = line)\n el <- names(el)[vapply(el, isTRUE, logical(1L), USE.NAMES = FALSE)]\n el_axis <- el_pos <- NULL\n if (length(positions <- vec_set_intersect(axes, .tlbr))) {\n positions <- .subset(\n c(t = \"top\", l = \"left\", b = \"bottom\", r = \"right\"),\n positions\n )\n el_pos <- vec_expand_grid(pos = positions, el = el)\n el_pos <- paste(\"axis\",\n .subset2(el_pos, \"el\"),\n if_else(.subset2(el_pos, \"pos\") %in% c(\"top\", \"bottom\"), \"x\", \"y\"),\n .subset2(el_pos, \"pos\"),\n sep = \".\"\n )\n }\n if (length(axes <- vec_set_intersect(axes, c(\"x\", \"y\")))) {\n el_axis <- vec_expand_grid(axes = axes, el = el)\n el_axis <- paste(\"axis\",\n .subset2(el_axis, \"el\"), .subset2(el_axis, \"axes\"),\n sep = \".\"\n )\n }\n el <- c(el_axis, el_pos)\n el <- vec_set_names(vec_rep(list(element_blank()), length(el)), el)\n inject(theme(!!!el, validate = FALSE))\n}\n\n##########################################################################\n#' Theme Polygon elements\n#'\n#' Draw polygon.\n#'\n#' @inheritParams ggplot2::element_rect\n#' @inheritParams geom_rect3d\n#' @inheritParams ggplot2::fill_alpha\n#' @param linewidth Line size in `mm`.\n#' @param linetype Line type for lines. An integer (0:8), a name (blank, solid,\n#' dashed, dotted, dotdash, longdash, twodash), or a string with an even number\n#' (up to eight) of hexadecimal digits which give the lengths in consecutive\n#' positions in the string.\n#' @seealso [`element_rect`][ggplot2::element_rect]\n#' @return A `element_polygon` object\n#' @export\nelement_polygon <- function(fill = NULL, colour = NULL, linewidth = NULL,\n linetype = NULL, alpha = NULL, lineend = NULL,\n linejoin = NULL, linemitre = NULL, color = NULL,\n inherit.blank = FALSE) {\n if (!is.null(color)) colour <- color\n structure(\n list(\n fill = fill, colour = colour, alpha = alpha,\n linewidth = linewidth, linetype = linetype,\n lineend = lineend, linejoin = linejoin, linemitre = linemitre,\n inherit.blank = inherit.blank\n ),\n class = c(\"ggalign_element_polygon\", \"element_polygon\", \"element\")\n )\n}\n\n#' @importFrom utils packageVersion\n#' @importFrom grid gpar\n#' @importFrom ggplot2 element_grob fill_alpha\n#' @export\nelement_grob.ggalign_element_polygon <- function(element,\n x = c(0, 0.5, 1, 0.5),\n y = c(0.5, 1, 0.5, 0),\n fill = NULL,\n colour = NULL,\n linewidth = NULL,\n linetype = NULL, ...) {\n if (packageVersion(\"ggplot2\") > \"3.5.2\") {\n gp <- ggfun(\"gg_par\")(\n lwd = linewidth, col = colour, fill = fill, lty = linetype\n )\n element_gp <- ggfun(\"gg_par\")(\n lwd = element$linewidth,\n col = element$colour,\n fill = fill_alpha(element$fill, element$alpha %||% NA),\n lty = element$linetype,\n lineend = element$lineend,\n linejoin = element$linejoin,\n linemitre = element$linemitre\n )\n } else {\n gp <- gpar(\n lwd = ggfun(\"len0_null\")(linewidth * .pt),\n col = colour,\n fill = fill,\n lty = linetype\n )\n element_gp <- gpar(\n lwd = ggfun(\"len0_null\")(element$linewidth * .pt),\n col = element$colour,\n fill = fill_alpha(element$fill, element$alpha %||% NA),\n lty = element$linetype,\n lineend = element$lineend,\n linejoin = element$linejoin,\n linemitre = element$linemitre\n )\n }\n grid::polygonGrob(\n x = x, y = y,\n gp = ggfun(\"modify_list\")(element_gp, gp), ...\n )\n}\n\n#' Theme curve elements\n#'\n#' Draw curve.\n#'\n#' @inheritParams element_polygon\n#' @inheritParams grid::curveGrob\n#' @param arrow.fill Fill colour for arrows.\n#' @return A `element_curve` object\n#' @export\nelement_curve <- function(colour = NULL, linewidth = NULL, linetype = NULL,\n lineend = NULL, color = NULL, curvature = NULL,\n angle = NULL, ncp = NULL, shape = NULL,\n arrow = NULL, arrow.fill = NULL,\n inherit.blank = FALSE) {\n colour <- color %||% colour\n arrow.fill <- arrow.fill %||% colour\n arrow <- arrow %||% FALSE\n structure(\n list(\n colour = colour, linewidth = linewidth, linetype = linetype,\n lineend = lineend, curvature = curvature, angle = angle,\n ncp = ncp, shape = shape, arrow = arrow, arrow.fill = arrow.fill,\n inherit.blank = inherit.blank\n ),\n class = c(\"ggalign_element_curve\", \"element_curve\", \"element\")\n )\n}\n\n#' @importFrom grid gpar gTree gList\n#' @importFrom ggplot2 element_grob\n#' @export\nelement_grob.ggalign_element_curve <- function(element, x = 0:1, y = 0:1,\n colour = NULL, linewidth = NULL, linetype = NULL, lineend = NULL,\n arrow.fill = NULL,\n default.units = \"npc\",\n id = NULL,\n id.lengths = NULL, ...) {\n arrow <- if (is.logical(element$arrow) && !element$arrow) {\n NULL\n } else {\n element$arrow\n }\n if (is.null(arrow)) {\n arrow.fill <- colour\n element$arrow.fill <- element$colour\n }\n # The gp settings can override element_gp\n gp <- gpar(\n col = colour,\n fill = arrow.fill %||% colour,\n lwd = ggfun(\"len0_null\")(linewidth * .pt),\n lty = linetype,\n lineend = lineend\n )\n element_gp <- gpar(\n col = element$colour,\n fill = element$arrow.fill %||% element$colour,\n lwd = ggfun(\"len0_null\")(element$linewidth * .pt),\n lty = element$linetype,\n lineend = element$lineend\n )\n gp <- ggfun(\"modify_list\")(element_gp, gp)\n if (is.null(id)) {\n if (is.null(id.lengths)) {\n id <- vec_rep(1L, length(x))\n } else {\n id <- vec_rep_each(seq_along(id.lengths), id.lengths)\n }\n }\n index_list <- .subset2(vec_split(seq_along(x), id), \"val\")\n ans <- lapply(index_list, function(index) {\n grid::curveGrob(\n vec_slice(x, index),\n vec_slice(y, index),\n default.units = default.units,\n gp = gp[index],\n curvature = element$curvature,\n angle = element$angle,\n ncp = element$ncp,\n shape = element$shape,\n arrow = arrow,\n square = FALSE, squareShape = 1,\n inflect = FALSE, open = TRUE,\n ...\n )\n })\n gTree(children = inject(gList(!!!ans)))\n}\n\n##########################################################################\nelement_lengths <- function(.el, .fn, ...) {\n fields <- element_vec_fields(.el)\n if (is.null(fields)) 0L\n lengths(.el[fields])\n}\n\n#' Apply a function to the fields of an element object\n#'\n#' @description\n#' For an [`element`][ggplot2::element_blank] object, some fields are\n#' vectorized, while others are not. This function allows you to apply a\n#' function to the vectorized fields.\n#'\n#' The following helper functions are available:\n#'\n#' - `element_rep`: Applies [`rep()`].\n#' - `element_rep_len`: Applies [`rep_len()`].\n#' - `element_vec_recycle`: Applies [`vec_recycle()`][vctrs::vec_recycle].\n#' - `element_vec_rep`: Applies [`vec_rep()`][vctrs::vec_rep].\n#' - `element_vec_rep_each`: Applies [`vec_rep_each()`][vctrs::vec_rep_each].\n#' - `element_vec_slice`: Applies [`vec_slice()`][vctrs::vec_slice].\n#'\n#' @param .el An [`element`][ggplot2::element_blank] object.\n#' @param .fn The function to be applied to the vectorized fields of the element\n#' object.\n#' @param ... Additional arguments passed on to `fn`.\n#' @export\nelement_vec <- function(.el, .fn, ...) {\n fields <- element_vec_fields(.el)\n if (is.null(fields)) {\n return(.el)\n }\n .el[fields] <- lapply(.el[fields], function(value) {\n if (!is.null(value)) value <- .fn(value, ...)\n value\n })\n .el\n}\n\n#' @export\n#' @rdname element_vec\nelement_rep <- function(.el, ...) element_vec(.el, rep, ...)\n\n#' @param length.out Non-negative integer. The desired length of the output\n#' vector. Other inputs will be coerced to a double vector and the first element\n#' taken. Ignored if `NA` or invalid.\n#' @export\n#' @rdname element_vec\nelement_rep_len <- function(.el, length.out, ...) {\n element_vec(.el, rep_len, ..., length.out = length.out)\n}\n\n#' @inheritParams vctrs::vec_recycle\n#' @export\n#' @rdname element_vec\nelement_vec_recycle <- function(.el, size, ...) {\n element_vec(.el, vec_recycle, size = size, ...)\n}\n\n#' @inheritParams vctrs::vec_rep\n#' @export\n#' @rdname element_vec\nelement_vec_rep <- function(.el, times, ...) {\n element_vec(.el, vec_rep, times = times, ...)\n}\n\n#' @export\n#' @rdname element_vec\nelement_vec_rep_each <- function(.el, times, ...) {\n element_vec(.el, vec_rep_each, times = times, ...)\n}\n\n#' @inheritParams vctrs::vec_slice\n#' @importFrom grid is.unit\n#' @export\n#' @rdname element_vec\nelement_vec_slice <- function(.el, i, ...) {\n element_vec(.el, function(x) {\n if (is.unit(x)) x[i, ...] else vec_slice(x, i, ...)\n })\n}\n\nelement_vec_fields <- function(el) UseMethod(\"element_vec_fields\")\n\n#' @export\nelement_vec_fields.ggalign_element_polygon <- function(el) {\n c(\n \"fill\", \"colour\", \"linewidth\", \"linetype\",\n \"lineend\", \"linejoin\", \"linemitre\", \"alpha\"\n )\n}\n\n#' @export\nelement_vec_fields.element_blank <- function(el) NULL\n\n#' @export\nelement_vec_fields.element_polygon <- function(el) {\n c(\"fill\", \"colour\", \"linewidth\", \"linetype\")\n}\n\n#' @export\nelement_vec_fields.element_point <- function(el) {\n c(\"colour\", \"shape\", \"size\", \"fill\", \"stroke\")\n}\n\n#' @export\nelement_vec_fields.element_rect <- function(el) {\n c(\"fill\", \"colour\", \"linewidth\", \"linetype\")\n}\n\n#' @export\nelement_vec_fields.element_line <- function(el) {\n c(\"colour\", \"linewidth\", \"linetype\", \"lineend\")\n}\n\n#' @export\nelement_vec_fields.element_text <- function(el) {\n c(\n \"family\", \"face\", \"colour\", \"size\", \"hjust\", \"vjust\",\n \"angle\", \"lineheight\"\n )\n}\n\n#' @export\nelement_vec_fields.default <- function(el) stop_input_type(el, \"an element\")\n\n######################################################\n#' Remove scale expansion\n#'\n#' @param borders Which border should be removed? A string containing\n#' one or more of `r oxford_and(c(.tlbr, \"x\", \"y\"))`.\n#' @return An object which can be added to ggplot.\n#' @export\nno_expansion <- function(borders = \"tlbr\") {\n assert_string(borders, empty_ok = FALSE)\n if (grepl(\"[^tlbrxy]\", borders)) {\n cli_abort(sprintf(\n \"{.arg borders} can only contain the %s characters\",\n oxford_and(c(.tlbr, \"x\", \"y\"))\n ))\n }\n borders <- .subset(list(\n t = \"top\", l = \"left\", b = \"bottom\", r = \"right\",\n x = c(\"left\", \"right\"), y = c(\"bottom\", \"top\")\n ), split_position(borders))\n borders <- vec_unique(unlist(borders, recursive = FALSE, use.names = FALSE))\n # expansion in x-axis\n structure(list(borders = borders), class = c(\"ggalign_no_expansion\"))\n}\n\n#' @importFrom ggplot2 ggplot_add ggproto ggproto_parent\n#' @export\nggplot_add.ggalign_no_expansion <- function(object, plot, object_name, ...) {\n borders <- .subset2(object, \"borders\")\n ParentLayout <- plot$layout\n\n # tricks to ensure remove `coord` won't remove `no_expansion()`\n plot$layout <- ggproto(NULL, ParentLayout,\n setup_panel_params = function(self) {\n ParentCoord <- self$coord\n self$coord <- ggproto(NULL, ParentCoord,\n setup_panel_params = function(self, scale_x, scale_y,\n params = list()) {\n if (!is.null(scale_x)) {\n expansion <- scale_x$expand %|w|%\n if (packageVersion(\"ggplot2\") > \"3.5.2\") {\n ggfun(\"default_expansion\")(\n scale_y,\n # for ggplot2 > 3.5.2, expand was passed by\n # params\n expand = params$expand[c(4, 2)]\n )\n } else {\n ggfun(\"default_expansion\")(\n scale_y,\n # for ggplot2 > 3.5.2, expand was passed by\n # params\n expand = self$expand\n )\n }\n if (any(borders == \"left\")) {\n expansion[1:2] <- 0\n }\n if (any(borders == \"right\")) {\n expansion[3:4] <- 0\n }\n scale_x$expand <- expansion\n }\n if (!is.null(scale_y)) {\n expansion <- scale_y$expand %|w|%\n if (packageVersion(\"ggplot2\") > \"3.5.2\") {\n ggfun(\"default_expansion\")(\n scale_y,\n # for ggplot2 > 3.5.2, expand was passed by\n # params\n expand = params$expand[c(3, 1)]\n )\n } else {\n ggfun(\"default_expansion\")(\n scale_y,\n # for ggplot2 > 3.5.2, expand was passed by\n # params\n expand = self$expand\n )\n }\n if (any(borders == \"bottom\")) {\n expansion[1:2] <- 0\n }\n if (any(borders == \"top\")) {\n expansion[3:4] <- 0\n }\n scale_y$expand <- expansion\n }\n ggproto_parent(ParentCoord, self)$setup_panel_params(\n scale_x = scale_x, scale_y = scale_y, params = params\n )\n }\n )\n ggproto_parent(ParentLayout, self)$setup_panel_params()\n }\n )\n plot\n}\n"], ["/ggalign/R/link.R", "#' Define the links to connect a pair of observations\n#'\n#' @description\n#' This function allows users to define links between a pair of observations,\n#' facilitating the visualization of connections between related data points.\n#'\n#' @param .draw A function used to draw the links. The function must return a\n#' [`grob()`][grid::grob] object. If the function does not return a valid\n#' `grob`, no drawing will occur. The input data for the function should\n#' include a data frame with the coordinates of the pair of observations to\n#' be linked.\n#' @inheritParams .link_draw\n#' @seealso\n#' - [`link_line()`]\n#' - [`.link_draw()`]\n#' @importFrom rlang is_empty inject\n#' @importFrom grid gTree gList\n#' @export\nlink_draw <- function(.draw, ...) {\n if (!is.function(draw <- allow_lambda(.draw))) {\n cli_abort(\"{.arg .draw} must be a function\")\n }\n new_draw <- function(data) {\n ans <- lapply(data, draw)\n ans <- ans[vapply(ans, is.grob, logical(1L), USE.NAMES = FALSE)]\n if (!is_empty(ans)) inject(gList(!!!ans))\n }\n .link_draw(new_draw, ...)\n}\n\n#' @inherit link_draw title\n#'\n#' @description\n#' A base version of [`link_draw()`], optimized for performance. This function\n#' serves as the foundation for building other `link_*` functions that manage\n#' the drawing of links between pairs of observations.\n#'\n#' @param .draw A function used to draw the links. The function must return a\n#' [`grob()`][grid::grob] object. If the function does not return a valid\n#' `grob`, no drawing will occur. The input data for the function should be\n#' a list, where each item is a data frame containing the coordinates of\n#' the pair of observations.\n#' @inheritParams pair_links\n#' @seealso [`link_draw()`]\n#' @export\n.link_draw <- function(.draw, ...) {\n if (override_call(call <- caller_call())) {\n call <- current_call()\n }\n if (!is.function(draw <- allow_lambda(.draw))) {\n cli_abort(\"{.arg .draw} must be a function\", call = call)\n }\n links <- pair_links(...)\n structure(list(draw = draw, links = links), class = \"ggalign_link_draw\")\n}\n\n#' @export\nprint.ggalign_link_draw <- function(x, ...) {\n header <- sprintf(\"<%s>\", vec_ptype_full(x))\n cat(header, sep = \"\\n\")\n obj_print_data(.subset2(x, \"links\"))\n invisible(x)\n}\n\n#' Link the paired observations with a line\n#'\n#' @inheritParams .link_draw\n#' @param .element A [`element_line()`][ggplot2::element_line] object.\n#' Vectorized fields will be recycled to match the total number of groups, or\n#' you can wrap the element with [`I()`] to recycle to match the drawing\n#' groups. The drawing groups typically correspond to the product of the\n#' number of observations from both sides, as each pair of observations will\n#' be linked with a single line.\n#' @importFrom ggplot2 element_line\n#' @export\nlink_line <- function(..., .element = NULL) {\n assert_s3_class(.element, \"element_line\", allow_null = TRUE)\n default <- calc_element(\"ggalign.line\", complete_theme(theme_get()))\n if (is.null(.element)) {\n .element <- default\n } else {\n .element <- ggplot2::merge_element(.element, default)\n }\n ans <- .link_draw(.draw = function(data) {\n data <- lapply(data, function(d) {\n # if the link is only in one side, we do nothing\n if (vec_unique_count(.subset2(d, \".hand\")) < 2L) {\n return(NULL)\n }\n both <- .subset2(vec_split(d, .subset2(d, \".hand\")), \"val\")\n data <- cross_join(.subset2(both, 1L), .subset2(both, 2L))\n data_frame0(\n x = vec_interleave(\n (data$x.x + data$xend.x) / 2L,\n (data$x.y + data$xend.y) / 2L\n ),\n y = vec_interleave(\n (data$y.x + data$yend.x) / 2L,\n (data$y.y + data$yend.y) / 2L\n )\n )\n })\n if (inherits(.element, \"AsIs\")) {\n .element <- element_rep_len(.element,\n length.out = sum(list_sizes(data)) / 2L\n )\n } else {\n .element <- element_rep_len(.element, length.out = length(data))\n .element <- element_vec_rep_each(.element,\n times = list_sizes(data) / 2L\n )\n }\n data <- vec_rbind(!!!data)\n if (vec_size(data)) {\n element_grob(\n .element,\n x = data$x, y = data$y,\n id.lengths = vec_rep(2L, vec_size(data) / 2L),\n default.units = \"native\"\n )\n }\n }, ...)\n add_class(ans, \"ggalign_link_line\")\n}\n\n#' Link the paired observations with a quadrilateral\n#'\n#' @inheritParams .link_draw\n#' @inheritParams mark_tetragon\n#' @export\nlink_tetragon <- function(..., .element = NULL) {\n assert_s3_class(.element, \"element_polygon\", allow_null = TRUE)\n default <- calc_element(\"ggalign.polygon\", complete_theme(theme_get()))\n if (is.null(.element)) {\n .element <- default\n } else {\n .element <- ggplot2::merge_element(.element, default)\n }\n .link_draw(.draw = function(data) {\n data <- lapply(data, function(d) {\n # if the link is only in one side, we do nothing\n if (vec_unique_count(.subset2(d, \".hand\")) < 2L) {\n return(NULL)\n }\n both <- .subset2(vec_split(d, .subset2(d, \".hand\")), \"val\")\n both <- lapply(both, function(link) {\n # find the consecutive groups\n index <- .subset2(link, \"link_index\")\n oindex <- order(index)\n group <- cumsum(c(0L, diff(index[oindex])) != 1L)\n\n # restore the order\n group <- group[order(oindex)]\n\n # split link into groups\n .subset2(vec_split(link, group), \"val\")\n })\n both <- vec_expand_grid(\n hand1 = .subset2(both, 1L),\n hand2 = .subset2(both, 2L)\n )\n ans <- .mapply(function(hand1, hand2) {\n data_frame0(\n x = vec_c(\n min(hand1$x), max(hand1$xend),\n max(hand2$xend), min(hand2$x)\n ),\n y = vec_c(\n min(hand1$y), max(hand1$yend),\n max(hand2$yend), min(hand2$y)\n )\n )\n }, both, NULL)\n vec_rbind(!!!ans)\n })\n if (inherits(.element, \"AsIs\")) {\n .element <- element_rep_len(.element,\n length.out = sum(list_sizes(data)) / 4L\n )\n } else {\n .element <- element_rep_len(.element, length.out = length(data))\n .element <- element_vec_rep_each(.element,\n times = list_sizes(data) / 4L\n )\n }\n data <- vec_rbind(!!!data)\n if (vec_size(data)) {\n element_grob(\n .element,\n x = data$x, y = data$y,\n id.lengths = vec_rep(4L, vec_size(data) / 4L),\n default.units = \"native\"\n )\n }\n }, ...)\n}\n\n# preDraw:\n# - makeContext\n# - pushvpgp\n# - preDrawDetails: by default, do noting\n# makeContent:\n# drawDetails:\n# postDraw:\n# - postDrawDetails: by default, do noting\n# - popgrobvp\n#' @importFrom grid makeContent convertHeight convertWidth gList setChildren\n#' @export\nmakeContent.ggalignLinkTree <- function(x) {\n # Grab viewport information\n width <- convertWidth(unit(1, \"npc\"), \"mm\", valueOnly = TRUE)\n height <- convertHeight(unit(1, \"npc\"), \"mm\", valueOnly = TRUE)\n\n # Grab grob metadata\n full_data1 <- .subset2(x, \"full_data1\")\n full_data2 <- .subset2(x, \"full_data2\")\n direction <- .subset2(x, \"direction\")\n link_index_list <- .subset2(x, \"link_index\")\n data_index_list <- .subset2(x, \"data_index\")\n obs_size <- .subset2(x, \"obs_size\")\n\n # prepare output for current for loop\n coords <- vector(\"list\", 2L)\n names(coords) <- c(\"hand1\", \"hand2\")\n for (link in names(coords)) {\n link_index <- lapply(link_index_list, .subset2, link)\n data_index <- lapply(data_index_list, .subset2, link)\n # early exit and step into next cycle if no link\n if (all(vapply(link_index, is.null, logical(1L), USE.NAMES = FALSE))) {\n coords[link] <- list(link_index)\n next\n }\n full_breaks <- switch(link,\n hand1 = full_data1,\n hand2 = full_data2\n )\n\n spacing <- .subset2(x, switch(link,\n hand1 = \"spacing1\",\n hand2 = \"spacing2\"\n ))\n\n # each value represent an `observation`, for panel space, we use `NA`\n # obs arranged from left to top, and from bottom to top\n points <- unlist(vec_interleave(full_breaks, list(NA)), FALSE, FALSE)\n # remove the last panel space, shouldn't exist\n points <- points[-length(points)]\n sizes <- numeric(length(points))\n n_spacing <- length(full_breaks) - 1L\n\n # then, we define the link grobs\n if (is_horizontal(direction)) { # the link should be in left or right\n spacing <- convertHeight(spacing, \"mm\", valueOnly = TRUE)\n spacing <- scales::rescale(spacing, c(0, 1), from = c(0, height))\n sizes[is.na(points)] <- spacing\n obs_height <- (1 - spacing * n_spacing) / sum(!is.na(points))\n sizes[!is.na(points)] <- obs_height # nobs\n yend <- cumsum(sizes)\n link_x <- switch(link,\n hand1 = 0,\n hand2 = 1\n )\n # by default, the height for each observation is `1`,\n # if we define obs size, we just re-scale it\n removed <- (1 - obs_size) * obs_height\n link_coord <- data_frame0(\n x = link_x, xend = link_x,\n y = yend - sizes + removed / 2L,\n yend = yend - removed / 2L\n )\n link_coord <- vec_slice(link_coord, !is.na(points))\n } else { # the link should be in top or bottom\n spacing <- convertWidth(spacing, \"mm\", valueOnly = TRUE)\n spacing <- scales::rescale(spacing, c(0, 1), from = c(0, width))\n sizes[is.na(points)] <- spacing\n obs_width <- (1 - spacing * n_spacing) / sum(!is.na(points))\n sizes[!is.na(points)] <- obs_width\n xend <- cumsum(sizes)\n link_y <- switch(link,\n hand1 = 1,\n hand2 = 0\n )\n # by default, the width for each observation is `1`,\n # if we define obs size, we just re-scale it\n removed <- (1 - obs_size) * obs_width\n link_coord <- data_frame0(\n x = xend - sizes + removed / 2L,\n xend = xend - removed / 2L,\n y = link_y, yend = link_y\n )\n link_coord <- vec_slice(link_coord, !is.na(points))\n }\n hand <- switch(link,\n hand1 = switch_direction(direction, \"left\", \"top\"),\n hand2 = switch_direction(direction, \"right\", \"bottom\")\n )\n nms <- names(link_index)\n link_panels <- vec_rep_each(names(full_breaks), list_sizes(full_breaks))\n coords[[link]] <- lapply(seq_along(link_index), function(i) {\n l_index <- .subset2(link_index, i)\n if (is.null(l_index)) return(NULL) # styler: off\n d_index <- .subset2(data_index, i)\n link <- vec_slice(link_coord, l_index)\n link$link_id <- nms[i]\n link$link_panel <- reorder(\n vec_slice(link_panels, l_index), l_index,\n order = FALSE\n )\n link$link_index <- l_index\n link$.hand <- hand\n link$.index <- d_index\n link\n })\n }\n\n # hand1 - hand2\n data <- .mapply(vec_rbind, coords, NULL)\n draw <- .subset2(x, \"draw\")\n if (is.grob(grob <- draw(data))) { # wrap single grob to a gList\n grob <- gList(grob)\n }\n if (is.gList(grob)) {\n setChildren(x, grob)\n } else {\n x\n }\n}\n"], ["/ggalign/R/layout-.R", "# Will ensure serialisation includes a link to the ggalign namespace\n# Copied from patchwork\nnamespace_link <- function() NULL\n\n# https://stackoverflow.com/questions/65817557/s3-methods-extending-ggplot2-gg-function\n# Here we use S4 object to override the double dispatch of `+.gg` method\n# TO-DO: use S7\n#' A `Layout` object\n#'\n#' A `Layout` object defines how to place the plots.\n#'\n#' @keywords internal\n# add suffix \"Proto\" to avoid conflict with ggplot2\nmethods::setClass(\"LayoutProto\",\n list(\n active = \"ANY\", # current active plot\n schemes = \"list\", # used to provide global parameters for all plots\n # control the layout, `theme` will also be used by `ggsave`\n titles = \"list\",\n annotation = \"list\", # To-Do add `pacth_titles` for layout\n theme = \"ANY\",\n `_namespace` = \"ANY\"\n ),\n prototype = list(\n active = NULL, titles = list(),\n annotation = list(), theme = NULL,\n `_namespace` = namespace_link\n )\n)\n\n#' @export\nprint.LayoutProto <- print.alignpatches\n\n#' @importFrom grid grid.draw\n#' @exportS3Method\ngrid.draw.LayoutProto <- grid.draw.alignpatches\n\n#' @export\nalignpatch.LayoutProto <- function(x) alignpatch(ggalign_build(x))\n\n#' Print Layout object\n#'\n#' @param object A `r rd_layout()`.\n#' @return The input invisiblely.\n#' @importFrom methods show\n#' @export\n#' @keywords internal\nmethods::setMethod(\"show\", \"LayoutProto\", function(object) {\n print(object)\n})\n\n#' Subset a `Layout` object\n#'\n#' Used by [`ggplot_build`][ggplot2::ggplot_build] and\n#' [`ggsave`][ggplot2::ggsave]\n#'\n#' @param x A `Layout` object\n#' @param name A string of slot name in `Layout` object.\n#' @return The slot value.\n#' @importFrom methods slot\n#' @export\n#' @keywords internal\nmethods::setMethod(\"$\", \"LayoutProto\", function(x, name) {\n slot(x, name)\n})\n\n###########################################################\ndefault_layout <- function(layout) { # setup default value for the layout\n layout@theme <- complete_theme(default_theme() + layout@theme)\n\n # we by default, collect all guides\n layout@schemes$scheme_align[\"guides\"] <- list(\n .subset2(.subset2(layout@schemes, \"scheme_align\"), \"guides\") %|w|% \"tlbr\"\n )\n\n # we by default, use `default_theme()`\n layout@schemes$scheme_theme <- update_scheme(\n .subset2(layout@schemes, \"scheme_theme\"),\n new_scheme_theme(complete_theme(default_theme()))\n )\n layout\n}\n\nis_linear <- function(layout) UseMethod(\"is_linear\")\n\n#' @export\nis_linear.StackLayout <- function(layout) TRUE\n\n#' @export\nis_linear.CircleLayout <- function(layout) FALSE\n\n###########################################################\ninherit_parent_layout_schemes <- function(layout, schemes) {\n if (is.null(schemes)) {\n return(layout@schemes)\n }\n inherit_schemes(layout@schemes, schemes)\n}\n\ninherit_parent_layout_theme <- function(layout, theme, spacing = NULL) {\n if (is.null(theme)) return(layout@theme) # styler: off\n # parent theme, set the global panel spacing,\n # so that every panel aligns well\n if (is.null(layout@theme)) return(theme) # styler: off\n ans <- theme + layout@theme\n if (is.null(spacing)) return(ans) # styler: off\n switch(spacing,\n x = ans + theme(\n panel.spacing.x = calc_element(\"panel.spacing.x\", theme)\n ),\n y = ans + theme(\n panel.spacing.y = calc_element(\"panel.spacing.y\", theme)\n )\n )\n}\n\n############################################################\n#' Get the statistics from the layout\n#'\n#' @param x A `r rd_layout()`.\n#' @inheritParams rlang::args_dots_used\n#' @return The statistics\n#' @export\nggalign_stat <- function(x, ...) {\n UseMethod(\"ggalign_stat\")\n}\n\n#' @param position A string of `r oxford_or(.TLBR)`.\n#' @export\n#' @rdname ggalign_stat\nggalign_stat.QuadLayout <- function(x, position, ...) {\n ggalign_stat(x = slot(x, position), ...)\n}\n\n#' @param what A single number or string of the plot elements in the stack\n#' layout.\n#' @export\n#' @rdname ggalign_stat\nggalign_stat.StackLayout <- function(x, what, ...) {\n plot_list <- x@plot_list\n index <- vec_as_location2(\n what,\n n = length(plot_list),\n names = names(plot_list),\n missing = \"error\"\n )\n ggalign_stat(x = .subset2(plot_list, index), ...)\n}\n\n#' @export\nggalign_stat.CraftBox <- function(x, ...) {\n ggalign_stat(x@craftsman, ...)\n}\n\n#' @export\nggalign_stat.CraftAlign <- function(x, ...) {\n rlang::check_dots_empty()\n .subset2(x, \"statistics\")\n}\n\n#' @export\nggalign_stat.default <- function(x, ...) {\n cli_abort(sprintf(\"no statistics found for %s\", object_name(x)))\n}\n\n#############################################################\n#' Reports whether `x` is layout object\n#'\n#' @param x An object to test.\n#' @return A single boolean value.\n#' @examples\n#' is_layout(ggheatmap(1:10))\n#'\n#' @importFrom methods is\n#' @export\nis_layout <- function(x) is(x, \"LayoutProto\")\n\n#' @examples\n#' # for quad_layout()\n#' is_quad_layout(quad_alignb(1:10))\n#' is_quad_layout(quad_alignh(1:10))\n#' is_quad_layout(quad_alignv(1:10))\n#' is_quad_layout(quad_free(mtcars))\n#'\n#' @export\n#' @rdname is_layout\nis_quad_layout <- function(x) is(x, \"QuadLayout\")\n\n#' @examples\n#' # for stack_layout()\n#' is_stack_layout(stack_discrete(\"h\", 1:10))\n#' is_stack_layout(stack_continuous(\"h\", 1:10))\n#'\n#' @export\n#' @rdname is_layout\nis_stack_layout <- function(x) is(x, \"StackLayout\")\n\n#' @export\n#' @rdname is_layout\nis_stack_cross <- function(x) is(x, \"StackCross\")\n\n#' @export\n#' @rdname is_layout\nis_circle_layout <- function(x) is(x, \"CircleLayout\")\n\n#' @examples\n#' # for heatmap_layout()\n#' is_heatmap_layout(ggheatmap(1:10))\n#' @export\n#' @rdname is_layout\nis_heatmap_layout <- function(x) is(x, \"HeatmapLayout\")\n\n#' @examples\n#' is_ggheatmap(ggheatmap(1:10))\n#' @export\n#' @rdname is_layout\nis_ggheatmap <- is_heatmap_layout\n\nis_cross_layout <- function(x) is_stack_cross(x)\n"], ["/ggalign/R/alignpatch-ggplot2.R", "#' @export\nggalign_gtable.ggplot <- function(x) alignpatch(x)$patch_gtable()\n\n#' @export\nggalign_build.ggplot <- function(x) x\n\n##################################################\n#' @export\n#' @include alignpatch-build.R\nprint.patch_ggplot <- print.alignpatches\n\n#' @importFrom grid grid.draw\n#' @exportS3Method\ngrid.draw.patch_ggplot <- grid.draw.alignpatches\n\n#################################################\n#' @importFrom ggplot2 ggproto\n#' @export\nalignpatch.ggplot <- function(x) ggproto(NULL, PatchGgplot, plot = x)\n\n# ggplot2 has following grobs:\n# panel\n# axis: must follow panel\n# strip: must follow the panel\n# xlab/ylab: can be aligned or follow the panel\n# subtitle\n# title\n# caption\n# guide: can be collected or kept\n#' @importFrom ggplot2 ggplotGrob update_labels\n#' @include alignpatch-.R\nPatchGgplot <- ggproto(\"PatchGgplot\", Patch,\n set_guides = function(guides) guides,\n patch_gtable = function(self, theme, guides, plot = self$plot) {\n # extract patch titles --------------------------------\n patch_titles <- plot$ggalign_patch_labels\n\n # complete_theme() will ensure elements exist --------\n theme <- complete_theme(plot$theme)\n # here: we remove tick length when the tick is blank\n theme <- setup_tick_length_element(theme)\n plot$theme <- theme\n\n # build the grob -------------------------------------\n ans <- ggplotGrob(plot)\n strip_pos <- find_strip_pos(ans)\n # always add strips columns and/or rows\n ans <- add_strips(ans, strip_pos)\n setup_patch_titles(ans, patch_titles = patch_titles, theme = theme)\n },\n respect = function(self, gt = self$gt) .subset2(gt, \"respect\"),\n\n #' @importFrom ggplot2 find_panel\n align_panel_sizes = function(self, panel_width, panel_height,\n gt = self$gt) {\n panel_pos <- find_panel(gt)\n rows <- c(.subset2(panel_pos, \"t\"), .subset2(panel_pos, \"b\"))\n cols <- c(.subset2(panel_pos, \"l\"), .subset2(panel_pos, \"r\"))\n respect <- .subset2(gt, \"respect\")\n if (rows[1L] == rows[2L] && cols[1L] == cols[2L]) {\n if (respect) {\n can_set_width <- is.na(as.numeric(panel_width))\n can_set_height <- is.na(as.numeric(panel_height))\n w <- .subset2(gt, \"widths\")[LEFT_BORDER + 1L]\n h <- .subset2(gt, \"heights\")[TOP_BORDER + 1L]\n if (can_set_width && can_set_height) {\n panel_width <- w\n panel_height <- h\n } else if (can_set_width) {\n panel_width <- as.numeric(w) / as.numeric(h) * panel_height\n } else if (can_set_height) {\n panel_height <- as.numeric(h) / as.numeric(w) * panel_width\n } else {\n respect <- FALSE\n }\n }\n } else {\n respect <- FALSE\n }\n list(width = panel_width, height = panel_height, respect = respect)\n },\n\n #' @importFrom gtable gtable_add_grob gtable_height gtable_width\n #' @importFrom grid unit viewport\n #' @importFrom ggplot2 find_panel\n free_border = function(self, borders, gt = self$gt) {\n panel_pos <- find_panel(gt)\n for (border in borders) {\n if (border == \"top\") {\n gt <- liberate_area(\n gt,\n 1L,\n 1L,\n .subset2(panel_pos, \"t\") - 1L,\n ncol(gt),\n clip = \"off\",\n name = \"free-border-top\",\n vp = ~ viewport(\n y = 0L, just = \"bottom\",\n height = gtable_height(.x)\n )\n )\n } else if (border == \"left\") {\n gt <- liberate_area(\n gt,\n 1L,\n 1L,\n nrow(gt),\n .subset2(panel_pos, \"l\") - 1L,\n clip = \"off\",\n name = \"free-border-left\",\n vp = ~ viewport(\n x = 1L, just = \"right\",\n width = gtable_width(.x)\n )\n )\n } else if (border == \"bottom\") {\n gt <- liberate_area(\n gt,\n .subset2(panel_pos, \"b\") + 1L,\n 1L,\n nrow(gt),\n ncol(gt),\n clip = \"off\",\n name = \"free-border-bottom\",\n vp = ~ viewport(\n y = 1L, just = \"top\",\n height = gtable_height(.x)\n )\n )\n } else if (border == \"right\") {\n gt <- liberate_area(\n gt,\n 1L,\n .subset2(panel_pos, \"r\") + 1L,\n nrow(gt),\n ncol(gt),\n clip = \"off\",\n name = \"free-border-right\",\n vp = ~ viewport(\n x = 0L, just = \"left\",\n width = gtable_width(.x)\n )\n )\n }\n }\n gt\n },\n align_free_border = function(self, borders,\n t = NULL, l = NULL, b = NULL, r = NULL,\n gt = self$gt) {\n if (is.null(t) && is.null(l) && is.null(b) && is.null(r)) {\n return(gt)\n }\n # For free borders, we also align the margins\n for (border in borders) {\n i <- .subset2(.subset2(gt, \"layout\"), \"name\") ==\n sprintf(\"free-border-%s\", border)\n if (any(i)) {\n i <- which(i)\n gt$grobs[[i]] <- switch_position(\n border,\n Patch$align_border(l = l, r = r, gt = gt$grobs[[i]]),\n Patch$align_border(t = t, b = b, gt = gt$grobs[[i]])\n )\n }\n }\n gt\n },\n\n #' @importFrom ggplot2 find_panel\n #' @importFrom gtable is.gtable gtable_height gtable_width gtable_add_grob\n #' @importFrom grid grobHeight grobWidth viewport\n free_lab = function(self, labs, gt = self$gt) {\n panel_pos <- find_panel(gt)\n for (lab in labs) {\n name <- paste(\n switch_position(lab, \"xlab\", \"ylab\"),\n \"axis\", lab,\n sep = \"-\"\n )\n if (lab == \"top\") {\n panel_border <- .subset2(panel_pos, \"t\")\n gt <- liberate_area(\n gt,\n panel_border - 3L,\n .subset2(panel_pos, \"l\"),\n panel_border - 1L,\n .subset2(panel_pos, \"r\"),\n name = name,\n vp = ~ viewport(\n y = 0L, just = \"bottom\",\n height = gtable_height(.x)\n )\n )\n } else if (lab == \"left\") {\n panel_border <- .subset2(panel_pos, \"l\")\n gt <- liberate_area(\n gt,\n .subset2(panel_pos, \"t\"),\n panel_border - 3L,\n .subset2(panel_pos, \"b\"),\n panel_border - 1L,\n name = name,\n vp = ~ viewport(\n x = 1L, just = \"right\",\n width = gtable_width(.x)\n )\n )\n } else if (lab == \"bottom\") {\n panel_border <- .subset2(panel_pos, \"b\")\n gt <- liberate_area(\n gt,\n panel_border + 1L,\n .subset2(panel_pos, \"l\"),\n panel_border + 3L,\n .subset2(panel_pos, \"r\"),\n name = name,\n vp = ~ viewport(\n y = 1L, just = \"top\",\n height = gtable_height(.x)\n )\n )\n } else if (lab == \"right\") {\n panel_border <- .subset2(panel_pos, \"r\")\n gt <- liberate_area(\n gt,\n .subset2(panel_pos, \"t\"),\n panel_border + 1L,\n .subset2(panel_pos, \"b\"),\n panel_border + 3L,\n name = name,\n vp = ~ viewport(\n x = 0L, just = \"left\",\n width = gtable_width(.x)\n )\n )\n }\n }\n gt\n }\n)\n\n#' @importFrom ggplot2 calc_element\n#' @importFrom grid unit\nsetup_tick_length_element <- function(theme) {\n for (tick in c(\"x.top\", \"y.left\", \"x.bottom\", \"y.right\")) {\n for (axis in c(\"axis.minor\", \"axis\")) {\n blank <- inherits(calc_element(\n paste(axis, \"ticks\", tick, sep = \".\"), theme\n ), \"element_blank\")\n if (blank) { # No ticks, no length\n element <- paste(axis, \"ticks.length\", tick, sep = \".\")\n theme[[element]] <- unit(0, \"mm\")\n }\n }\n }\n theme\n}\n\n#' @importFrom gtable gtable_add_rows gtable_add_cols\n#' @importFrom ggplot2 find_panel\n#' @importFrom grid unit\nadd_strips <- function(gt, strip_pos) {\n panel_loc <- find_panel(gt)\n strip_pos <- switch(strip_pos, inside = 0L, outside = 2L) # styler: off\n layout <- .subset2(gt, \"layout\")\n if (!any(grepl(\"strip-b\", layout$name))) { # No strips\n gt <- gtable_add_rows(\n gt, unit(0L, \"mm\"),\n panel_loc$b + strip_pos\n )\n } else if (strip_pos == 2L && !any(layout$b == panel_loc$b + 2L)) {\n # Merge the strip-gap height into the axis and remove it. Only performed\n # if an axis exist\n gt$heights[panel_loc$b + 1L] <- sum(gt$heights[panel_loc$b + 1:2])\n gt <- gt[-(panel_loc$b + 2L), ]\n }\n if (!any(grepl(\"strip-t\", layout$name))) {\n gt <- gtable_add_rows(\n gt, unit(0L, \"mm\"),\n panel_loc$t - 1L - strip_pos\n )\n } else if (strip_pos == 2L && !any(layout$t == panel_loc$t - 2L)) {\n gt$heights[panel_loc$t - 1L] <- sum(gt$heights[panel_loc$t - 1:2])\n gt <- gt[-(panel_loc$t - 2L), ]\n }\n if (!any(grepl(\"strip-r\", layout$name))) {\n gt <- gtable_add_cols(\n gt, unit(0L, \"mm\"),\n panel_loc$r + strip_pos\n )\n } else if (strip_pos == 2L && !any(layout$r == panel_loc$r + 2L)) {\n gt$widths[panel_loc$r + 1L] <- sum(gt$widths[panel_loc$r + 1:2])\n gt <- gt[, -(panel_loc$r + 2L)]\n }\n if (!any(grepl(\"strip-l\", layout$name))) {\n gt <- gtable_add_cols(\n gt, unit(0L, \"mm\"),\n panel_loc$l - 1L - strip_pos\n )\n } else if (strip_pos == 2L && !any(layout$l == panel_loc$l - 2L)) {\n gt$widths[panel_loc$l - 1L] <- sum(gt$widths[panel_loc$l - 1:2])\n gt <- gt[, -(panel_loc$l - 2L)]\n }\n gt\n}\n\n# theme(strip.placement)\n#' @importFrom ggplot2 find_panel\nfind_strip_pos <- function(gt) {\n panel_loc <- find_panel(gt)\n layout <- .subset2(gt, \"layout\")\n nms <- .subset2(layout, \"name\")\n ind <- grep(\"strip-t\", nms)\n if (length(ind) != 0L && panel_loc$t - min(layout$t[ind]) != 1L) {\n return(\"outside\")\n }\n ind <- grep(\"strip-l\", nms)\n if (length(ind) != 0L && panel_loc$l - min(layout$l[ind]) != 1L) {\n return(\"outside\")\n }\n ind <- grep(\"strip-r\", nms)\n if (length(ind) != 0L && max(layout$r[ind]) - panel_loc$r != 1L) {\n return(\"outside\")\n }\n ind <- grep(\"strip-b\", nms)\n if (length(ind) != 0L && max(layout$b[ind]) - panel_loc$b != 1L) {\n return(\"outside\")\n }\n \"inside\"\n}\n"], ["/ggalign/R/raster-magick.R", "#' Rasterize the ggplot layers\n#'\n#' The function rasterizes input graphical objects (e.g., grob, layer, ggplot)\n#' and optionally processes the resulting raster using magick, a powerful image\n#' manipulation library. This allows for advanced graphical transformations\n#' directly within the plotting pipeline.\n#'\n#' @param x An object to rasterize, can be a [`grob()`][grid::grob],\n#' [`layer()`][ggplot2::layer], [`ggplot()`][ggplot2::ggplot], or a list of such\n#' objects.\n#'\n#' @inheritParams rlang::args_dots_empty\n#' @inheritParams magickGrob\n#' @examples\n#' # Currently, `magick` package require R >= 4.1.0\n#' if (requireNamespace(\"magick\")) {\n#' # data generated code was copied from `ComplexHeatmap`\n#' set.seed(123)\n#' small_mat <- matrix(rnorm(56), nrow = 7)\n#' rownames(small_mat) <- paste0(\"row\", seq_len(nrow(small_mat)))\n#' colnames(small_mat) <- paste0(\"column\", seq_len(ncol(small_mat)))\n#' ggheatmap(small_mat, aes(.x, .y), filling = NULL) +\n#' raster_magick(geom_tile(aes(fill = value)), res = 20)\n#'\n#' ggheatmap(small_mat, aes(.x, .y), filling = NULL) +\n#' # Use `magick::filter_types()` to check available `filter` arguments\n#' raster_magick(\n#' geom_tile(aes(fill = value)),\n#' magick = function(image) {\n#' magick::image_resize(image,\n#' geometry = \"50%x\", filter = \"Lanczos\"\n#' )\n#' }\n#' )\n#' }\n#' @return An object with the same class of the input.\n#' @seealso [`magickGrob()`]\n#' @export\nraster_magick <- function(x, magick = NULL, ...,\n res = NULL, interpolate = FALSE,\n vp = NULL) {\n rlang::check_installed(\"magick\", \"to use `raster_magick()`\")\n if (!is.null(magick) && !is.function(magick <- allow_lambda(magick))) {\n cli_abort(\"{.arg magick} must be a function\")\n }\n assert_number_whole(res, min = 1, allow_null = TRUE)\n assert_bool(interpolate)\n raster_magick0(\n x = x, ..., magick = magick,\n res = res, interpolate = interpolate,\n vp = vp\n )\n}\n\n# Used to do the actual process, but won't check the arguments\n#' @keywords internal\nraster_magick0 <- function(x, ...) {\n UseMethod(\"raster_magick0\")\n}\n\n#' @importFrom ggplot2 ggproto ggproto_parent\n#' @export\nraster_magick0.Layer <- function(x, ...) {\n ggproto(\n NULL, x,\n draw_geom = function(self, data, layout) {\n grobs <- ggproto_parent(x, self)$draw_geom(data, layout)\n if (!inherits(layout$coord, \"CoordCartesian\")) {\n cli_warn(\n \"{.fn raster_magick} only works with {.fn coord_cartesian}.\"\n )\n return(grobs)\n }\n raster_magick0(grobs, ...)\n }\n )\n}\n\n#' @export\nraster_magick0.ggplot <- function(x, ...) {\n x$layers <- lapply(x$layers, raster_magick0, ...)\n x\n}\n\n#' @export\nraster_magick0.list <- function(x, ...) lapply(x, raster_magick0, ...)\n\n#' @export\nraster_magick0.grob <- function(x, magick = NULL, ...,\n res = NULL, interpolate = FALSE,\n vp = NULL) {\n rlang::check_dots_empty()\n magickGrob0(\n grob = x, magick = magick,\n res = res, interpolate = interpolate, vp = vp\n )\n}\n\n#' @export\nraster_magick0.gList <- raster_magick0.grob\n\n#' @export\nraster_magick0.default <- function(x, ...) {\n cli_abort(\"Cannot rasterize {.obj_type_friendly {x}}\")\n}\n"], ["/ggalign/R/fortify-matrix-list.R", "#' Convert the shape of a list for fortify method\n#'\n#' @param data A list\n#' @param shape Not used currently.\n#' @seealso [`fortify_matrix.list_upset()`]\n#' @family tune\n#' @export\ntune.list <- function(data, shape = NULL) {\n if (!is.null(shape)) {\n cli_abort(\"{.arg shape} cannot be used currently for {.cls list} object\")\n }\n new_tune(data, class = \"list_upset\")\n}\n\n#' Build a Matrix for UpSet plot\n#'\n#' @description\n#' `r lifecycle::badge('experimental')`\n#'\n#' This function converts a list into a matrix format suitable for creating an\n#' UpSet plot. It always returns a matrix for a `horizontal` UpSet plot.\n#' @inheritParams rlang::args_dots_empty\n#' @param data A list of sets.\n#' @param mode A string of `r oxford_or(c(\"distinct\", \"intersect\", \"union\"))`\n#' indicates the mode to define the set intersections. Check\n#' \n#' for details.\n#' @inheritParams fortify_matrix\n#' @section ggalign attributes:\n#' - `intersection_sizes`: An integer vector indicating the size of each\n#' intersection.\n#' - `set_sizes`: An integer vector indicating the size of each set.\n#' @seealso [`tune.list()`]\n#' @family fortify_matrix\n#' @aliases fortify_matrix.list\n#' @export\nfortify_matrix.list_upset <- function(data, mode = \"distinct\", ...,\n data_arg = NULL, call = NULL) {\n call <- call %||% current_call()\n rlang::check_dots_empty(call = call)\n mode <- arg_match0(mode, c(\"distinct\", \"intersect\", \"union\"),\n error_call = call\n )\n data <- lapply(tune_data(data), function(x) {\n vec_unique(vec_slice(x, !vec_detect_missing(x)))\n })\n data <- list_drop_empty(data)\n if (length(data) == 0L) {\n cli::cli_abort(\n \"No valid data: All input lists are either empty or contain only missing values.\",\n call = call\n )\n }\n\n # Based on the explanation from\n # https://jokergoo.github.io/ComplexHeatmap-reference/book/upset-plot.html\n action <- switch(mode,\n distinct = function(data, intersection) {\n out <- NULL\n for (i in which(intersection)) {\n if (is.null(out)) {\n out <- .subset2(data, i)\n } else if (vec_size(out) == 0L) { # early exit for empty items\n return(out)\n } else {\n out <- vec_set_intersect(out, .subset2(data, i))\n }\n }\n for (i in which(!intersection)) {\n if (vec_size(out) == 0L) { # early exit for empty items\n return(out)\n }\n out <- vec_set_difference(out, .subset2(data, i))\n }\n return(out)\n },\n intersect = function(data, intersection) {\n out <- NULL\n for (i in which(intersection)) {\n if (is.null(out)) {\n out <- .subset2(data, i)\n } else if (vec_size(out) == 0L) { # early exit for empty items\n return(out)\n } else {\n out <- vec_set_intersect(out, .subset2(data, i))\n }\n }\n out\n },\n union = function(data, intersection) {\n Reduce(vec_set_union, .subset(data, intersection))\n }\n )\n\n intersection <- logical(vec_size(data)) # template\n intersection_and_size <- lapply(\n seq_len(vec_size(intersection)),\n function(n) {\n # generate all possible intersections\n utils::combn(vec_size(intersection), n, function(index) {\n intersection[index] <- TRUE\n list(\n intersection = intersection,\n # for each intersection, we define the size\n size = vec_size(action(data, intersection))\n )\n }, simplify = FALSE)\n }\n )\n\n # https://en.wikipedia.org/wiki/UpSet_plot\n # UpSets can be used horizontally and vertically.\n # In a vertical UpSet plot, the columns of the matrix correspond to the\n # sets, the rows correspond to the intersections.\n # we by default use `horizontal` upset, the rows of the matrix correspond\n # to the sets, the columns correspond to the intersections.\n ans <- list_transpose(unlist(intersection_and_size, FALSE, FALSE))\n intersections <- inject(cbind(!!!.subset2(ans, \"intersection\")))\n rownames(intersections) <- names(data)\n intersection_sizes <- unlist(.subset2(ans, \"size\"), FALSE, FALSE)\n keep <- intersection_sizes > 0L # remove intersection without items\n intersections <- intersections[, keep, drop = FALSE]\n intersection_sizes <- intersection_sizes[keep]\n ggalign_data_set(intersections,\n intersection_sizes = intersection_sizes,\n set_sizes = list_sizes(data),\n upset_mode = mode\n )\n}\n"], ["/ggalign/R/alignpatch-alignpatches.R", "#' @importFrom ggplot2 ggproto\n#' @export\nalignpatch.alignpatches <- function(x) {\n ggproto(NULL, PatchAlignpatches, plot = x)\n}\n\n#' @noRd\nPatchAlignpatches <- ggproto(\"PatchAlignpatches\", Patch,\n set_guides = function(self, guides) guides,\n #' @importFrom gtable gtable gtable_add_grob\n #' @importFrom grid unit\n #' @importFrom ggplot2 wrap_dims calc_element zeroGrob theme_get\n #' @importFrom S7 prop\n patch_gtable = function(self, theme = theme_get(), guides = NULL,\n top_level = FALSE, plot = self$plot) {\n patches <- lapply(prop(plot, \"plots\"), alignpatch)\n layout <- prop(plot, \"layout\")\n\n # get the design areas and dims ------------------\n panel_widths <- .subset2(layout, \"widths\")\n panel_heights <- .subset2(layout, \"heights\")\n if (is.null(area <- .subset2(layout, \"area\"))) {\n if (is.null(layout$ncol) && length(panel_widths) > 1L) {\n layout$ncol <- length(panel_widths)\n }\n if (is.null(layout$nrow) && length(panel_heights) > 1L) {\n layout$nrow <- length(panel_heights)\n }\n dims <- wrap_dims(\n length(patches),\n .subset2(layout, \"nrow\"),\n .subset2(layout, \"ncol\")\n )\n area <- create_area(\n dims[2L], dims[1L],\n .subset2(layout, \"byrow\")\n )\n } else {\n dims <- c(max(field(area, \"b\")), max(field(area, \"r\")))\n }\n\n # filter `plots` based on the design areas --------------------\n if (vec_size(area) < vec_size(patches)) {\n cli_warn(\n \"Too few patch areas to hold all plots. Dropping plots\"\n )\n plots <- vec_slice(patches, vec_seq_along(area))\n } else {\n area <- vec_slice(area, seq_along(patches))\n }\n\n # remove NULL patch -----------------------------------\n keep <- !vapply(patches, is.null, logical(1L), USE.NAMES = FALSE)\n patches <- vec_slice(patches, keep)\n\n # if no plots, we return empty gtable -----------------\n if (is_empty(patches)) return(make_patch_table()) # styler: off\n self$patches <- patches\n\n # add borders to patch --------------------------------\n area <- vec_slice(area, keep)\n for (i in seq_along(patches)) {\n patches[[i]]$borders <- c(\n if (field(area, \"t\")[i] == 1L) \"top\" else NULL,\n if (field(area, \"l\")[i] == 1L) \"left\" else NULL,\n if (field(area, \"b\")[i] == .subset(dims, 1L)) {\n \"bottom\"\n } else {\n NULL\n },\n if (field(area, \"r\")[i] == .subset(dims, 2L)) {\n \"right\"\n } else {\n NULL\n }\n )\n }\n\n # we inherit parameters from the parent --------------------\n # by default, we won't collect any guide legends\n parent_guides <- guides\n guides <- .subset2(layout, \"guides\") %|w|% parent_guides\n\n # by default, we use ggplot2 default theme\n if (!is.null(prop(plot, \"theme\"))) theme <- theme + prop(plot, \"theme\")\n self$theme <- theme\n\n #######################################################\n # 1. patch_gtable: create the gtable for the patch, will set internal\n # `gt`\n # 2. `collect_guides`, can change the internal `gt`\n # 3. set_sizes:\n # - (To-Do) align_panel_spaces: can change the internal `gt`\n # - align_panel_sizes, can change the internal `gt`\n # - get_sizes, the widths and heights for the internal `gt`\n # 4. set_grobs: will call `align_border` and `split_gt`, return the\n # final gtable\n # setup gtable list ----------------------------------\n # Let each patch to determine whether to collect guides\n collected <- lapply(patches, function(patch) patch$set_guides(guides))\n collected_guides <- vector(\"list\", length(patches))\n\n # Always ensure that plots placed in a border collect their guides, if\n # any guides are to be collected in that border. This prevents overlap,\n # unless the guides will be collected by the parent layout.\n border_with_guides <- unique(unlist(collected, FALSE, FALSE))\n border_with_guides <- setdiff(border_with_guides, parent_guides)\n for (i in seq_along(patches)) {\n patch <- .subset2(patches, i)\n g <- union(\n .subset2(collected, i),\n intersect(border_with_guides, patch$borders)\n )\n patch$gt <- patch$patch_gtable(theme = theme, guides = g)\n collected_guides[i] <- list(patch$collect_guides(g))\n }\n\n # collect guides ---------------------------------------\n self$collected_guides <- collect_guides_list(collected_guides)\n\n # prepare the output ----------------------------------\n gt <- gtable(\n unit(rep(0L, TABLE_COLS * dims[2L]), \"null\"),\n unit(rep(0L, TABLE_ROWS * dims[1L]), \"null\")\n )\n\n # setup sizes for each row/column -----------------------\n gt <- self$set_sizes(\n area, dims, panel_widths, panel_heights,\n patches = patches, gt = gt\n )\n\n # add the panel position --------------------------------\n panel_pos <- list(\n t = TOP_BORDER + 1L,\n l = LEFT_BORDER + 1L,\n b = TABLE_ROWS * dims[1L] - BOTTOM_BORDER,\n r = TABLE_COLS * dims[2L] - RIGHT_BORDER\n )\n\n # add guides into the final gtable ----------------------\n if (top_level) {\n gt <- self$attach_guide_list(\n guide_list = self$collected_guides,\n theme = theme,\n panel_pos = panel_pos,\n gt = gt\n )\n }\n\n # setup grobs -------------------------------------------\n # For z in the gtable layout\n # 0L: layout background\n # 1L: background of the plot\n # 2L: plot table\n # 3L: foreground of the panel area\n # 4L: legends\n gt <- self$set_grobs(area, patches = patches, gt = gt)\n\n # add panel area ---------------------------------------\n gt <- gtable_add_grob(\n gt, list(zeroGrob()),\n t = .subset2(panel_pos, \"t\"),\n l = .subset2(panel_pos, \"l\"),\n b = .subset2(panel_pos, \"b\"),\n r = .subset2(panel_pos, \"r\"),\n z = 0L,\n name = \"panel-area\"\n )\n gt <- gtable_add_grob(\n gt,\n # foreground\n list(element_render(theme, \"panel.border\", fill = NA)),\n t = .subset2(panel_pos, \"t\"),\n l = .subset2(panel_pos, \"l\"),\n b = .subset2(panel_pos, \"b\"),\n r = .subset2(panel_pos, \"r\"),\n z = 3L,\n name = \"panel-foreground\"\n )\n\n # add background -----------------------------------\n if (!top_level && inherits(theme$plot.background, \"element\")) {\n gt <- gtable_add_grob(gt,\n element_render(theme, \"plot.background\"),\n t = 1L, l = 1L, b = -1L, r = -1L,\n name = \"background\", z = 0L\n )\n }\n\n # arrange the grobs\n idx <- order(.subset2(.subset2(gt, \"layout\"), \"z\"))\n gt$layout <- vec_slice(.subset2(gt, \"layout\"), idx)\n gt$grobs <- .subset(.subset2(gt, \"grobs\"), idx)\n gt\n },\n align_border = function(self, t = NULL, l = NULL, b = NULL, r = NULL,\n gt = self$gt, patches = self$patches) {\n if (is.null(t) && is.null(l) && is.null(b) && is.null(r)) {\n return(gt)\n }\n gt <- Patch$align_border(t = t, l = l, b = b, r = r, gt = gt)\n self$recurse_lapply(function(patch, grob, t, l, b, r) {\n # For each plot grob, we reuse it's method to set the border\n # sizes we only set the border sizes for plot in the border\n patch$align_border(t = t, l = l, b = b, r = r, gt = grob)\n }, t = t, l = l, b = b, r = r, gt = gt, patches = patches)\n },\n collect_guides = function(self, guides, gt = self$gt) {\n collected_guides <- self$collected_guides\n # for guides not collected by the top-level alignpatches, we attach the\n # guides\n self$gt <- self$attach_guide_list(\n collected_guides[\n vec_set_difference(names(collected_guides), guides)\n ],\n gt = gt\n )\n # return guides to be collected\n .subset(collected_guides, guides)\n },\n #' @importFrom grid is.unit unit\n set_sizes = function(self, area, dims,\n panel_widths, panel_heights,\n patches, gt = self$gt) {\n panel_widths <- rep(panel_widths, length.out = dims[2L])\n panel_heights <- rep(panel_heights, length.out = dims[1L])\n if (!is.unit(panel_widths)) panel_widths <- unit(panel_widths, \"null\")\n if (!is.unit(panel_heights)) {\n panel_heights <- unit(panel_heights, \"null\")\n }\n\n # For gtable with fixed aspect ratio -------------\n # if it cannot be fixed and aligned, the strip, axis and labs will be\n # attached into the panel\n # the plot to be fixed must in only one square of the area\n need_fix <- field(area, \"l\") == field(area, \"r\") &\n field(area, \"t\") == field(area, \"b\") &\n vapply(\n patches,\n function(patch) patch$respect(),\n logical(1L),\n USE.NAMES = FALSE\n )\n\n # here we respect the aspect ratio when necessary -----\n # if the width or height is NA, we will guess the panel widths or\n # heights based on the fixed aspect ratio\n guess_widths <- which(is.na(as.numeric(panel_widths)))\n guess_heights <- which(is.na(as.numeric(panel_heights)))\n cols <- field(area, \"l\")\n rows <- field(area, \"t\")\n patch_index <- order(\n # we first set the widths for the fixed plot with heights set by\n # user\n cols %in% guess_widths & !rows %in% guess_heights,\n # we then set the heights for the fixed plot with widths set by user\n !cols %in% guess_widths & rows %in% guess_heights,\n # we set widths and heights for remaning plots\n # based on the number of plots in each row/column in the descending\n # order\n c(table(rows[need_fix]))[as.character(rows)],\n c(table(cols[need_fix]))[as.character(cols)],\n decreasing = TRUE\n )\n respect_dims <- vector(\"list\", length(patches))\n\n # For plot cannot be fixed, we always attach strips, axes and labels\n # into the panel area\n for (i in patch_index) {\n row <- .subset(rows, i)\n col <- .subset(cols, i)\n # we always build a standard gtable layout from the gtable\n panel_sizes <- .subset2(patches, i)$align_panel_sizes(\n panel_width = panel_widths[col],\n panel_height = panel_heights[row]\n )\n panel_widths[col] <- .subset2(panel_sizes, \"width\")\n panel_heights[row] <- .subset2(panel_sizes, \"height\")\n if (.subset2(panel_sizes, \"respect\")) {\n respect_dims[[i]] <- matrix(c(\n (row - 1L) * TABLE_ROWS + TOP_BORDER + 1L,\n (col - 1L) * TABLE_COLS + LEFT_BORDER + 1L\n ), nrow = 1L)\n }\n }\n if (!is.null(respect_dims <- do.call(base::rbind, respect_dims))) {\n respect <- matrix(\n 0L, TABLE_ROWS * dims[1L],\n TABLE_COLS * dims[2L]\n )\n respect[respect_dims] <- 1L\n gt$respect <- respect\n }\n\n # we set the widths/heights with no fixed plots to be 1 null\n if (any(guess_widths <- is.na(as.numeric(panel_widths)))) {\n panel_widths[guess_widths] <- unit(1L, \"null\")\n }\n if (any(guess_heights <- is.na(as.numeric(panel_heights)))) {\n panel_heights[guess_heights] <- unit(1L, \"null\")\n }\n\n # setup sizes for non-panel rows/columns --------------\n sizes <- table_sizes(\n lapply(patches, function(patch) patch$get_sizes()),\n area, dims[2L], dims[1L]\n )\n widths <- .subset2(sizes, \"widths\")\n heights <- .subset2(sizes, \"heights\")\n\n # restore the panel sizes ----------------------------\n width_ind <- seq(LEFT_BORDER + 1L,\n by = TABLE_COLS, length.out = dims[2L]\n )\n height_ind <- seq(TOP_BORDER + 1L,\n by = TABLE_ROWS, length.out = dims[1L]\n )\n widths[width_ind] <- panel_widths\n heights[height_ind] <- panel_heights\n\n # setup the widths and heights -----------------------\n gt$widths <- widths\n gt$heights <- heights\n gt\n },\n\n #' @importFrom gtable gtable_add_grob\n set_grobs = function(self, area, patches, gt = self$gt) {\n widths <- .subset2(gt, \"widths\")\n heights <- .subset2(gt, \"heights\")\n for (i in seq_along(patches)) {\n loc <- vec_slice(area, i)\n # We must align the borders for the gtable grob with the\n # final plot area sizes\n l <- (field(loc, \"l\") - 1L) * TABLE_COLS + 1L\n l_widths <- widths[seq(l, l + LEFT_BORDER - 1L)]\n r <- field(loc, \"r\") * TABLE_COLS\n r_widths <- widths[seq(r - RIGHT_BORDER + 1L, r)]\n t <- (field(loc, \"t\") - 1L) * TABLE_ROWS + 1L\n t_heights <- heights[seq(t, t + TOP_BORDER - 1L)]\n b <- field(loc, \"b\") * TABLE_ROWS\n b_heights <- heights[seq(b - BOTTOM_BORDER + 1L, b)]\n patch <- .subset2(patches, i)\n\n grobs <- patch$split_gt(patch$align_border(\n t = t_heights, l = l_widths,\n b = b_heights, r = r_widths\n ))\n\n # then we add the plot ---------------------------------\n gt <- patch$add_plot(\n gt, .subset2(grobs, \"plot\"), t, l, b, r,\n name = paste(\"plot\", i, sep = \"-\")\n )\n\n # add background grob ----------------------------------\n if (!is.null(bg <- .subset2(grobs, \"bg\"))) {\n # we always add background in the beginning --------\n gt <- patch$add_background(\n gt, bg, t, l, b, r,\n name = paste(\"plot\", i, \"background\", sep = \"-\")\n )\n }\n\n # remove the grob from the patch, we wont' use it anymore\n patch$gt <- NULL\n }\n gt\n },\n attach_guide_list = function(self, guide_list, theme = self$theme,\n panel_pos = find_panel(gt),\n gt = self$gt) {\n if (length(guide_list)) {\n # https://github.com/tidyverse/ggplot2/blob/57ba97fa04dadc6fd73db1904e39a09d57a4fcbe/R/guides-.R#L512\n theme$legend.spacing <- theme$legend.spacing %||% unit(0.5, \"lines\")\n theme$legend.spacing.y <- calc_element(\"legend.spacing.y\", theme)\n theme$legend.spacing.x <- calc_element(\"legend.spacing.x\", theme)\n theme$legend.box.spacing <- calc_element(\n \"legend.box.spacing\", theme\n ) %||% unit(0.2, \"cm\")\n for (guide_pos in names(guide_list)) {\n gt <- self$attach_guides(\n guide_pos = guide_pos,\n guides = .subset2(guide_list, guide_pos),\n theme = theme, panel_pos = panel_pos,\n clip = \"off\", z = 4L, gt = gt\n )\n }\n }\n gt\n },\n #' @importFrom gtable gtable_width gtable_height\n #' @importFrom grid unit.c grobWidth grobHeight\n #' @importFrom ggplot2 find_panel zeroGrob\n attach_guides = function(self, guide_pos, guides, theme,\n panel_pos = find_panel(gt), ...,\n gt = self$gt) {\n guide_box <- assemble_guides(guides, guide_pos, theme = theme)\n name <- sprintf(\"guide-box-collected-%s\", guide_pos)\n if (guide_pos == \"inside\") {\n gt <- gtable_add_grob(\n x = gt,\n grobs = guide_box,\n t = panel_pos$t,\n l = panel_pos$l,\n b = panel_pos$b,\n r = panel_pos$r,\n name = name,\n ...\n )\n return(gt)\n }\n spacing <- .subset2(theme, \"legend.box.spacing\")\n if (guide_pos == \"left\") {\n if (is.gtable(guide_box)) {\n legend_width <- gtable_width(guide_box)\n widths <- unit.c(spacing, legend_width)\n } else {\n legend_width <- grobWidth(guide_box)\n widths <- unit(c(0, 0), \"mm\")\n }\n gt <- gtable_add_grob(\n x = gt,\n grobs = guide_box,\n t = panel_pos$t,\n l = panel_pos$l - 6L,\n b = panel_pos$b,\n name = name,\n ...\n )\n gt$widths[.subset2(panel_pos, \"l\") - 5:6] <- widths\n } else if (guide_pos == \"right\") {\n if (is.gtable(guide_box)) {\n legend_width <- gtable_width(guide_box)\n widths <- unit.c(spacing, legend_width)\n } else {\n legend_width <- grobWidth(guide_box)\n widths <- unit(c(0, 0), \"mm\")\n }\n gt <- gtable_add_grob(\n x = gt,\n grobs = guide_box,\n t = panel_pos$t,\n l = panel_pos$r + 6L,\n b = panel_pos$b,\n name = name,\n ...\n )\n gt$widths[.subset2(panel_pos, \"r\") + 5:6] <- widths\n } else if (guide_pos == \"bottom\") {\n location <- .subset2(theme, \"legend.location\") %||% \"panel\"\n place <- switch(location,\n panel = panel_pos,\n list(l = 1L, r = ncol(gt))\n )\n if (is.gtable(guide_box)) {\n legend_height <- gtable_height(guide_box)\n heights <- unit.c(spacing, legend_height)\n } else {\n legend_height <- grobHeight(guide_box)\n heights <- unit(c(0, 0), \"mm\")\n }\n gt <- gtable_add_grob(\n x = gt,\n grobs = guide_box,\n t = panel_pos$b + 6L,\n l = place$l,\n r = place$r,\n name = name,\n ...\n )\n gt$heights[.subset2(panel_pos, \"b\") + 5:6] <- heights\n } else if (guide_pos == \"top\") {\n location <- .subset2(theme, \"legend.location\") %||% \"panel\"\n place <- switch(location,\n panel = panel_pos,\n list(l = 1L, r = ncol(gt))\n )\n if (is.gtable(guide_box)) {\n legend_height <- gtable_height(guide_box)\n heights <- unit.c(spacing, legend_height)\n } else {\n legend_height <- grobHeight(guide_box)\n heights <- unit(c(0, 0), \"mm\")\n }\n gt <- gtable_add_grob(\n x = gt,\n grobs = guide_box,\n t = panel_pos$t - 6L,\n l = place$l,\n r = place$r,\n name = name,\n ...\n )\n gt$heights[.subset2(panel_pos, \"t\") - 5:6] <- heights\n }\n gt\n },\n\n #' @importFrom rlang is_empty\n free_border = function(self, borders, gt = self$gt,\n patches = self$patches) {\n gt <- self$recurse_lapply(\n function(patch, grob, t, l, b, r) {\n borders <- intersect(borders, c(t, l, b, r))\n if (is_empty(borders)) return(grob) # styler: off\n patch$free_border(borders = borders, gt = grob)\n },\n t = \"top\", l = \"left\", b = \"bottom\", r = \"right\",\n gt = gt, patches = patches\n )\n # for the collected guides, we should also liberate them\n guide_index <- sprintf(\"guide-box-collected-%s\", borders) %in%\n .subset2(.subset2(gt, \"layout\"), \"name\")\n if (any(guide_index)) {\n gt <- PatchGgplot$free_border(\n borders = borders[guide_index], gt = gt\n )\n }\n gt\n },\n align_free_border = function(self, borders,\n t = NULL, l = NULL, b = NULL, r = NULL,\n gt = self$gt, patches = self$patches) {\n gt <- self$recurse_lapply(\n function(patch, grob, t, l, b, r) {\n patch$align_free_border(\n borders = borders,\n t = t, l = l, b = b, r = r, gt = grob\n )\n },\n t = t, l = l, b = b, r = r,\n gt = gt, patches = patches\n )\n PatchGgplot$align_free_border(\n borders = borders,\n t = t, l = l, b = b, r = r, gt = gt\n )\n },\n\n #' @importFrom rlang is_empty\n free_lab = function(self, labs, gt = self$gt, patches = self$patches) {\n self$recurse_lapply(\n function(patch, grob, t, l, b, r) {\n labs <- intersect(labs, c(t, l, b, r))\n if (is_empty(labs)) return(grob) # styler: off\n patch$free_lab(labs = labs, gt = grob)\n },\n t = \"top\", l = \"left\", b = \"bottom\", r = \"right\",\n gt = gt, patches = patches\n )\n },\n # we apply function in each plot gtable in `gt`.\n #' @importFrom rlang is_empty\n recurse_lapply = function(self, .fn, t, l, b, r,\n gt = self$gt, patches = self$patches) {\n # if no plot provided, we'll do nothing\n if (is_empty(patches)) return(gt) # styler: off\n patch_index <- seq_along(patches)\n grobs <- .subset2(gt, \"grobs\")\n layout_index <- match(\n paste0(\"plot-\", patch_index),\n .subset2(.subset2(gt, \"layout\"), \"name\")\n )\n # For each grob, we reuse the method from the patch\n gt$grobs[layout_index] <- .mapply(function(layout_idx, patch_idx) {\n patch <- .subset2(patches, patch_idx)\n borders <- .subset2(patch, \"borders\")\n .fn(\n patch = patch,\n grob = .subset2(grobs, layout_idx),\n t = if (any(borders == \"top\")) t else NULL,\n l = if (any(borders == \"left\")) l else NULL,\n b = if (any(borders == \"bottom\")) b else NULL,\n r = if (any(borders == \"right\")) r else NULL\n )\n }, list(layout_idx = layout_index, patch_idx = patch_index), NULL)\n gt\n }\n)\n\n#' @importFrom grid convertHeight convertWidth unit\ntable_sizes <- function(sizes, area, ncol, nrow) {\n # `null` unit of the panel area will be converted into 0\n # we'll set the panel width and height afterward\n widths <- lapply(sizes, function(size) {\n convertWidth(.subset2(size, \"widths\"), \"mm\", valueOnly = TRUE)\n })\n widths <- vapply(seq_len(ncol * TABLE_COLS), function(i) {\n area_col <- (i - 1L) %/% TABLE_COLS + 1L\n col_loc <- i %% TABLE_COLS\n if (col_loc == 0L) col_loc <- TABLE_COLS\n area_side <- if (col_loc <= LEFT_BORDER + 1L) \"l\" else \"r\"\n idx <- field(area, area_side) == area_col\n if (any(idx)) {\n max(\n vapply(.subset(widths, idx), .subset, numeric(1L), col_loc),\n 0L\n )\n } else {\n 0L\n }\n }, numeric(1L), USE.NAMES = FALSE)\n heights <- lapply(sizes, function(size) {\n convertHeight(.subset2(size, \"heights\"), \"mm\", valueOnly = TRUE)\n })\n heights <- vapply(seq_len(nrow * TABLE_ROWS), function(i) {\n area_row <- recycle_each(i, TABLE_ROWS)\n row_loc <- recycle_whole(i, TABLE_ROWS)\n area_side <- if (row_loc <= TOP_BORDER + 1L) \"t\" else \"b\"\n idx <- field(area, area_side) == area_row\n if (any(idx)) {\n max(\n vapply(\n .subset(heights, idx), .subset, numeric(1L),\n row_loc,\n USE.NAMES = FALSE\n ),\n 0L\n )\n } else {\n 0L\n }\n }, numeric(1L), USE.NAMES = FALSE)\n list(widths = unit(widths, \"mm\"), heights = unit(heights, \"mm\"))\n}\n"], ["/ggalign/R/layout-chain-stack-build.R", "#' @export\nggalign_build.StackLayout <- function(x) {\n x <- default_layout(x)\n (stack_build(x) %||% align_plots(theme = x@theme)) +\n layout_title(\n title = .subset2(x@titles, \"title\"),\n subtitle = .subset2(x@titles, \"subtitle\"),\n caption = .subset2(x@titles, \"caption\")\n )\n}\n\n#' @param schemes,theme Parameters from parent layout\n#' @param extra_design layout parameters of the axis vertically with the stack.\n#' @noRd\nstack_build <- function(stack, schemes = NULL, theme = NULL,\n extra_design = NULL) {\n if (is_empty(stack@plot_list)) {\n return(NULL)\n }\n direction <- stack@direction\n position <- .subset2(stack@heatmap, \"position\")\n schemes <- inherit_parent_layout_schemes(stack, schemes)\n\n if (is_horizontal(direction)) {\n spacing <- \"y\"\n # for horizontal stack, we by default remove top and bottom spaces\n # if (!is.null(position)) {\n # schemes$scheme_align[\"free_spaces\"] <- list(\n # .subset2(schemes$scheme_align, \"free_spaces\") %|w|% \"tb\"\n # )\n # }\n } else {\n spacing <- \"x\"\n # for vertical stack, we by default remove left and right spaces\n # if (!is.null(position)) {\n # schemes$scheme_align[\"free_spaces\"] <- list(\n # .subset2(schemes$scheme_align, \"free_spaces\") %|w|% \"lr\"\n # )\n # }\n }\n theme <- inherit_parent_layout_theme(stack, theme, spacing = spacing)\n composer <- resolve_stack_layout(stack, schemes, theme, extra_design)\n if (is_empty(plots <- .subset2(composer, \"plots\"))) {\n return(NULL)\n }\n\n # arrange plots\n if (is.null(position)) { # for stack layout\n # sizes should be of length 3\n sizes <- stack@sizes\n # recycle the sizes when necessary\n if (length(sizes) == 1L) sizes <- rep(sizes, length.out = 3L)\n sizes <- sizes[\n c(\n .subset2(composer, \"left_or_top\"),\n TRUE,\n .subset2(composer, \"right_or_bottom\")\n )\n ]\n } else { # for the heatmap annotation\n sizes <- NA\n }\n plot <- align_plots(\n !!!plots,\n design = area(\n .subset2(composer, \"t\"),\n .subset2(composer, \"l\"),\n .subset2(composer, \"b\"),\n .subset2(composer, \"r\")\n ),\n widths = switch_direction(\n direction,\n do.call(unit.c, .subset2(composer, \"sizes\")),\n sizes\n ),\n heights = switch_direction(\n direction,\n sizes,\n do.call(unit.c, .subset2(composer, \"sizes\"))\n ),\n guides = .subset2(.subset2(schemes, \"scheme_align\"), \"guides\"),\n theme = stack@theme\n )\n\n # for annotation, we should always make it next to the main body\n if (is.null(position)) {\n return(plot)\n }\n plot <- free_vp(\n plot,\n x = switch(position,\n left = 1L,\n right = 0L,\n 0.5\n ),\n y = switch(position,\n top = 0L,\n bottom = 1L,\n 0.5\n ),\n just = switch(position,\n top = \"bottom\",\n left = \"right\",\n bottom = \"top\",\n right = \"left\"\n )\n )\n\n # whether we should override the `guides` collection for the whole\n # annotation stack\n free_guides <- .subset2(stack@heatmap, \"free_guides\")\n if (!is.waive(free_guides)) plot <- free_guide(plot, free_guides)\n # we also apply the `free_spaces` for the whole annotation stack\n free_spaces <- .subset2(\n .subset2(schemes, \"scheme_align\"), \"free_spaces\"\n ) %|w|% NULL\n if (!is.null(free_spaces)) {\n plot <- free_space(free_border(plot, free_spaces), free_spaces)\n }\n plot\n}\n\n#' @param schemes,theme Parameters for current stack, which have inherited\n#' parameters from the parent.\n#' @noRd\nresolve_stack_layout <- function(stack, schemes, theme, extra_design) {\n UseMethod(\"resolve_stack_layout\")\n}\n\n#' @export\nresolve_stack_layout.StackLayout <- function(stack, schemes, theme,\n extra_design) {\n plot_list <- stack@plot_list\n direction <- stack@direction\n position <- .subset2(stack@heatmap, \"position\")\n\n # we remove the plot without actual plot area\n keep <- vapply(plot_list, function(plot) {\n # we remove objects without plot area\n # Now, only `CraftBox` will contain `NULL`\n !is_craftbox(plot) || !is.null(plot@plot)\n }, logical(1L), USE.NAMES = FALSE)\n plot_list <- .subset(plot_list, keep)\n if (is_empty(plot_list)) return(NULL) # styler: off\n\n # we reorder the plots based on the `order` slot\n plot_order <- vapply(plot_list, function(plot) {\n if (is_layout(plot)) {\n .subset2(plot@plot_active, \"order\")\n } else {\n .subset2(plot@active, \"order\")\n }\n }, integer(1L), USE.NAMES = FALSE)\n plot_list <- .subset(plot_list, make_order(plot_order))\n\n # build the stack\n composer <- stack_composer(direction)\n\n # for `free_spaces`, if we have applied it in the whole stack layout\n # we shouln't use it for a single plot. Otherwise, the guide legends\n # collected by the layout will overlap with the axis of the plot in the\n # layout.\n #\n # this occurs in the annotation stack (`position` is not `NULL`).\n #\n # here is the example:\n # p1 <- ggplot(mtcars) +\n # geom_point(aes(mpg, disp))\n # p2 <- ggplot(mtcars) +\n # geom_boxplot(aes(gear, disp, group = gear, fill = gear))\n # p3 <- ggplot(mtcars) +\n # geom_bar(aes(gear)) +\n # facet_wrap(~cyl)\n # align_plots(\n # free_space(free_border(\n # align_plots(\n # # we shouldn't add free_space for the internal plot\n # free_space(\n # free_border(\n # p1 + scale_y_continuous(\n # expand = expansion(),\n # labels = ~ paste(\"very very long labels\", .x)\n # ),\n # \"l\"\n # ),\n # \"l\"\n # ),\n # p2 + theme(legend.position = \"left\"),\n # guides = \"l\"\n # ),\n # \"l\"\n # ), \"l\"),\n # p3 + theme(plot.margin = margin(l = 5, unit = \"cm\")),\n # ncol = 1\n # )\n stack_spaces <- .subset2(.subset2(schemes, \"scheme_align\"), \"free_spaces\")\n if (is_string(stack_spaces) && !is.null(position)) {\n released_spaces <- stack_spaces\n } else {\n released_spaces <- NULL\n }\n\n design <- setup_design(stack@design)\n stack_composer_add(\n plot_list,\n stack = stack,\n composer,\n schemes = schemes,\n theme = theme,\n design = design,\n extra_design = extra_design,\n direction = direction,\n position = position,\n released_spaces = released_spaces,\n previous_design = NULL\n )\n}\n\nmake_order <- function(order) {\n l <- length(order)\n index <- seq_len(l)\n\n # for order not set by user, we use heuristic algorithm to define the order\n need_action <- is.na(order)\n if (all(need_action)) { # shorthand for the usual way, we don't set any\n return(index)\n } else if (all(!need_action)) { # we won't need do something special\n return(order(order))\n }\n\n # 1. for outliers, we always put them in the two tail\n # 2. for order has been set and is not the outliers,\n # we always follow the order\n # 3. non-outliers were always regarded as the integer index\n used <- as.integer(order[!need_action & order >= 1L & order <= l])\n\n # we flatten user index to continuous integer sequence\n sequence <- vec_unrep(used) # key is the sequence start\n start <- .subset2(sequence, \"key\")\n end <- pmin(\n start + .subset2(sequence, \"times\") - 1L,\n vec_c(start[-1L] - 1L, l) # the next start - 1L\n )\n used <- .mapply(function(s, e) s:e, list(s = start, e = end), NULL)\n\n # following index can be used\n unused <- vec_set_difference(index, unlist(used, FALSE, FALSE))\n\n # we assign the candidate index to the order user not set.\n order[need_action] <- unused[seq_len(sum(need_action))]\n\n # make_order(c(NA, 1, NA)): c(2, 1, 3)\n # make_order(c(NA, 1, 3)): c(2, 1, 3)\n # make_order(c(NA, 1, 3, 1)): c(2, 4, 3, 1)\n order(order)\n}\n"], ["/ggalign/R/alignpatch-.R", "# here is copied from patchwork\n# we modified the `patchwork` package for following reasons:\n# 1. collect guides for each side (should be merged into patchwork, not allowed\n# to be merged: https://github.com/thomasp85/patchwork/issues/379).\n# 2. `free_*()` functions: see https://github.com/thomasp85/patchwork/issues/379\n# - `free_align()`: added\n# - `free_border()`: not added\n# - `free_lab()`: added\n# - `free_space()`: added\n# - `free_vp()`: not added\n# 3. Added titles around the plot top, left, bottom, and right\n# (`patch_titles()`)\nTABLE_ROWS <- 18L + 2L\nTABLE_COLS <- 15L + 2L\n\nTOP_BORDER <- 9L + 1L\nLEFT_BORDER <- 7L + 1L\nBOTTOM_BORDER <- 8L + 1L\nRIGHT_BORDER <- 7L + 1L\n\n# top-bottom\n# 1: margin\n# 2: tag\n# 3: title\n# 4: subtitle\n# 5: guide-box-top\n# 6: legend.box.spacing\n# feature: insert patch title\n# 7: xlab-t\n# strip.placement = \"inside\"/\"outside\"\n# 8: axis-t/strip-t\n# 9: strip-t/axis-t\n# 10: panel\n# 11: strip-b\n# 12: axis-b\n# 13: xlab-b\n# feature: insert patch title\n# 14: legend.box.spacing\n# 15: guide-box-bottom\n# 16: caption\n# 17: tag\n# 18: margin\n\n# left-right\n#\n# 1: margin\n# 2: tag\n# 3: guide-box-left\n# 4: legend.box.spacing\n# feature: insert patch title\n# 5: ylab-l\n# 6: axis-l\n# 8: panel\n# 10: axis-r\n# 11: ylab-r\n# feature: insert patch title\n# 12: legend.box.spacing\n# 13: guide-box-right\n# 14: tag\n# 15: margin\n\n.TLBR <- c(\"top\", \"left\", \"bottom\", \"right\")\n.tlbr <- c(\"t\", \"l\", \"b\", \"r\")\n\n# position is a single string contains `.tlbr`\nsetdiff_position <- function(x, y) gsub(sprintf(\"[%s]\", y), \"\", x)\nunion_position <- function(x, y) paste0(x, gsub(sprintf(\"[%s]\", x), \"\", y))\nsplit_position <- function(x) {\n vec_unique(.subset2(strsplit(x, \"\", fixed = TRUE), 1L))\n}\n\n# pos is an atomic character\nsetup_pos <- function(x) unname(complete_pos(split_position(x)))\n\nsetup_guides <- function(x) {\n .subset(\n c(t = \"top\", l = \"left\", b = \"bottom\", r = \"right\", i = \"inside\"),\n split_position(x)\n )\n}\n\ncomplete_pos <- function(x) {\n .subset(c(t = \"top\", l = \"left\", b = \"bottom\", r = \"right\"), x)\n}\n\nopposite_pos <- function(pos) {\n switch(pos,\n top = \"bottom\",\n bottom = \"top\",\n left = \"right\",\n right = \"left\"\n )\n}\n\n#' @importFrom ggplot2 zeroGrob\n#' @importFrom gtable gtable gtable_add_grob\n#' @importFrom grid unit\nmake_patch_table <- function() {\n widths <- unit(rep(0L, TABLE_COLS), \"mm\")\n widths[LEFT_BORDER + 1L] <- unit(1L, \"null\")\n heights <- unit(rep(0L, TABLE_ROWS), \"mm\")\n heights[TOP_BORDER + 1L] <- unit(1L, \"null\")\n ans <- gtable(widths, heights)\n gtable_add_grob(ans,\n list(zeroGrob()), TOP_BORDER + 1L, LEFT_BORDER + 1L,\n z = -Inf, name = \"panel-area\"\n )\n}\n\n#' Generate a plot grob.\n#'\n#' @param x An object to be converted into a [grob][grid::grob].\n#' @return A [`grob()`][grid::grob] object.\n#' @examples\n#' ggalignGrob(ggplot())\n#' @export\nggalignGrob <- function(x) {\n ggalign_gtable(ggalign_build(x))\n}\n\n# Now, we only define `ggalign_gtable` method for `alignpatches` and `ggplot`\n# `ggalign_build` must return these objects\nggalign_build <- function(x) UseMethod(\"ggalign_build\")\n\nggalign_gtable <- function(x) UseMethod(\"ggalign_gtable\")\n\n#' @export\nggalign_gtable.gtable <- function(x) x\n\n#' Prepare plots to be aligned with `align_plots`\n#'\n#' @param x A plot object to be prepared for alignment.\n#' @details\n#' `ggalign` has implement `alignpatch` method for following objects:\n#' - [`ggplot`][ggplot2::ggplot]\n#' - [`alignpatches`][align_plots]\n#' - [`wrapped_plot`][ggwrap]\n#' - [`patch`][patchwork::patchGrob]\n#' - [`wrapped_patch`][patchwork::wrap_elements]\n#' - [`spacer`][patchwork::plot_spacer]\n#'\n#' @return A `Patch` object.\n#' @examples\n#' alignpatch(ggplot())\n#' @seealso [`align_plots()`]\n#' @export\n#' @keywords internal\nalignpatch <- function(x) UseMethod(\"alignpatch\")\n\n#' @export\nalignpatch.default <- function(x) {\n cli_abort(\"Cannot align {.obj_type_friendly {x}}\")\n}\n\n#' @export\nalignpatch.NULL <- function(x) NULL\n\npatch_no_method <- function(plot, method) {\n cli_abort(\"no {.fn {method}} method for {.obj_type_friendly {plot}}\")\n}\n\n#' @importFrom ggplot2 ggproto\n#' @importFrom grid unit.c\nPatch <- ggproto(\n \"Patch\", NULL,\n # following fields will be added by `alignpatch()`\n plot = NULL,\n # following fields will be added in `alignpatches$patch_gtable()`\n # borders = NULL, gt = NULL,\n\n #' @param guides `guides` argument from the parent alignpatches\n #' @return Which side of guide legends should be collected by the parent\n #' `alignpatches` object?\n #' @noRd\n set_guides = function(self, guides) {\n patch_no_method(self$plot, \"set_guides\")\n },\n patch_gtable = function(self, theme, guides, plot = self$plot) {\n patch_no_method(self$plot, \"patch_gtable\")\n },\n collect_guides = function(self, guides, gt = self$gt) {\n if (is.null(guides)) return(list()) # styler: off\n layout <- .subset2(gt, \"layout\")\n grobs <- .subset2(gt, \"grobs\")\n guides_ind <- grep(\"guide-box\", .subset2(layout, \"name\"))\n guides_loc <- vec_slice(layout, guides_ind)\n collected_guides <- vector(\"list\", length(guides))\n names(collected_guides) <- guides\n panel_loc <- find_panel(gt)\n remove_grobs <- NULL\n for (guide_pos in guides) {\n guide_ind <- switch(guide_pos,\n top = .subset2(guides_loc, \"b\") < .subset2(panel_loc, \"t\"),\n left = .subset2(guides_loc, \"r\") < .subset2(panel_loc, \"l\"),\n bottom = .subset2(guides_loc, \"t\") > .subset2(panel_loc, \"b\"),\n right = .subset2(guides_loc, \"l\") > .subset2(panel_loc, \"r\"),\n inside = .subset2(guides_loc, \"t\") >= .subset2(panel_loc, \"t\") &\n .subset2(guides_loc, \"b\") <= .subset2(panel_loc, \"b\") &\n .subset2(guides_loc, \"l\") >= .subset2(panel_loc, \"l\") &\n .subset2(guides_loc, \"r\") <= .subset2(panel_loc, \"r\")\n )\n if (!any(guide_ind)) next\n guide_loc <- vec_slice(guides_loc, guide_ind)\n guide_ind <- .subset(guides_ind, guide_ind)\n remove_grobs <- c(guide_ind, remove_grobs)\n collected_guides[[guide_pos]] <- .subset2(grobs, guide_ind)\n\n # remove the guide spaces from the original gtable\n # for inside guide, no need to remove the spaces\n if (guide_pos == \"inside\") next\n\n space_pos <- switch(guide_pos,\n top = ,\n left = 1L,\n bottom = ,\n right = -1L\n )\n if (guide_pos %in% c(\"right\", \"left\")) {\n gt$widths[c(guide_loc$l, guide_loc$l + space_pos)] <- unit(\n c(0L, 0L), \"mm\"\n )\n } else if (guide_pos %in% c(\"bottom\", \"top\")) {\n gt$heights[c(guide_loc$t, guide_loc$t + space_pos)] <- unit(\n c(0L, 0L), \"mm\"\n )\n }\n }\n if (length(remove_grobs)) {\n gt <- subset_gt(gt, -remove_grobs, trim = FALSE)\n }\n self$gt <- gt\n collected_guides\n },\n respect = function(self, gt = self$gt) isTRUE(.subset2(gt, \"respect\")),\n align_panel_sizes = function(self, panel_width, panel_height,\n gt = self$gt) {\n list(width = panel_width, height = panel_height, respect = FALSE)\n },\n get_sizes = function(self, free = NULL, gt = self$gt) {\n ans <- .subset2(gt, \"heights\")\n if (any(free == \"t\")) {\n top <- unit(rep_len(0, TOP_BORDER), \"mm\")\n } else {\n top <- ans[seq_len(TOP_BORDER)]\n }\n if (any(free == \"b\")) {\n bottom <- unit(rep_len(0, BOTTOM_BORDER), \"mm\")\n } else {\n bottom <- ans[seq(length(ans) - BOTTOM_BORDER + 1L, length(ans))]\n }\n ans <- .subset2(gt, \"widths\")\n if (any(free == \"l\")) {\n left <- unit(rep_len(0, LEFT_BORDER), \"mm\")\n } else {\n left <- ans[seq_len(LEFT_BORDER)]\n }\n if (any(free == \"r\")) {\n right <- unit(rep_len(0, RIGHT_BORDER), \"mm\")\n } else {\n right <- ans[seq(length(ans) - RIGHT_BORDER + 1L, length(ans))]\n }\n list(\n widths = unit.c(left, unit(0, \"mm\"), right),\n heights = unit.c(top, unit(0, \"mm\"), bottom)\n )\n },\n align_border = function(self, t = NULL, l = NULL, b = NULL, r = NULL,\n gt = self$gt) {\n if (!is.null(t)) gt$heights[seq_along(t)] <- t\n if (!is.null(l)) gt$widths[seq_along(l)] <- l\n if (!is.null(b)) {\n n_row <- nrow(gt)\n gt$heights[seq(n_row - length(b) + 1L, n_row)] <- b\n }\n if (!is.null(r)) {\n n_col <- ncol(gt)\n gt$widths[seq(n_col - length(r) + 1L, n_col)] <- r\n }\n gt\n },\n split_gt = function(self, gt = self$gt) {\n isbg <- .subset2(.subset2(gt, \"layout\"), \"name\") == \"background\"\n if (any(isbg)) {\n bg <- .subset(.subset2(gt, \"grobs\"), isbg) # a list of background\n plot <- subset_gt(gt, !isbg, trim = FALSE)\n } else {\n bg <- NULL\n plot <- gt\n }\n list(bg = bg, plot = plot)\n },\n add_plot = function(self, gt, plot, t, l, b, r, name, z = 2L) {\n gtable_add_grob(\n gt,\n grobs = plot,\n t = t, l = l, b = b, r = r,\n name = name, z = z\n )\n },\n add_background = function(self, gt, bg, t, l, b, r, name, z = 1L) {\n gtable_add_grob(\n gt,\n grobs = bg,\n t = t, l = l, b = b, r = r,\n name = name, z = z\n )\n },\n free_border = function(self, borders, gt = self$gt) {\n patch_no_method(self$plot, \"free_border\")\n },\n align_free_border = function(self, borders,\n t = NULL, l = NULL, b = NULL, r = NULL,\n gt = self$gt) {\n patch_no_method(self$plot, \"align_free_border\")\n },\n free_lab = function(self, labs, gt = self$gt) {\n patch_no_method(self$plot, \"free_lab\")\n }\n)\n"], ["/ggalign/R/grid-grob-magick.R", "#' Rasterize a grob object with magick\n#'\n#' @param grob A [`grob()`][grid::grob]. Use [`patch()`] to convert any objects\n#' into a `grob`.\n#' @param magick A function (purrr-style formula is accepted) that takes an\n#' [`image_read()`][magick::image_read] object as input and returns an object\n#' compatible with [`as.raster()`][grDevices::as.raster]. You can use any of\n#' the `image_*()` functions from the **magick** package to process the raster\n#' image.\n#' @param res An integer sets the desired resolution in pixels.\n#' @inheritParams rlang::args_dots_empty\n#' @inheritParams grid::rasterGrob\n#' @return A `magickGrob` object.\n#' @export\nmagickGrob <- function(grob, magick = NULL, ...,\n res = NULL, interpolate = FALSE,\n name = NULL, vp = NULL) {\n rlang::check_installed(\"magick\", \"to use `magickGrob()`\")\n if (!is.null(magick) && !is.function(magick <- allow_lambda(magick))) {\n cli_abort(\"{.arg magick} must be a function\")\n }\n assert_number_whole(res, min = 1, allow_null = TRUE)\n assert_bool(interpolate)\n magickGrob0(\n grob = grob, magick = magick, ..., res = res,\n interpolate = interpolate, name = name, vp = vp\n )\n}\n\nmagickGrob0 <- function(grob, ...) UseMethod(\"magickGrob0\")\n\n#' @importFrom grid gTree\n#' @export\nmagickGrob0.grob <- function(grob, magick = NULL, ...,\n res = NULL, interpolate = FALSE,\n name = NULL, vp = NULL) {\n rlang::check_dots_empty()\n gTree(\n grob = grob, magick = magick, res = res,\n interpolate = interpolate, name = name, vp = vp,\n cl = \"magickGrob\"\n )\n}\n\n#' @importFrom grid gTree\n#' @export\nmagickGrob0.gList <- function(grob, ...) {\n magickGrob0(grob = gTree(children = grob), ...)\n}\n\n#' @importFrom grid editGrob\n#' @importFrom rlang inject\n#' @export\nmagickGrob0.magickGrob <- function(grob, magick = waiver(), ...,\n res = waiver(), interpolate = waiver(),\n name = waiver(), vp = waiver()) {\n rlang::check_dots_empty()\n params <- list(\n magick = magick, res = res,\n interpolate = interpolate, name = name, vp = vp\n )\n params <- params[!vapply(params, is.waive, logical(1L), USE.NAMES = FALSE)]\n inject(editGrob(grob, !!!params))\n}\n\n#' @export\nmagickGrob0.default <- function(grob, ...) {\n cli_abort(\"{.arg grob} must be a {.cls grob} object\")\n}\n\n# preDraw:\n# - makeContext\n# - pushvpgp\n# - preDrawDetails: by default, do noting\n# makeContent:\n# drawDetails:\n# postDraw:\n# - postDrawDetails: by default, do noting\n# - popgrobvp\n#' @importFrom grid makeContent unit convertHeight convertWidth viewport gList\n#' @export\nmakeContent.magickGrob <- function(x) {\n # Grab viewport information\n width <- convertWidth(unit(1, \"npc\"), \"pt\", valueOnly = TRUE)\n height <- convertHeight(unit(1, \"npc\"), \"pt\", valueOnly = TRUE)\n\n # Grab grob metadata\n plot_res <- convertWidth(unit(1, \"inch\"), \"pt\", valueOnly = TRUE)\n res <- .subset2(x, \"res\") %||% plot_res\n\n magick <- .subset2(x, \"magick\")\n interpolate <- .subset2(x, \"interpolate\")\n\n # Track current device\n old_dev <- grDevices::dev.cur()\n\n # Reset current device upon function exit\n on.exit(grDevices::dev.set(old_dev), add = TRUE)\n\n # open the magick raster device\n image <- magick::image_graph(\n width = width * res / plot_res,\n height = height * res / plot_res,\n bg = NA_character_, res = res,\n clip = FALSE, antialias = FALSE\n )\n\n # Render the grob\n grid::pushViewport(viewport())\n\n # Clean up the grob for rendering\n grid::grid.draw(.subset2(x, \"grob\")) # should respect the viewport of `x`\n grid::popViewport()\n grDevices::dev.off()\n on.exit(magick::image_destroy(image), add = TRUE)\n\n # run `magick` when necessary\n if (!is.null(magick)) image <- magick(image)\n\n # Use native raster instead\n raster <- grDevices::as.raster(image, native = TRUE)\n\n # Forward raster grob\n setChildren(x, children = gList(\n grid::rasterGrob(\n raster, # should contain current area of full viewport\n x = 0.5, y = 0.5,\n height = unit(height, \"pt\"),\n width = unit(width, \"pt\"),\n default.units = \"npc\",\n just = \"center\",\n interpolate = interpolate\n )\n ))\n}\n"], ["/ggalign/R/alignpatch-patch.R", "#' Convert Object into a Grob\n#'\n#' The `patch()` function is used by [`ggwrap()`] and [inset()] to convert\n#' objects into a [`grob`][grid::grob].\n#'\n#' @param x An object to be converted into a [`grob`][grid::grob].\n#' @param ... Additional arguments passed to specific methods.\n#' @return A [`grob`][grid::grob] object.\n#' @eval rd_collect_family(\"patch\", \"`patch` method collections\")\n#' @export\n#' @keywords internal\npatch <- function(x, ...) {\n UseMethod(\"patch\")\n}\n\n# Following methods much are copied from `cowplot` or `ggplotify`\n#' @export\npatch.default <- function(x, ...) {\n cli_abort(\"Cannot make grob from {.obj_type_friendly {x}}\")\n}\n\n#' @inherit patch title description return\n#' @inheritParams patch\n#' @param ... Not used currently.\n#' @family patch\n#' @export\npatch.grob <- function(x, ...) {\n rlang::check_dots_empty()\n x\n}\n\n#' @importFrom grid gTree\n#' @export\n#' @rdname patch.grob\npatch.gList <- function(x, ...) {\n rlang::check_dots_empty()\n # gLists need to be wrapped in a gTree\n gTree(children = x)\n}\n\n#' @importFrom ggplot2 ggplotGrob\n#' @inherit patch.grob\n#' @seealso [ggplot][ggplot2::ggplot]\n#' @family patch\n#' @export\npatch.ggplot <- function(x, ...) {\n ggplotGrob(x, ...)\n}\n\n#' @inherit patch.grob\n#' @seealso\n#' - [`patch_titles()`]\n#' - [`inset()`]\n#' - [`ggwrap()`]\n#' @family patch\n#' @export\npatch.patch_ggplot <- function(x, ...) {\n ggalignGrob(x, ...)\n}\n\n#' @inherit patch.grob\n#' @seealso [`alignpatches`][align_plots]\n#' @family patch\n#' @export\npatch.alignpatches <- function(x, ...) {\n ggalignGrob(x, ...)\n}\n\n#' @inherit patch.grob\n#' @seealso [`patchwork`][patchwork::patchworkGrob]\n#' @family patch\n#' @export\npatch.patchwork <- function(x, ...) {\n rlang::check_installed(\"patchwork\", \"to make grob from patchwork\")\n patchwork::patchworkGrob(x, ...)\n}\n\n#' @inherit patch.grob\n#' @seealso [`patch`][patchwork::patchGrob]\n#' @family patch\n#' @export\npatch.patch <- function(x, ...) {\n rlang::check_installed(\"patchwork\", \"to make grob from patch\")\n patchwork::patchGrob(x, ...)\n}\n\n#' @inherit patch.grob\n#' @param ... Graphical Parameters passed on to [par()][graphics::par].\n#' @inheritParams gridGraphics::echoGrob\n#' @seealso [`plot()`]\n#' @family patch\n#' @export\npatch.formula <- function(x, ..., device = NULL, name = NULL) {\n rlang::check_installed(\"gridGraphics\", \"to make grob from base plot\")\n gp <- graphics::par(..., no.readonly = TRUE)\n gridGraphics::echoGrob(\n function() {\n old_gp <- graphics::par(no.readonly = TRUE)\n graphics::par(gp)\n on.exit(try(graphics::par(old_gp)))\n suppressMessages(eval(x[[2]], attr(x, \".Environment\")))\n invisible(NULL)\n },\n name = name,\n device = device %||% offscreen\n )\n}\n\n#' @export\n#' @rdname patch.formula\npatch.function <- function(x, ..., device = NULL, name = NULL) {\n rlang::check_installed(\"gridGraphics\", \"to make grob from base plot\")\n gp <- graphics::par(..., no.readonly = TRUE)\n gridGraphics::echoGrob(\n function() {\n old_gp <- graphics::par(no.readonly = TRUE)\n graphics::par(gp)\n on.exit(try(graphics::par(old_gp)))\n suppressMessages(x())\n invisible(NULL)\n },\n name = name,\n device = device %||% offscreen\n )\n}\n\n#' @inherit patch.grob\n#' @inheritParams gridGraphics::echoGrob\n#' @seealso [`recordPlot()`][grDevices::recordPlot]\n#' @family patch\n#' @export\npatch.recordedplot <- function(x, ..., device = NULL) {\n rlang::check_installed(\"gridGraphics\", \"to make grob from recordedplot\")\n rlang::check_dots_empty()\n gridGraphics::echoGrob(x, device = device %||% offscreen)\n}\n\noffscreen <- function(width, height) {\n if (requireNamespace(\"ragg\", quietly = TRUE)) {\n ragg::agg_capture(width = width, height = height, units = \"in\")\n grDevices::dev.control(\"enable\")\n } else {\n grDevices::pdf(NULL, width = width, height = height)\n grDevices::dev.control(\"enable\")\n }\n}\n\n#' @inherit patch.grob\n#' @inheritDotParams grid::grid.grabExpr -expr -device\n#' @inheritParams grid::grid.grabExpr\n#' @seealso [`trellis`][lattice::trellis.object]\n#' @family patch\n#' @export\npatch.trellis <- function(x, ..., device = NULL) {\n grid::grid.grabExpr(expr = print(x), ..., device = device %||% offscreen)\n}\n\n#' @inherit patch.grob\n#' @param ... Additional arguments passed to [draw()][ComplexHeatmap::draw].\n#' @inheritParams grid::grid.grabExpr\n#' @seealso\n#' - [`Heatmap()`][ComplexHeatmap::Heatmap]\n#' - [`HeatmapAnnotation()`][ComplexHeatmap::HeatmapAnnotation]\n#' @family patch\n#' @export\npatch.Heatmap <- function(x, ..., device = NULL) {\n rlang::check_installed(\n \"ComplexHeatmap\",\n sprintf(\"to make grob from %s plot\", obj_type_friendly(x))\n )\n draw <- getExportedValue(\"ComplexHeatmap\", \"draw\")\n grid::grid.grabExpr(\n expr = draw(object = x, ...),\n device = device %||% offscreen\n )\n}\n\n#' @export\n#' @rdname patch.Heatmap\npatch.HeatmapList <- patch.Heatmap\n\n#' @export\n#' @rdname patch.Heatmap\npatch.HeatmapAnnotation <- patch.HeatmapList\n\n#' @inherit patch.grob\n#' @seealso [`pheatmap()`][pheatmap::pheatmap]\n#' @family patch\n#' @export\npatch.pheatmap <- function(x, ...) {\n rlang::check_dots_empty()\n .subset2(x, \"gtable\")\n}\n"], ["/ggalign/R/grid-utils.R", "#' @importFrom grid gpar\n#' @export\ngrid::gpar\n\n#' @importFrom grid unit\n#' @export\ngrid::unit\n\nis.gList <- function(x) inherits(x, \"gList\")\n\nis.gTree <- function(x) inherits(x, \"gTree\")\n\n#' @importFrom grid unitType absolute.size\nis_absolute_unit <- function(x) unitType(absolute.size(x)) != \"null\"\n\n#' @importFrom grid unitType\nis_null_unit <- function(x) unitType(x) == \"null\"\n\nis_null_grob <- function(x) inherits(x, c(\"zeroGrob\", \"null\"))\n\n#' @importFrom grid is.grob nullGrob\nensure_grob <- function(x, default = nullGrob()) {\n if (is.gList(x)) x <- gTree(children = x)\n if (is.grob(x)) x else default\n}\n\n# `current.transform()` transforms from *inches* within the current viewport to\n# *inches* on the overall device.\ngrid_solve_loc <- function(loc, trans, valueOnly = FALSE) {\n x <- grid::convertX(loc$x, \"inches\", valueOnly = TRUE)\n y <- grid::convertY(loc$y, \"inches\", valueOnly = TRUE)\n out <- matrix(c(x, y, rep_len(1, length(x))), ncol = 3L) %*%\n trans\n out <- list(x = out[, 1L, drop = TRUE], y = out[, 2L, drop = TRUE])\n if (!valueOnly) out <- lapply(out, unit, \"inches\")\n out\n}\n\nloc_device2vp <- function(x, y, valueOnly = FALSE) {\n assert_s3_class(x, \"unit\")\n assert_s3_class(y, \"unit\")\n if (length(x) != length(y)) {\n cli_abort(\"{.arg x} and {.arg y} must have the same length\")\n }\n assert_bool(valueOnly)\n grid_solve_loc(\n list(x = x, y = y),\n solve(grid::current.transform()),\n valueOnly = valueOnly\n )\n}\n\nloc_vp2device <- function(x, y, valueOnly = FALSE) {\n assert_s3_class(x, \"unit\")\n assert_s3_class(y, \"unit\")\n if (length(x) != length(y)) {\n cli_abort(\"{.arg x} and {.arg y} must have the same length\")\n }\n assert_bool(valueOnly)\n grid::deviceLoc(x, y, valueOnly = valueOnly)\n}\n\n# # allow the missing value in the unit for `str` method\n# ggalign_unit <- function(x, ...) UseMethod(\"ggalign_unit\")\n# #' @export\n# ggalign_unit.default <- function(x, ...) ggalign_unit(as.numeric(x), ...)\n# #' @export\n# ggalign_unit.numeric <- function(x, units = \"null\", data = NULL, ...) {\n# add_class(unit(x, units, data = data), \"ggalign_unit\")\n# }\n# #' @export\n# ggalign_unit.unit <- function(x, ...) add_class(x, \"ggalign_unit\")\n# is_ggalign_unit <- function(x) inherits(x, \"ggalign_unit\")\n\n# # allow the missing value in the unit for `str` method\n#' @importFrom utils str\n#' @export\nstr.unit <- function(object, ...) obj_str(object, ...)\n\n#' @export\nvec_ptype_abbr.unit <- function(x, ...) fclass(x)\n\n#' @importFrom utils str\n#' @export\nobj_str_footer.unit <- function(x, ..., indent.str = \" \", nest.lev = 0,\n give.attr = TRUE) {\n if (!isTRUE(give.attr)) {\n return(invisible(x))\n }\n attr <- attributes(x)\n attr[[\"class\"]] <- NULL\n attr[[\"names\"]] <- NULL\n if (length(attr) == 0) {\n return(invisible(x))\n }\n indent.str <- paste0(\" \", indent.str)\n for (nm in names(attr)) {\n cat(indent.str, paste0(\"- attr(*, \\\"\", nm, \"\\\"):\"), sep = \"\")\n str(\n attr[[nm]],\n no.list = TRUE, ...,\n nest.lev = nest.lev + 1L,\n indent.str = indent.str\n )\n }\n invisible(x)\n}\n\n#' @importFrom gtable gtable_trim\nsubset_gt <- function(gt, index, trim = TRUE) {\n gt$layout <- vec_slice(.subset2(gt, \"layout\"), index)\n gt$grobs <- .subset(.subset2(gt, \"grobs\"), index)\n if (trim) gtable_trim(gt) else gt\n}\n\ngtable_trim_widths <- function(gt) {\n layout <- .subset2(gt, \"layout\")\n w <- range(.subset2(layout, \"l\"), .subset2(layout, \"r\"))\n gt$widths <- .subset2(gt, \"widths\")[seq.int(w[1L], w[2L])]\n if (is.matrix(respect <- .subset2(gt, \"respect\"))) {\n respect <- respect[, seq.int(w[1L], w[2L]), drop = FALSE]\n if (all(respect == 0L)) respect <- FALSE\n gt$respect <- respect\n }\n layout$l <- .subset2(layout, \"l\") - w[1L] + 1L\n layout$r <- .subset2(layout, \"r\") - w[1L] + 1L\n gt$layout <- layout\n gt\n}\n\ngtable_trim_heights <- function(gt) {\n layout <- .subset2(gt, \"layout\")\n h <- range(.subset2(layout, \"t\"), .subset2(layout, \"b\"))\n gt$heights <- .subset2(gt, \"heights\")[seq.int(h[1L], h[2L])]\n if (is.matrix(respect <- .subset2(gt, \"respect\"))) {\n respect <- respect[seq.int(h[1L], h[2L]), , drop = FALSE]\n if (all(respect == 0L)) respect <- FALSE\n gt$respect <- respect\n }\n layout$t <- .subset2(layout, \"t\") - h[1L] + 1L\n layout$b <- .subset2(layout, \"b\") - h[1L] + 1L\n gt$layout <- layout\n gt\n}\n\nliberate_area <- function(gt, top, left, bottom, right,\n clip = \"inherit\", name = NULL, vp = NULL) {\n if (any(remove <- grob_in_area(gt, top, right, bottom, left))) {\n liberated <- gt[top:bottom, left:right]\n if (is.function(vp <- allow_lambda(vp))) {\n liberated$vp <- vp(liberated)\n } else if (inherits(vp, \"viewport\")) {\n liberated$vp <- vp\n }\n liberated$respect <- FALSE\n name <- name %||%\n paste(\n .subset2(.subset2(liberated, \"layout\"), \"name\"),\n collapse = \"; \"\n )\n gt <- subset_gt(gt, !remove, trim = FALSE)\n gt <- gtable_add_grob(\n gt,\n list(liberated),\n top,\n left,\n bottom,\n right,\n z = max(.subset2(.subset2(liberated, \"layout\"), \"z\")),\n clip = clip,\n name = name\n )\n }\n gt\n}\n\ngrob_in_area <- function(gt, top, right, bottom, left) {\n .subset2(.subset2(gt, \"layout\"), \"l\") >= left &\n .subset2(.subset2(gt, \"layout\"), \"t\") >= top &\n .subset2(.subset2(gt, \"layout\"), \"r\") <= right &\n .subset2(.subset2(gt, \"layout\"), \"b\") <= bottom\n}\n\ncompute_null_width <- function(x, unitTo = \"mm\", valueOnly = FALSE) {\n compute_null_unit(x, \"width\", unitTo = unitTo, valueOnly = valueOnly)\n}\n\ncompute_null_height <- function(x, unitTo = \"mm\", valueOnly = FALSE) {\n compute_null_unit(x, \"height\", unitTo = unitTo, valueOnly = valueOnly)\n}\n\n#' @importFrom grid unit convertHeight convertWidth\ncompute_null_unit <- function(x, type = c(\"width\", \"height\"), unitTo = \"mm\",\n valueOnly = FALSE) {\n null <- is_null_unit(x) # null unit\n if (type == \"width\") {\n ans <- convertWidth(x, unitTo, valueOnly = TRUE)\n total <- convertWidth(unit(1, \"npc\"), unitTo = unitTo, valueOnly = TRUE)\n } else {\n ans <- convertHeight(x, unitTo, valueOnly = TRUE)\n total <- convertHeight(\n unit(1, \"npc\"),\n unitTo = unitTo,\n valueOnly = TRUE\n )\n }\n if (any(null)) {\n null_size <- total - sum(ans[!null])\n # other units in the same row/ column also have unit null\n coef <- as.numeric(x[null])\n ans[null] <- (null_size / sum(coef)) * coef\n }\n if (!valueOnly) ans <- unit(ans, unitTo)\n ans\n}\n"], ["/ggalign/R/craft-align-phylo.R", "#' Plot Phylogenetics tree\n#'\n#' @param phylo A [`phylo`][ape::as.phylo] object.\n#' @param ... <[dyn-dots][rlang::dyn-dots]> Additional arguments passed to\n#' [`geom_segment()`][ggplot2::geom_segment].\n#' @param ladderize A single string of `r oxford_or(c(\"left\", \"right\"))`,\n#' indicating whether to ladderize the tree. Ladderizing arranges the tree so\n#' that the smallest clade is positioned on the `\"right\"` or the `\"left\"`. By\n#' default, `NULL` means the tree will not be ladderized.\n#' @inheritParams fortify_data_frame.phylo\n#' @inheritParams ggalign\n#' @export\nalign_phylo <- function(phylo, ..., ladderize = NULL, type = \"rectangle\",\n center = FALSE, tree_type = NULL,\n no_axes = NULL, active = NULL,\n size = NULL) {\n if (!is.null(ladderize)) {\n ladderize <- arg_match0(ladderize, c(\"left\", \"right\"))\n rlang::check_installed(\"ape\", \"to ladderize phylogenetics tree\")\n }\n assert_s3_class(phylo, \"phylo\")\n assert_active(active)\n active <- update_active(active, new_active(use = TRUE))\n align(\n align = AlignPhylo,\n phylo = phylo,\n ladderize = ladderize,\n no_axes = no_axes,\n plot = ggplot() +\n ggplot2::geom_segment(\n mapping = aes(\n x = .data$x, y = .data$y,\n xend = .data$xend, yend = .data$yend\n ),\n ...,\n stat = \"identity\",\n data = function(data) ggalign_attr(data, \"edge\")\n ),\n data_params = list(type = type, center = center, tree_type = tree_type),\n active = active,\n size = size\n )\n}\n\nAlignPhylo <- ggproto(\"AlignPhylo\", CraftAlign,\n interact_layout = function(self, layout) {\n layout <- ggproto_parent(CraftAlign, self)$interact_layout(layout)\n\n # we keep the names from the layout data for usage\n tip_labels <- self$phylo$tip.label\n if (is.null(tip_labels)) {\n cli_abort(\n \"{.arg phylo} must have tip labels to match the layout data\",\n call = self$call\n )\n } else if (vec_duplicate_any(tip_labels)) {\n cli_abort(\n \"{.arg phylo} cannot have duplicated tip labels\",\n call = self$call\n )\n }\n\n # we ensure the layout data has names to match the phylo tree\n if (is.null(layout_labels <- vec_names(layout@data))) {\n cli_abort(c(\n sprintf(\n \"Cannot add %s to %s\", object_name(self),\n self$layout_name\n ),\n i = sprintf(\n \"%s has no labels (rownames) to match {.arg phylo}\",\n self$layout_name\n )\n ))\n } else if (vec_duplicate_any(layout_labels)) {\n cli_abort(c(\n sprintf(\n \"Cannot add %s to %s\", object_name(self),\n self$layout_name\n ),\n i = sprintf(\"%s has duplicated labels\", self$layout_name)\n ))\n }\n assert_mismatch_nobs(\n self, .subset2(layout@design, \"nobs\"), vec_size(tip_labels),\n arg = \"phylo\"\n )\n\n # we keep the names from the layout data for usage\n self$labels <- layout_labels\n layout\n },\n compute = function(self, panel, index) {\n phylo <- self$phylo\n # R CMD check won't give error even we don't add `ape` to the dependency\n if (!is.null(self$ladderize)) {\n phylo <- ape::ladderize(phylo,\n right = identical(self$ladderize, \"right\")\n )\n }\n inject(fortify_data_frame.phylo(\n data = phylo, !!!self$data_params,\n data_arg = \"phylo\", call = self$call\n ))\n },\n align = function(self, panel, index) {\n data <- self$statistics\n tip <- vec_slice(data, .subset2(data, \"tip\"))\n ordered <- .subset2(tip, \"label\")[order(.subset2(tip, \"x\"))]\n index <- match(ordered, self$labels)\n if (!is.null(panel) && nlevels(panel) > 1L &&\n !all(index == reorder_index(panel, index))) {\n layout_name <- self$layout_name\n object_name <- object_name(self)\n cli_abort(c(\n sprintf(\"Cannot add %s to %s\", object_name, layout_name),\n i = sprintf(\n \"Group of %s will disrupt the ordering index of %s\", layout_name, object_name\n )\n ), call = self$call)\n }\n list(panel, index)\n },\n setup_plot = function(self, plot) {\n ggadd_default(plot, aes(x = .data$x, y = .data$y)) + switch_direction(\n self$direction,\n ggplot2::labs(x = \"timing\"),\n ggplot2::labs(y = \"timing\")\n )\n },\n build_plot = function(self, plot, design, extra_design = NULL,\n previous_design = NULL) {\n if (!is.null(panel <- .subset2(design, \"panel\")) &&\n nlevels(panel) > 1L) {\n layout_name <- self$layout_name\n object_name <- object_name(self)\n cli_abort(c(\n sprintf(\"Cannot add %s to %s\", object_name, layout_name),\n i = sprintf(\"%s cannot span multiple panels\", object_name)\n ))\n }\n\n data <- self$statistics\n edge <- ggalign_attr(data, \"edge\")\n node <- data\n node$.panel <- unique(panel)\n edge$.panel <- unique(panel)\n\n # add names\n if (!is.null(node$label)) {\n node$.names <- node$label\n }\n if (!is.null(edge$label)) {\n edge$.names <- edge$label\n }\n if (is_horizontal(self$direction)) {\n edge <- rename(\n edge,\n c(x = \"y\", xend = \"yend\", y = \"x\", yend = \"xend\")\n )\n node <- rename(node, c(x = \"y\", y = \"x\"))\n }\n plot <- gguse_data(plot, ggalign_data_set(node, edge = edge))\n position <- self$position\n if (!self$in_linear || # for circular layout\n # for top annotation, reverse y-axis\n (!is.null(position) && position == \"top\")) {\n plot <- reverse_continuous_axis(plot, \"y\")\n } else if (!is.null(position) && position == \"right\") {\n # for right annotation, reverse x-axis\n plot <- reverse_continuous_axis(plot, \"x\")\n }\n\n # always turn off clip, this is what dendrogram dependends on\n old_coord <- plot$coordinates\n if (!identical(old_coord$clip, \"off\")) {\n # to prevent from changing the input of user.\n plot$coordinates <- ggproto(NULL, old_coord, clip = \"off\")\n }\n plot\n },\n summary_align = function(self) c(TRUE, FALSE)\n)\n\n#' Build a matrix from `phylo` object\n#'\n#' @description This method allows a [`phylo`][ape::as.phylo] object to be\n#' directly input into `stack_discrete()` or `circle_discrete()`. This makes it\n#' possible to add [`align_phylo()`] to the stack independently, as\n#' [`align_phylo()`] requires the layout to have labels.\n#' @inheritParams rlang::args_dots_empty\n#' @param data A [`phylo`][ape::as.phylo] object.\n#' @inheritParams fortify_matrix\n#' @return A one-column matrix where the tip labels are the values, and the row\n#' names will also be the tip labels.\n#' @family fortify_matrix\n#' @export\nfortify_matrix.phylo <- function(data, ..., data_arg = caller_arg(data),\n call = NULL) {\n call <- call %||% current_call()\n rlang::check_dots_empty(call = call)\n if (is.null(labels <- data$tip.label)) {\n cli_abort(\n \"{.arg {data_arg}} must have tip labels to match the layout data\",\n call = call\n )\n }\n as.matrix(vec_set_names(labels, labels))\n}\n\n#' @inherit fortify_data_frame.default title description\n#' @inheritParams rlang::args_dots_empty\n#' @inheritParams fortify_data_frame.dendrogram\n#' @param tree_type A single string, one of\n#' `r oxford_or(c(\"phylogram\", \"cladogram\"))`, indicating the type of tree.\n#' - `phylogram`: Represents a phylogenetic tree where branch lengths indicate\n#' evolutionary distance or time.\n#' - `cladogram`: Represents a tree where branch lengths are not used, or the\n#' branches do not reflect evolutionary time.\n#'\n#' Usually, you don't need to modify this.\n#'\n#' @param tip_pos The x-coordinates of the tip. Must be the same length\n#' of the number of tips in `tree`.\n#' @return A `data frame` with the node coordinates:\n#' - `.index`: the original index in the tree for the the tip/node.\n#' - `label`: the tip/node label text.\n#' - `x` and `y`: x-axis and y-axis coordinates for the tip/node.\n#' - `tip`: A logical value indicates whether current node is a tip.\n#' @section ggalign attributes:\n#' `edge`: A `data frame` for edge coordinates:\n#'\n#' - `x` and `y`: x-axis and y-axis coordinates for the start node of the edge.\n#' - `xend` and `yend`: the x-axis and y-axis coordinates of the terminal node\n#' for edge.\n#' @family fortify_data_frame\n#' @export\nfortify_data_frame.phylo <- function(data, ..., type = \"rectangle\",\n center = FALSE,\n tree_type = NULL, tip_pos = NULL,\n data_arg = NULL, call = NULL) {\n call <- call %||% current_call()\n data_arg <- data_arg %||% \"data\"\n rlang::check_dots_empty(call = call)\n type <- arg_match0(type, c(\"rectangle\", \"triangle\"))\n rectangle <- type == \"rectangle\"\n edge <- data$edge\n edge_lengths <- data$edge.length\n if (!is.null(tree_type)) {\n tree_type <- arg_match0(tree_type,\n c(\"phylogram\", \"cladogram\"),\n error_call = call\n )\n if (tree_type == \"phylogram\" && is.null(edge_lengths)) {\n cli_warn(c(\n \"Cannot use {.code tree_type = 'phylogram'}\",\n \"No branch length found in {.arg {data_arg}}\"\n ))\n tree_type <- \"cladogram\"\n }\n }\n if (identical(tree_type, \"cladogram\")) {\n edge_lengths <- NULL\n }\n parent <- edge[, 1L, drop = TRUE]\n child <- edge[, 2L, drop = TRUE]\n tip_labels <- data$tip.label\n node_labels <- data$node.label\n N <- length(tip_labels)\n if (is.null(tip_pos)) {\n tip_pos <- seq_len(N)\n } else if (length(tip_pos) != N) {\n cli_abort(\n \"{.arg tip_pos} must have the same length as the number of tips in {.arg {data_arg}}\",\n call = call\n )\n }\n i <- 0L # tip index\n phylo_data <- function(index, level, timing) {\n if (any(select <- parent == index)) {\n # recursively for each child\n data <- list(index = child[select])\n # if we have edge length, timing should be available\n if (!is.null(edge_lengths)) {\n data <- c(data, list(timing = timing + edge_lengths[select]))\n }\n data <- list_transpose(.mapply(\n function(index, timing = NULL) {\n phylo_data(index, level = level + 1L, timing = timing)\n },\n data, NULL\n ))\n\n # integrate the data for each child\n node <- vec_rbind(!!!.subset2(data, \"node\"))\n edge <- vec_rbind(!!!.subset2(data, \"edge\"))\n\n # all coordinate for direct children nodes -------------\n direct_leaves_x <- unlist(\n .subset2(data, \"x\"),\n recursive = FALSE, use.names = FALSE\n )\n direct_leaves_y <- unlist(\n .subset2(data, \"y\"),\n recursive = FALSE, use.names = FALSE\n )\n\n # prepare node data ------------------------------------\n # all x coordinate for children nodes ------------------\n # used if center is `TRUE`, we'll calculate the center position\n # among all children nodes\n leaves <- vec_slice(node, .subset2(node, \"tip\")) # all leaves\n\n # x coordinate for current node: the midpoint\n if (center) {\n x <- sum(range(.subset2(leaves, \"x\"))) / 2L\n } else {\n x <- sum(range(direct_leaves_x)) / 2L\n }\n\n # y coordinate for current node\n if (is.null(edge_lengths) && is.null(timing)) {\n y <- min(direct_leaves_y) * level / (level + 1L)\n } else {\n y <- timing\n }\n\n # there is no node data for the root\n node <- vec_rbind(data_frame0(\n .index = index,\n label = node_labels[index - N],\n x = x, y = y, tip = FALSE\n ), node)\n\n # if it's the `rectangle`\n if (rectangle) {\n # vertical lines\n vertical_lines <- data_frame0(\n x = direct_leaves_x,\n xend = direct_leaves_x,\n y = y,\n yend = direct_leaves_y\n )\n added_edge <- vec_rbind(\n vertical_lines,\n # horizontal line\n data_frame0(\n x = x,\n xend = direct_leaves_x,\n y = y,\n yend = y\n )\n )\n } else {\n added_edge <- data_frame0(\n x = x,\n xend = direct_leaves_x,\n y = y,\n yend = direct_leaves_y\n )\n }\n if (is.null(edge)) {\n edge <- added_edge\n } else {\n edge <- vec_rbind(added_edge, edge)\n }\n list(node = node, edge = edge, x = x, y = y)\n } else if (any(select <- child == index)) { # for the tip\n i <<- i + 1L\n x <- tip_pos[i]\n if (is.null(edge_lengths)) {\n y <- 1L\n } else {\n y <- timing\n }\n\n list(\n node = data_frame0(\n .index = index,\n label = tip_labels[index],\n x = x,\n y = y,\n tip = TRUE\n ),\n edge = NULL,\n x = x, y = y\n )\n } else {\n cli_abort(\"Invalid {.cls phylo} provided in {.arg {data_arg}}\",\n call = call\n )\n }\n }\n\n # from ape::is.rooted, this should be the most ancester\n ans <- phylo_data(N + 1L, 0L, timing = 0)\n ggalign_data_set(.subset2(ans, \"node\"), edge = .subset2(ans, \"edge\"))\n}\n"], ["/ggalign/R/import-standalone-assert.R", "# Standalone file: do not edit by hand\n# Source: https://github.com/Yunuuuu/standalone/blob/HEAD/R/standalone-assert.R\n# Generated by: usethis::use_standalone(\"Yunuuuu/standalone\", \"assert\")\n# ----------------------------------------------------------------------\n#\n# ---\n# repo: Yunuuuu/standalone\n# file: standalone-assert.R\n# last-updated: 2025-04-16\n# license: https://unlicense.org\n# dependencies: [standalone-obj-type.R]\n# imports: rlang\n# ---\n\n# ## Changelog\n# 2025-04-16:\n# - `assert_number_whole` gains `allow_infinite` argument\n#\n# 2025-04-11:\n# - new `.rlang_allow_number`\n# - new `.rlang_check_number`\n# - new `.rlang_check_bool`\n# - new `.rlang_check_string`\n#\n# 2024-11-10:\n# - Added support for S3 object\n#\n# nocov start\n# Following codes were modified from `rlang` package\n\n#' Report if an argument is a specific class\n#'\n#' @param x The object type which does not conform to `what`. Its\n#' `obj_type_friendly()` is taken and mentioned in the error message.\n#' @param what The friendly expected type as a string. Can be a\n#' character vector of expected types, in which case the error\n#' message mentions all of them in an \"or\" enumeration.\n#' @param show_value Passed to `value` argument of `obj_type_friendly()`.\n#' @param show_length Passed to `length` argument of `obj_type_friendly()`.\n#' @param ... Arguments passed to [rlang::abort()].\n#' @importFrom rlang is_missing\n#' @noRd\nassert_ <- function(x, check, what,\n allow_null = FALSE,\n allow_na = FALSE,\n show_value = TRUE,\n show_length = FALSE,\n ...,\n arg = caller_arg(x),\n call = caller_env()) {\n if (!is_missing(x) && (\n (allow_null && is.null(x)) || check(x)\n )) {\n return(invisible(NULL))\n }\n stop_input_type(x, what,\n allow_na = allow_na,\n allow_null = allow_null,\n show_value = show_value,\n show_length = show_length,\n ...,\n arg = arg, call = call\n )\n}\n\nIS_NUMBER_true <- 0\nIS_NUMBER_false <- 1\nIS_NUMBER_oob <- 2\n\n.standalone_types_check_assert_call <- .Call\n\n#' @importFrom rlang ffi_standalone_check_number_1.0.7\n.rlang_check_number <- function(x, allow_decimal,\n min = NULL,\n max = NULL,\n allow_infinite = allow_decimal,\n allow_na = FALSE,\n allow_null = FALSE) {\n .standalone_types_check_assert_call(\n ffi_standalone_check_number_1.0.7,\n x,\n allow_decimal,\n min,\n max,\n allow_infinite,\n allow_na,\n allow_null\n )\n}\n\n#' @importFrom rlang ffi_standalone_is_bool_1.0.7\n.rlang_check_bool <- function(x, allow_na = FALSE, allow_null = FALSE) {\n .standalone_types_check_assert_call(\n ffi_standalone_is_bool_1.0.7,\n x,\n allow_na,\n allow_null\n )\n}\n\n#' @importFrom rlang is_string\n.rlang_check_string <- function(x, allow_empty = TRUE,\n allow_na = FALSE, allow_null = FALSE) {\n if (is_string(x) && !is.na(x)) {\n if (allow_empty || x != \"\") {\n return(TRUE)\n }\n }\n\n if (allow_null && is.null(x)) {\n return(TRUE)\n }\n\n if (allow_na && (identical(x, NA) || identical(x, NA_character_))) {\n return(TRUE)\n }\n\n FALSE\n}\n\n#' @importFrom rlang abort\n.rlang_allow_number <- function(x, exit_code, allow_decimal,\n min = NULL,\n max = NULL,\n allow_na = FALSE,\n allow_null = FALSE) {\n if (allow_decimal) {\n what <- \"a number\"\n } else {\n what <- \"a whole number\"\n }\n if (exit_code == IS_NUMBER_oob) {\n min <- min %||% -Inf\n max <- max %||% Inf\n\n if (min > -Inf && max < Inf) {\n what <- sprintf(\"%s between %s and %s\", what, min, max)\n } else if (x < min) {\n what <- sprintf(\"%s larger than or equal to %s\", what, min)\n } else if (x > max) {\n what <- sprintf(\"%s smaller than or equal to %s\", what, max)\n } else {\n abort(\"Unexpected state in OOB check\", .internal = TRUE)\n }\n }\n allow_what_type(what, allow_na = allow_na, allow_null = allow_null)\n}\n\n# scalar object ----------------------------------\nassert_string <- function(x,\n ...,\n allow_empty = TRUE,\n allow_na = FALSE,\n allow_null = FALSE,\n arg = caller_arg(x),\n call = caller_env()) {\n assert_(\n x = x,\n check = function(x) {\n .rlang_check_string(\n x,\n allow_empty = allow_empty,\n allow_na = allow_na,\n allow_null = allow_null\n )\n },\n what = \"a single string\",\n ...,\n allow_na = allow_na,\n allow_null = allow_null,\n arg = arg,\n call = call\n )\n}\n\n#' @importFrom rlang abort\n.stop_not_number <- function(x,\n exit_code,\n allow_decimal,\n ...,\n min = NULL,\n max = NULL,\n allow_na = FALSE,\n allow_null = FALSE,\n show_value = TRUE,\n show_length = FALSE,\n arg = caller_arg(x),\n call = caller_env()) {\n what <- .rlang_allow_number(\n x = x,\n exit_code = exit_code,\n allow_decimal = allow_decimal,\n min = min, max = max,\n allow_na = allow_na,\n allow_null = allow_null\n )\n if (inherits(arg, \"AsIs\")) {\n format_arg <- identity\n } else {\n format_arg <- function(x) sprintf(\"`%s`\", x)\n }\n message <- sprintf(\n \"%s must be %s, not %s.\",\n format_arg(arg), what,\n obj_type_friendly(x, value = show_value, length = show_length)\n )\n abort(message, ..., call = call, arg = arg)\n}\n\n#' @importFrom rlang is_missing\nassert_number_decimal <- function(x,\n ...,\n min = NULL,\n max = NULL,\n allow_infinite = TRUE,\n allow_na = FALSE,\n allow_null = FALSE,\n arg = caller_arg(x),\n call = caller_env()) {\n if (is_missing(x)) {\n exit_code <- IS_NUMBER_false\n } else if (0 == (exit_code <- .rlang_check_number(\n x,\n allow_decimal = TRUE,\n min = min,\n max = max,\n allow_infinite = allow_infinite,\n allow_na = allow_na,\n allow_null = allow_null\n ))) {\n return(invisible(NULL))\n }\n\n .stop_not_number(\n x,\n ...,\n exit_code = exit_code,\n allow_decimal = TRUE,\n min = min,\n max = max,\n allow_na = allow_na,\n allow_null = allow_null,\n arg = arg,\n call = call\n )\n}\n\n#' @importFrom rlang is_missing\nassert_number_whole <- function(x,\n ...,\n min = NULL,\n max = NULL,\n allow_infinite = FALSE,\n allow_na = FALSE,\n allow_null = FALSE,\n arg = caller_arg(x),\n call = caller_env()) {\n if (is_missing(x)) {\n exit_code <- IS_NUMBER_false\n } else if (0 == (exit_code <- .rlang_check_number(\n x,\n allow_decimal = FALSE,\n min = min,\n max = max,\n allow_infinite = allow_infinite,\n allow_na = allow_na,\n allow_null = allow_null\n ))) {\n return(invisible(NULL))\n }\n\n .stop_not_number(\n x,\n ...,\n exit_code = exit_code,\n allow_decimal = FALSE,\n min = min,\n max = max,\n allow_na = allow_na,\n allow_null = allow_null,\n arg = arg,\n call = call\n )\n}\n\n#' @importFrom rlang ffi_standalone_is_bool_1.0.7\nassert_bool <- function(x,\n ...,\n allow_na = FALSE,\n allow_null = FALSE,\n arg = caller_arg(x),\n call = caller_env()) {\n if (!missing(x) && .rlang_check_bool(x, allow_na, allow_null)) {\n return(invisible(NULL))\n }\n\n stop_input_type(\n x,\n c(\"`TRUE`\", \"`FALSE`\"),\n ...,\n allow_na = allow_na,\n allow_null = allow_null,\n arg = arg,\n call = call\n )\n}\n\n# atomic vector ------------------------------------\n#' @importFrom rlang abort\nassert_character <- function(x,\n ...,\n allow_na = TRUE,\n allow_null = FALSE,\n arg = caller_arg(x),\n call = caller_env()) {\n if (!missing(x)) {\n if (is.character(x)) {\n if (!allow_na && anyNA(x)) {\n abort(\n sprintf(\"`%s` can't contain NA values.\", arg),\n arg = arg, call = call\n )\n }\n return(invisible(NULL))\n }\n\n if (allow_null && is.null(x)) {\n return(invisible(NULL))\n }\n }\n stop_input_type(\n x,\n \"a character vector\",\n ...,\n allow_na = FALSE,\n allow_null = allow_null,\n arg = arg,\n call = call\n )\n}\n\n#' @importFrom rlang abort\nassert_logical <- function(x,\n ...,\n allow_na = TRUE,\n allow_null = FALSE,\n arg = caller_arg(x),\n call = caller_env()) {\n if (!missing(x)) {\n if (is.logical(x)) {\n if (!allow_na && anyNA(x)) {\n abort(\n sprintf(\"`%s` can't contain NA values.\", arg),\n arg = arg, call = call\n )\n }\n return(invisible(NULL))\n }\n if (allow_null && is.null(x)) {\n return(invisible(NULL))\n }\n }\n\n stop_input_type(\n x,\n \"a logical vector\",\n ...,\n allow_na = FALSE,\n allow_null = allow_null,\n arg = arg,\n call = call\n )\n}\n\n# S3 object ----------------------------------------\n#' @importFrom rlang is_string is_missing\nassert_s3_class <- function(x, is_class, what, ...,\n arg = caller_arg(x),\n call = caller_env()) {\n if (is.character(is_class)) {\n class <- is_class\n is_class <- function(x) inherits(x, what = class)\n if (is_missing(what)) what <- sprintf(\"a <%s>\", class)\n }\n assert_(\n x = x, check = is_class,\n what = what,\n ...,\n arg = arg, call = call\n )\n}\n\n# nocov end\n"], ["/ggalign/R/ggplot-geom-gshape.R", "#' Layer with a customized shape graphic using grid functions.\n#'\n#' @description\n#' `r lifecycle::badge('questioning')`\n#'\n#' `geom_gshape` depends on the new aesthetics `gshape` (shape with grid\n#' functions), which should always be provided with [`scale_gshape_manual()`],\n#' in which, we can provide a list of grobs or functions that define how each\n#' value should be drawn. Any ggplot2 aesthetics can be used as the arguments.\n#'\n#' @inheritParams ggplot2::layer\n#' @inheritParams ggplot2::geom_point\n#' @section Life cycle:\n#' We're unsure whether this function is truly necessary, which is why it is\n#' marked as questioning. So far, we've found that [`geom_subrect()`] and\n#' [`geom_subtile()`] handle most use cases effectively.\n#'\n#' @aesthetics GeomGshape\n#' @examples\n#' library(grid)\n#' ggplot(data.frame(value = letters[seq_len(5)], y = seq_len(5))) +\n#' geom_gshape(aes(x = 1, y = y, gshape = value, fill = value)) +\n#' scale_gshape_manual(values = list(\n#' a = function(x, y, width, height, fill) {\n#' rectGrob(x, y,\n#' width = width, height = height,\n#' gp = gpar(fill = fill),\n#' default.units = \"native\"\n#' )\n#' },\n#' b = function(x, y, width, height, fill) {\n#' rectGrob(x, y,\n#' width = width, height = height,\n#' gp = gpar(fill = fill),\n#' default.units = \"native\"\n#' )\n#' },\n#' c = function(x, y, width, height, fill) {\n#' rectGrob(x, y,\n#' width = width, height = height,\n#' gp = gpar(fill = fill),\n#' default.units = \"native\"\n#' )\n#' },\n#' d = function(x, y, width, height, shape) {\n#' gList(\n#' pointsGrob(x, y, pch = shape),\n#' # To ensure the rectangle color is shown in the legends, you\n#' # must explicitly provide a color argument and include it in\n#' # the `gpar()` of the graphical object\n#' rectGrob(x, y, width, height,\n#' gp = gpar(col = \"black\", fill = NA)\n#' )\n#' )\n#' },\n#' e = function(xmin, xmax, ymin, ymax) {\n#' segmentsGrob(\n#' xmin, ymin,\n#' xmax, ymax,\n#' gp = gpar(lwd = 2)\n#' )\n#' }\n#' )) +\n#' scale_fill_brewer(palette = \"Dark2\") +\n#' theme_void()\n#'\n#' @importFrom rlang list2\n#' @export\ngeom_gshape <- function(mapping = NULL, data = NULL, stat = \"identity\",\n position = \"identity\", ..., na.rm = FALSE,\n show.legend = NA, inherit.aes = TRUE) {\n dots <- list2(...)\n ggplot2::layer(\n data = data,\n mapping = mapping,\n stat = stat,\n geom = GeomGshape,\n position = position,\n show.legend = show.legend,\n inherit.aes = inherit.aes,\n params = c(list(na.rm = na.rm), dots, list(.__gshape_dots__ = dots))\n )\n}\n\n#' @inherit ggplot2::draw_key_point\n#' @description\n#' Each geom has an associated function that draws the key when the geom needs\n#' to be displayed in a legend. These functions are called `draw_key_*()`, where\n#' `*` stands for the name of the respective key glyph. The key glyphs can be\n#' customized for individual geoms by providing a geom with the `key_glyph`\n#' argument. The `draw_key_gshape` function provides this interface for custom\n#' key glyphs used with [`geom_gshape()`].\n#'\n#' @importFrom rlang inject\n#' @importFrom methods formalArgs\n#' @importFrom grid gTree\n#' @export\ndraw_key_gshape <- function(data, params, size) {\n gshape <- .subset2(data$gshape, 1L)\n data$gshape <- NULL\n if (is.function(gshape)) {\n for (d in formalArgs(gshape)) {\n if (is.null(.subset2(data, d))) {\n data[[d]] <- switch(d,\n x = ,\n y = 0.5,\n xmin = ,\n ymin = 0,\n xmax = ,\n ymax = 1,\n width = ,\n height = 1,\n color = data$colour %||% GeomGshape$default_aes[[\"colour\"]],\n fill = data$colour %||% GeomGshape$default_aes[[\"fill\"]],\n GeomGshape$default_aes[[d]]\n )\n }\n }\n }\n make_draw_grob(gshape, data, .subset2(params, \".__gshape_dots__\"))\n}\n\n#' @importFrom ggplot2 ggproto zeroGrob\n#' @importFrom rlang inject\n#' @importFrom grid gList\nGeomGshape <- ggproto(\n \"GeomGshape\",\n ggplot2::Geom,\n required_aes = c(\"x\", \"y\", \"gshape\"),\n default_aes = aes(\n shape = 19,\n colour = \"black\",\n size = 1.5,\n fill = NA,\n alpha = NA,\n stroke = 0.5,\n linewidth = 0.5,\n linetype = 1\n ),\n setup_data = ggplot2::GeomTile$setup_data,\n draw_panel = function(data, panel_params, coord, .__gshape_dots__) {\n coords <- coord$transform(data, panel_params)\n\n if (!is.null(coords$colour) && is.null(coords$color)) {\n coords$color <- coords$colour\n }\n if (!is.null(coords$color) && is.null(coords$colour)) {\n coords$colour <- coords$color\n }\n\n # restore width and height\n if (!is.null(coords$xmin) && !is.null(coords$xmax)) {\n coords$width <- coords$xmax - coords$xmin\n }\n if (!is.null(coords$ymin) && !is.null(coords$ymax)) {\n coords$height <- coords$ymax - coords$ymin\n }\n\n groups <- vec_group_loc(.subset2(coords, \"gshape\"))\n coords$gshape <- NULL\n\n # reordering by drawing order\n ordering <- vapply(\n .subset2(groups, \"key\"),\n function(gshape) {\n attr(gshape, \"gshape_ordering\", exact = TRUE) %||% NA_integer_\n },\n integer(1L),\n USE.NAMES = FALSE\n )\n groups <- vec_slice(groups, order(ordering))\n coords <- vec_chop(coords, indices = .subset2(groups, \"loc\"))\n\n grobs <- .mapply(\n make_draw_grob,\n list(draw = .subset2(groups, \"key\"), data = coords),\n list(dots = .__gshape_dots__)\n )\n grobs <- grobs[vapply(grobs, is.grob, logical(1L), USE.NAMES = FALSE)]\n if (is_empty(grobs)) {\n zeroGrob()\n } else {\n gTree(children = inject(gList(!!!grobs)))\n }\n },\n draw_key = draw_key_gshape\n)\n\n#' Scale for `gshape` aesthetic\n#'\n#' @inheritDotParams ggplot2::discrete_scale -expand -position -aesthetics -palette -scale_name\n#' @param values A list of grobs or functions (including purrr-like lambda\n#' syntax) that define how each cell's grob (graphical object) should be drawn.\n#' @inheritParams ggplot2::scale_discrete_manual\n#' @inherit geom_gshape\n#' @export\nscale_gshape_manual <- function(..., values, breaks = waiver(), na.value = NA) {\n ggplot2::scale_discrete_manual(\n aesthetics = \"gshape\",\n values = .mapply(function(f, i) {\n f <- allow_lambda(f)\n attr(f, \"gshape_ordering\") <- i # save the drawing order\n f\n }, list(values, seq_along(values)), NULL),\n breaks = breaks,\n na.value = na.value,\n ...\n )\n}\n\n# `gshape` should be provided manually\nscale_gshape_discrete <- function(name = waiver(), ...) {\n cli_abort(paste(\n \"You must provide {.fn scale_gshape_manual}\",\n \"to use {.field draw} aesthetic\"\n ))\n}\n\n# `gshape` should be provided manually\nscale_gshape_continuous <- scale_gshape_discrete\n"], ["/ggalign/R/layout-chain-circle-build.R", "#' @export\nggalign_build.CircleLayout <- function(x) {\n x <- default_layout(x)\n circle_build(x)\n}\n\n#' @importFrom utils packageVersion\n#' @importFrom ggplot2 find_panel calc_element ggproto ggplotGrob theme\n#' @importFrom gtable gtable_add_grob gtable_add_padding is.gtable\n#' @importFrom grid unit viewport editGrob\n#' @importFrom rlang is_empty arg_match0\ncircle_build <- function(circle, schemes = NULL, theme = NULL) {\n schemes <- inherit_parent_layout_schemes(circle, schemes)\n theme <- inherit_parent_layout_theme(circle, theme)\n # for empty plot\n base <- ggplot() +\n theme +\n ggplot2::labs(\n title = .subset2(circle@titles, \"title\"),\n subtitle = .subset2(circle@titles, \"subtitle\"),\n caption = .subset2(circle@titles, \"caption\")\n )\n if (is_empty(plot_list <- circle@plot_list)) {\n return(ggplotGrob(base))\n }\n\n # we remove the plot without actual plot area\n keep <- vapply(plot_list, function(plot) {\n !is.null(plot@plot)\n }, logical(1L), USE.NAMES = FALSE)\n plot_list <- .subset(plot_list, keep)\n if (is_empty(plot_list)) return(ggplotGrob(base)) # styler: off\n\n # we reorder the plots based on the `order` slot\n plot_order <- vapply(plot_list, function(plot) {\n .subset2(plot@active, \"order\")\n }, integer(1L), USE.NAMES = FALSE)\n plot_list <- .subset(plot_list, make_order(plot_order))\n\n # plot coordinate\n if (is.null(input_radial <- circle@radial)) {\n radial <- coord_circle(theta = \"x\", r.axis.inside = TRUE)\n } else {\n radial <- ggproto(NULL, input_radial, theta = \"x\", r_axis_inside = TRUE)\n }\n\n sizes <- vapply(plot_list, function(plot) {\n # for circular layout, we only support relative size\n if (is.na(size <- as.numeric(plot@size))) {\n size <- 1\n }\n size\n }, numeric(1L), USE.NAMES = FALSE)\n\n # For each plot track, relative to the total radius (1):\n # 1. total radius: 1\n # 2. total radius for the plot area (for each plot track): 1 - inner_radius\n if (inherits(radial, \"CoordCircle\")) {\n inner_radius <- radial$inner_radius[1L] / 0.5\n outer_radius <- radial$inner_radius[2L] / 0.5\n } else {\n # For `CoordRadial`\n # `0.4` is coord_radial used for scale size in ggplot2 to add extra\n # spaces for axis labels\n # https://github.com/tidyverse/ggplot2/issues/6284\n inner_radius <- radial$inner_radius[1L] / 0.4\n outer_radius <- radial$inner_radius[2L] / 0.4\n }\n plot_track <- sizes / sum(sizes) * (outer_radius - inner_radius)\n\n # For each plot, the plot size is calculated by adding the space for the\n # inner radius of each track.\n N <- length(plot_list)\n index <- seq_len(N)\n direction <- circle@direction\n if (identical(direction, \"outward\")) {\n plot_sizes <- inner_radius + cumsum(plot_track)\n } else {\n plot_sizes <- outer_radius -\n cumsum(c(0, utils::head(plot_track, -1L)))\n # The plots are always build outward, so the order is reversed.\n index <- rev(index)\n }\n\n # For each plot, the inner radius is calculated as the difference between\n # the plot size and its track size.\n plot_inner <- plot_sizes - plot_track\n guides <- vector(\"list\", N)\n plot_table <- NULL\n design <- setup_design(circle@design)\n for (i in index) {\n plot_size <- plot_sizes[[i]]\n plot <- .subset2(plot_list, i)\n craftsman <- plot@craftsman # `Craftsman` object\n plot_schemes <- inherit_schemes(plot@schemes, schemes)\n # the actual plot\n plot <- plot@plot\n\n # we always use `null` facet\n # we won't respect `free_facet` and `free_coord`\n plot_coord <- gguse_circle_coord(\n plot,\n coord = radial,\n # https://github.com/tidyverse/ggplot2/issues/6284\n # Use `0.5` to remove the extra spaces for axis label\n inner_radius = c(\n plot_inner[[i]] / plot_size,\n # for the outmost plot, we respect the outer radius defined by\n # the users, for others, we alway use 1 to remove any spacing\n # between two tracks\n if (i == N) outer_radius else 1\n ) * 0.5,\n layout_name = craftsman$layout_name\n )\n if (!craftsman$free_facet) {\n if (is_discrete_design(design)) {\n if (nlevels(.subset2(design, \"panel\")) > 1L) {\n plot <- plot + facet_sector(\n ggplot2::vars(.data$.panel),\n sector_spacing = circle@sector_spacing %||% (pi / 180),\n drop = FALSE\n )\n } else {\n plot <- ggmelt_facet(plot, ggplot2::facet_null())\n }\n } else {\n if (inherits(plot$facet, \"FacetSector\")) {\n plot <- ggfacet_modify(plot,\n sector_spacing = circle@sector_spacing %||% (pi / 180),\n drop = FALSE\n )\n } else {\n plot <- ggmelt_facet(plot, ggplot2::facet_null())\n }\n }\n }\n plot$coordinates <- plot_coord\n\n # set limits and default scales\n if (!craftsman$free_limits) {\n plot <- plot + ggalign_design(\n x = design,\n xlabels = .subset(craftsman$labels, .subset2(design, \"index\"))\n )\n }\n\n # let `Craftsman` add other components\n plot <- craftsman$build_plot(plot, design = design)\n plot <- craftsman$finish_plot(\n plot,\n schemes = plot_schemes, theme = theme\n )\n plot <- plot + ggplot2::labs(x = NULL, y = NULL) +\n theme(panel.border = element_blank())\n plot <- chain_decorate(circle, plot)\n\n # copied from `ggplot2:::ggplot_gtable`\n data <- ggplot2::ggplot_build(plot)\n plot <- data$plot\n plot_layout <- data$layout\n data <- data$data\n plot_theme <- complete_theme(plot$theme)\n\n geom_grobs <- ggfun(\"by_layer\")(\n function(l, d) l$draw_geom(d, plot_layout),\n plot$layers, data,\n \"converting geom to grob\"\n )\n gt <- plot_layout$render(geom_grobs, data, plot_theme, plot$labels)\n\n # for each inner gtable, we insert it to the panel area of the\n # outter gtable\n #\n # For bbox, `ggplot2::polar_bbox` always take (0.5, 0.5) as origin\n bbox <- ggfun(\"polar_bbox\")(\n plot_layout$coord$arc, margin = c(0, 0, 0, 0),\n inner_radius = plot_layout$coord$inner_radius\n )\n origin <- c(\n scales::rescale(0.5, from = bbox$x),\n scales::rescale(0.5, from = bbox$y)\n )\n spacing <- calc_element(\"panel.spacing.r\", plot_theme)\n\n if (is.null(plot_table)) {\n plot_table <- gt\n } else {\n # define the panel size of the inner track\n rescale_factor <- last_plot_size / plot_size\n\n # the spacer between two plots\n if (identical(direction, \"outward\")) {\n spacer <- last_spacing\n } else {\n spacer <- spacing\n }\n if (inherits(spacer, \"element_blank\") || is.null(spacer)) {\n spacer <- unit(0, \"mm\")\n }\n plot_table <- editGrob(plot_table, vp = viewport(\n width = unit(rescale_factor, \"npc\") - spacer,\n height = unit(rescale_factor, \"npc\") - spacer,\n x = origin[1L], y = origin[2L], just = just,\n default.units = \"native\", clip = \"off\"\n ))\n\n # add the inner track to the panel area of the outter track\n panel_loc <- find_panel(gt)\n plot_table <- gtable_add_grob(\n gt, plot_table,\n t = .subset2(panel_loc, \"t\"),\n l = .subset2(panel_loc, \"l\"),\n b = .subset2(panel_loc, \"b\"),\n r = .subset2(panel_loc, \"r\"),\n name = \"inner-track\"\n )\n }\n\n # build legends\n guides[i] <- list(plot$guides$assemble(plot_theme))\n\n # assign value for next loop\n just <- origin\n last_plot_size <- plot_size # the last plot panel size\n last_spacing <- spacing\n }\n\n # attach the guide legends\n guides <- collect_guides_list(guides, zeroGrob())\n theme$legend.spacing <- theme$legend.spacing %||% unit(0.5, \"lines\")\n theme$legend.spacing.y <- calc_element(\"legend.spacing.y\", theme)\n theme$legend.spacing.x <- calc_element(\"legend.spacing.x\", theme)\n theme$legend.box.spacing <- calc_element(\n \"legend.box.spacing\", theme\n ) %||% unit(0.2, \"cm\")\n legend_box <- .mapply(\n function(guides, guide_pos) assemble_guides(guides, guide_pos, theme),\n list(guides = guides, guide_pos = names(guides)),\n NULL\n )\n names(legend_box) <- names(guides)\n plot_table <- ggfun(\"table_add_legends\")(plot_table, legend_box, theme)\n\n # Title\n title <- element_render(\n theme, \"plot.title\", .subset2(circle@titles, \"title\"),\n margin_y = TRUE, margin_x = TRUE\n )\n title_height <- grobHeight(title)\n\n # Subtitle\n subtitle <- element_render(\n theme, \"plot.subtitle\", .subset2(circle@titles, \"subtitle\"),\n margin_y = TRUE, margin_x = TRUE\n )\n subtitle_height <- grobHeight(subtitle)\n\n # whole plot annotation\n caption <- element_render(\n theme, \"plot.caption\", .subset2(circle@titles, \"caption\"),\n margin_y = TRUE, margin_x = TRUE\n )\n caption_height <- grobHeight(caption)\n\n # positioning of title and subtitle is governed by plot.title.position\n # positioning of caption is governed by plot.caption.position\n # \"panel\" means align to the panel(s)\n # \"plot\" means align to the entire plot (except margins and tag)\n title_pos <- arg_match0(\n theme$plot.title.position %||% \"panel\",\n c(\"panel\", \"plot\"),\n arg_nm = \"plot.title.position\",\n error_call = quote(theme())\n )\n\n caption_pos <- arg_match0(\n theme$plot.caption.position %||% \"panel\",\n values = c(\"panel\", \"plot\"),\n arg_nm = \"plot.caption.position\",\n error_call = quote(theme())\n )\n\n pans <- plot_table$layout[\n grepl(\"^panel\", plot_table$layout$name), ,\n drop = FALSE\n ]\n if (title_pos == \"panel\") {\n title_l <- min(pans$l)\n title_r <- max(pans$r)\n } else {\n title_l <- 1\n title_r <- ncol(plot_table)\n }\n if (caption_pos == \"panel\") {\n caption_l <- min(pans$l)\n caption_r <- max(pans$r)\n } else {\n caption_l <- 1\n caption_r <- ncol(plot_table)\n }\n\n plot_table <- gtable_add_rows(plot_table, subtitle_height, pos = 0)\n plot_table <- gtable_add_grob(plot_table, subtitle,\n name = \"subtitle\",\n t = 1, b = 1, l = title_l, r = title_r, clip = \"off\"\n )\n\n plot_table <- gtable_add_rows(plot_table, title_height, pos = 0)\n plot_table <- gtable_add_grob(plot_table, title,\n name = \"title\",\n t = 1, b = 1, l = title_l, r = title_r, clip = \"off\"\n )\n\n plot_table <- gtable_add_rows(plot_table, caption_height, pos = -1)\n plot_table <- gtable_add_grob(plot_table, caption,\n name = \"caption\",\n t = -1, b = -1, l = caption_l, r = caption_r, clip = \"off\"\n )\n plot_table <- ggfun(\"table_add_tag\")(plot_table, NULL, theme)\n\n # Margins\n plot_margin <- calc_element(\"plot.margin\", theme) %||% margin()\n plot_table <- gtable_add_padding(plot_table, plot_margin)\n\n if (inherits(theme$plot.background, \"element\")) {\n plot_table <- gtable_add_grob(plot_table,\n element_render(theme, \"plot.background\"),\n t = 1, l = 1, b = -1, r = -1, name = \"background\", z = -Inf\n )\n plot_table$layout <- plot_table$layout[\n c(nrow(plot_table$layout), 1:(nrow(plot_table$layout) - 1)),\n ]\n plot_table$grobs <- plot_table$grobs[\n c(nrow(plot_table$layout), 1:(nrow(plot_table$layout) - 1))\n ]\n }\n\n # add alt-text as attribute\n # attr(plot_table, \"alt-label\") <- plot$labels$alt\n strip_pos <- find_strip_pos(plot_table)\n\n # always add strips columns and/or rows\n plot_table <- add_strips(plot_table, strip_pos)\n setup_patch_titles(plot_table, patch_titles = list(\n top = NULL, left = NULL, bottom = NULL, right = NULL\n ), theme = theme)\n}\n"], ["/ggalign/R/ggplot-geom-pie.R", "#' Pie charts\n#' @section new aesthetics:\n#' - `angle`: the pie circle angle.\n#' - `angle0`: the initial pie circle angle.\n#' - `radius`: the circle radius.\n#' @inheritParams ggplot2::layer\n#' @inheritParams ggplot2::geom_polygon\n#' @inheritParams ggplot2::geom_path\n#' @param steps An integer indicating the number of steps to generate the pie\n#' chart radian. Increasing this value results in a smoother pie circular.\n#' @param clockwise A single boolean value indicates clockwise or not.\n#' @aesthetics GeomPie\n#' @examples\n#' ggplot(data.frame(x = 1:10, y = 1:10, value = 1:10 / sum(1:10))) +\n#' geom_pie(aes(x, y, angle = value * 360))\n#' @export\ngeom_pie <- function(mapping = NULL, data = NULL, stat = \"identity\",\n position = \"identity\", ...,\n clockwise = TRUE, steps = 100,\n lineend = \"butt\", linejoin = \"round\", linemitre = 10,\n na.rm = FALSE,\n show.legend = NA, inherit.aes = TRUE) {\n ggplot2::layer(\n data = data,\n mapping = mapping,\n stat = stat,\n geom = GeomPie,\n position = position,\n show.legend = show.legend,\n inherit.aes = inherit.aes,\n params = list(\n lineend = lineend,\n linejoin = linejoin,\n linemitre = linemitre,\n clockwise = clockwise,\n na.rm = na.rm, steps = steps, ...\n )\n )\n}\n\n#' @importFrom grid gpar\n#' @importFrom ggplot2 ggproto aes resolution fill_alpha\n#' @importFrom rlang set_names\nGeomPie <- ggproto(\"GeomPie\",\n ggplot2::GeomPolygon,\n default_aes = aes(\n !!!set_names(\n ggplot2::GeomPolygon$default_aes,\n function(nms) {\n nms <- set_names(nms)\n vec_slice(nms, \"subgroup\") <- \"radius\"\n nms\n }\n ),\n angle0 = 0\n ),\n non_missing_aes = c(\"x\", \"y\", \"angle\", \"angle0\", \"radius\"),\n required_aes = c(\"x\", \"y\", \"angle\"),\n handle_na = ggplot2::Geom$handle_na,\n setup_params = function(self, data, params) {\n steps <- vec_cast(.subset2(params, \"steps\"), integer(),\n x_arg = \"steps\",\n call = call(snake_class(self))\n )\n assert_bool(.subset2(params, \"clockwise\"),\n arg = \"clockwise\", call = call(snake_class(self))\n )\n params$steps <- max(steps, 1L) + 1L\n params\n },\n setup_data = function(data, params) {\n # use the same strategy of geom_bar\n data$radius <- data$radius %||%\n params$radius %||% (\n min(\n vapply(\n split(data$x, data$PANEL, drop = TRUE),\n resolution, numeric(1),\n zero = FALSE,\n USE.NAMES = FALSE\n ),\n vapply(\n split(data$y, data$PANEL, drop = TRUE),\n resolution, numeric(1),\n zero = FALSE,\n USE.NAMES = FALSE\n )\n ) * 0.45)\n data\n },\n draw_panel = function(data, panel_params, coord, steps = 100L,\n clockwise = TRUE, lineend = \"butt\",\n linejoin = \"round\", linemitre = 10) {\n # Expand x, y, radius data to points along circle\n circular_data <- .mapply(\n function(x, y, radius, ang, ang0) {\n if (clockwise) {\n ang0 <- 90 - ang0\n radians <- seq(ang0, ang0 - ang, length.out = steps)[-1L]\n } else {\n ang0 <- 90 + ang0\n radians <- seq(ang0, ang0 + ang, length.out = steps)[-1L]\n }\n radians <- radians / 180 * pi\n data_frame0(\n x = c(x, cos(radians) * radius + x),\n y = c(y, sin(radians) * radius + y)\n )\n },\n list(\n x = data$x, y = data$y,\n radius = data$radius, ang = data$angle, ang0 = data$angle0\n ),\n MoreArgs = NULL\n )\n circular_data <- vec_rbind(!!!circular_data)\n\n # Transform to viewport coords\n circular_data <- coord$transform(circular_data, panel_params)\n\n # Draw as grob\n grid::polygonGrob(\n x = circular_data$x,\n y = circular_data$y,\n id.lengths = rep_len(steps, nrow(data)),\n default.units = \"native\",\n gp = gpar(\n col = data$colour,\n fill = fill_alpha(data$fill, data$alpha),\n lwd = data$linewidth,\n lty = data$linetype,\n lineend = lineend,\n linejoin = linejoin,\n linemitre = linemitre\n )\n )\n }\n)\n"], ["/ggalign/R/alignpatch-wrap.R", "#' Wrap Arbitrary Graphics to ggplot\n#'\n#' The `ggwrap()` function allows non-ggplot2 elements to be converted into a\n#' compliant representation for use with [`align_plots()`]. This is useful for\n#' adding any graphics that can be converted into a [`grob`][grid::grob] with\n#' the [`patch()`] method.\n#'\n#' @param plot Any graphic that can be converted into a [`grob`][grid::grob]\n#' using [`patch()`].\n#' @param ... Additional arguments passed to the [`patch()`] method.\n#' @param align A string specifying the area to place the plot: `\"full\"` for the\n#' full area, `\"plot\"` for the full plotting area (including the axis label), or\n#' `\"panel\"` for only the actual area where data is drawn.\n#' @param clip A single boolean value indicating whether the grob should be\n#' clipped if they expand outside their designated area.\n#' @param on_top A single boolean value indicates whether the graphic plot\n#' should be put frontmost. Note: the graphic plot will always put above the\n#' background.\n#' @param vp A [`viewport`][grid::viewport] object, you can use this to define\n#' the plot area.\n#' @return A `wrapped_plot` object that can be directly placed into\n#' [`align_plots()`].\n#' @inherit patch seealso\n#' @examples\n#' library(grid)\n#' ggwrap(rectGrob(gp = gpar(fill = \"goldenrod\")), align = \"full\") +\n#' inset(rectGrob(gp = gpar(fill = \"steelblue\")), align = \"panel\") +\n#' inset(textGrob(\"Here are some text\", gp = gpar(color = \"black\")),\n#' align = \"panel\"\n#' )\n#' p1 <- ggplot(mtcars) +\n#' geom_point(aes(mpg, disp)) +\n#' ggtitle(\"Plot 1\")\n#' align_plots(p1, ggwrap(\n#' ~ plot(mtcars$mpg, mtcars$disp),\n#' mar = c(0, 2, 0, 0), bg = NA\n#' ))\n#'\n#' @importFrom ggplot2 theme element_blank ggplot\n#' @importFrom grid is.grob\n#' @export\nggwrap <- function(plot, ..., align = \"panel\", on_top = FALSE,\n clip = TRUE, vp = NULL) {\n patch <- ggplot() +\n theme(\n plot.background = element_blank(),\n panel.background = element_blank()\n )\n inset <- make_inset(\n plot = plot, ..., align = align, on_top = on_top,\n clip = clip, vp = vp\n )\n make_wrap(patch, inset)\n}\n\nmake_wrap <- function(patch, inset) UseMethod(\"make_wrap\")\n\nmake_wrapped_plot <- function(patch, inset) {\n if (.subset2(inset, \"on_top\")) {\n patch$ggalign_wrapped_insets_above <- c(\n patch$ggalign_wrapped_insets_above, list(inset)\n )\n } else {\n patch$ggalign_wrapped_insets_under <- c(\n patch$ggalign_wrapped_insets_under, list(inset)\n )\n }\n add_class(patch, \"wrapped_plot\")\n}\n\n#' @export\nmake_wrap.ggplot <- function(patch, inset) {\n patch <- add_class(patch, \"patch_ggplot\")\n make_wrap(patch, inset)\n}\n\n#' @export\nmake_wrap.patch_ggplot <- make_wrapped_plot\n\n#' @export\nmake_wrap.alignpatches <- make_wrapped_plot\n\n#################################################\n#' @importFrom ggplot2 ggproto ggproto_parent\n#' @export\nalignpatch.wrapped_plot <- function(x) {\n Parent <- NextMethod()\n ggproto(\n \"PatchWrapped\", Parent,\n ggalign_wrapped_insets_under = x$ggalign_wrapped_insets_under,\n ggalign_wrapped_insets_above = x$ggalign_wrapped_insets_above,\n patch_gtable = function(self, theme, guides, plot = Parent$plot) {\n ans <- ggproto_parent(Parent, self)$patch_gtable(\n theme = theme, guides = guides, plot = plot\n )\n ans <- add_wrapped_insets(\n ans, self$ggalign_wrapped_insets_under, FALSE\n )\n add_wrapped_insets(ans, self$ggalign_wrapped_insets_above, TRUE)\n }\n )\n}\n\n# For wrapped plot -------------------\n#' @export\nalignpatch.grob <- function(x) alignpatch(ggwrap(x))\n\n#' @export\nalignpatch.gList <- alignpatch.grob\n\n#' @export\nalignpatch.formula <- alignpatch.grob\n\n#' @export\nalignpatch.function <- alignpatch.grob\n\n#' @export\nalignpatch.recordedplot <- alignpatch.grob\n\n#' @export\nalignpatch.trellis <- alignpatch.grob\n\n#' @export\nalignpatch.Heatmap <- function(x) alignpatch(ggwrap(x, align = \"full\"))\n\n#' @export\nalignpatch.HeatmapList <- alignpatch.Heatmap\n\n#' @export\nalignpatch.HeatmapAnnotation <- alignpatch.Heatmap\n\n#' @export\nalignpatch.pheatmap <- function(x) alignpatch(ggwrap(x, align = \"full\"))\n\n################################################## 3\nadd_wrapped_insets <- function(gt, insets, on_top) {\n if (is.null(insets)) return(gt) # styler: off\n for (i in seq_along(insets)) {\n gt <- add_wrapped_inset(gt, .subset2(insets, i), on_top, i)\n }\n gt\n}\n\n#' @importFrom gtable gtable is.gtable gtable_add_grob\nadd_wrapped_inset <- function(gt, inset, on_top, i) {\n align <- .subset2(inset, \"align\")\n clip <- .subset2(inset, \"clip\")\n layout <- .subset2(gt, \"layout\")\n grob <- .subset2(inset, \"grob\")\n if (on_top) {\n z <- Inf\n } else {\n background <- .subset2(layout, \"name\") == \"background\"\n z <- .subset2(layout, \"z\")[background] + 1L\n gt$layout$z[layout$z >= z] <- layout$z[layout$z >= z] + 1L\n }\n\n # add the grob to the gtable\n if (align == \"full\") {\n gt <- gtable_add_grob(gt,\n list(grob), 1L, 1L, nrow(gt), ncol(gt),\n clip = clip, name = sprintf(\"wrap-full-%d\", i), z = z\n )\n } else {\n panel_loc <- find_panel(gt)\n gt <- switch(align,\n plot = gtable_add_grob(gt,\n list(grob),\n .subset2(panel_loc, \"t\") - 3L,\n .subset2(panel_loc, \"l\") - 3L,\n .subset2(panel_loc, \"b\") + 3L,\n .subset2(panel_loc, \"r\") + 3L,\n clip = clip, name = sprintf(\"wrap-plot-%d\", i), z = z\n ),\n panel = gtable_add_grob(gt,\n list(grob),\n .subset2(panel_loc, \"t\"),\n .subset2(panel_loc, \"l\"),\n .subset2(panel_loc, \"b\"),\n .subset2(panel_loc, \"r\"),\n clip = clip, name = sprintf(\"wrap-panel-%d\", i), z = z\n )\n )\n }\n gt\n}\n"], ["/ggalign/R/layout-quad-build.R", "#' @importFrom grid unit.c\n#' @export\nggalign_build.QuadLayout <- function(x) {\n x <- default_layout(x)\n patches <- quad_build(x)\n plots <- .subset2(patches, \"plots\")\n sizes <- .subset2(patches, \"sizes\")\n design <- list(\n top = area(1, 2),\n left = area(2, 1),\n main = area(2, 2),\n bottom = area(3, 2),\n right = area(2, 3)\n )\n sizes <- imap(list(\n height = c(\"top\", \"main\", \"bottom\"),\n width = c(\"left\", \"main\", \"right\")\n ), function(x, name) {\n out <- .subset(sizes, x)\n out$main <- .subset2(.subset2(out, \"main\"), name)\n out <- .subset(\n out,\n !vapply(.subset(plots, x), is.null, logical(1L), USE.NAMES = FALSE)\n )\n do.call(unit.c, out)\n })\n keep <- !vapply(plots, is.null, logical(1L), USE.NAMES = FALSE)\n design <- trim_area(vec_c(!!!vec_set_names(vec_slice(design, keep), NULL)))\n titles <- x@titles\n align_plots(\n !!!.subset(plots, keep),\n design = design,\n heights = .subset2(sizes, \"height\"),\n widths = .subset2(sizes, \"width\"),\n guides = .subset2(.subset2(x@schemes, \"scheme_align\"), \"guides\"),\n theme = x@theme\n ) + layout_title(\n title = .subset2(titles, \"title\"),\n subtitle = .subset2(titles, \"subtitle\"),\n caption = .subset2(titles, \"caption\")\n )\n}\n\nquad_build <- function(quad, schemes = NULL, theme = NULL,\n direction = NULL) {\n UseMethod(\"quad_build\")\n}\n\n#######################################################################\n#' @param schemes,theme Parameters from parent layout\n#' @importFrom ggplot2 aes\n#' @importFrom rlang is_empty\n#' @importFrom grid unit is.unit unit.c\n#' @export\n#' @noRd\nquad_build.QuadLayout <- function(quad, schemes = NULL, theme = NULL,\n direction = NULL) {\n data <- quad@data\n row_design <- setup_design(quad@horizontal)\n column_design <- setup_design(quad@vertical)\n if (is.function(data)) {\n cli_abort(c(\n \"{.arg data} cannot be a {.cls function}\",\n i = sprintf(\n \"Did you want to add %s to a {.fn stack_layout}?\",\n object_name(quad)\n )\n ))\n }\n if (is_discrete_design(row_design) &&\n is.null(.subset2(row_design, \"nobs\"))) {\n cli_abort(sprintf(\n \"you must initialize %s before drawing the main plot\",\n object_name(quad),\n ))\n }\n if (is_discrete_design(column_design) &&\n is.null(.subset2(column_design, \"nobs\"))) {\n cli_abort(sprintf(\n \"you must initialize %s before drawing the main plot\",\n object_name(quad),\n ))\n }\n schemes <- inherit_parent_layout_schemes(quad, schemes)\n if (is.null(direction)) {\n spacing <- NULL\n } else if (is_horizontal(direction)) {\n spacing <- \"y\"\n } else {\n spacing <- \"x\"\n }\n theme <- inherit_parent_layout_theme(quad, theme, spacing = spacing)\n\n # prepare action for vertical and horizontal stack layout\n vertical_align <- horizontal_align <- the_align <-\n .subset2(schemes, \"scheme_align\")\n if (!is.null(layout_labs <- .subset2(the_align, \"free_labs\")) &&\n !is.waive(layout_labs)) {\n # prepare labs for child stack layout\n horizontal_align$free_labs <- gsub(\"[lr]\", \"\", layout_labs)\n vertical_align$free_labs <- gsub(\"[tb]\", \"\", layout_labs)\n if (!nzchar(horizontal_align$free_labs)) {\n horizontal_align[\"free_labs\"] <- list(NULL)\n }\n if (!nzchar(vertical_align$free_labs)) {\n vertical_align[\"free_labs\"] <- list(NULL)\n }\n }\n\n # inherit from the parent stack layout\n if (!is.null(layout_spaces <- .subset2(the_align, \"free_spaces\")) &&\n !is.waive(layout_spaces)) {\n horizontal_align$free_spaces <- gsub(\"[lr]\", \"\", layout_spaces)\n vertical_align$free_spaces <- gsub(\"[tb]\", \"\", layout_spaces)\n if (!nzchar(horizontal_align$free_spaces)) {\n horizontal_align[\"free_spaces\"] <- list(NULL)\n }\n if (!nzchar(vertical_align$free_spaces)) {\n vertical_align[\"free_spaces\"] <- list(NULL)\n }\n }\n\n # plot annotations ----------------------------\n stack_list <- lapply(.TLBR, function(position) {\n if (is_empty(stack <- slot(quad, position))) {\n return(list(plot = NULL, size = NULL))\n }\n pschemes <- schemes\n # inherit from horizontal align or vertical align\n if (is_horizontal(to_direction(position))) {\n extra_design <- column_design\n pschemes$scheme_align <- horizontal_align\n } else {\n extra_design <- row_design\n pschemes$scheme_align <- vertical_align\n }\n plot <- stack_build(\n stack,\n schemes = pschemes,\n theme = theme,\n extra_design = extra_design\n )\n if (is.null(plot)) {\n size <- NULL\n } else {\n size <- stack@sizes\n }\n list(plot = plot, size = size)\n })\n names(stack_list) <- .TLBR\n stack_list <- list_transpose(stack_list)\n plots <- .subset2(stack_list, 1L) # the annotation plot itself\n sizes <- .subset2(stack_list, 2L) # annotation size\n\n # read the plot ---------------------------------------\n p <- quad@plot\n\n # setup the facet -----------------------------------\n do_row_facet <- is_discrete_design(row_design) &&\n nlevels(.subset2(row_design, \"panel\")) > 1L\n do_column_facet <- is_discrete_design(column_design) &&\n nlevels(.subset2(column_design, \"panel\")) > 1L\n\n if (do_row_facet && do_column_facet) {\n default_facet <- ggplot2::facet_grid(\n rows = ggplot2::vars(.data$.panel_y),\n cols = ggplot2::vars(.data$.panel_x),\n scales = \"free\", space = \"free\",\n drop = FALSE, as.table = FALSE\n )\n free_row <- FALSE\n free_column <- FALSE\n } else if (do_row_facet) {\n default_facet <- ggplot2::facet_grid(\n rows = ggplot2::vars(.data$.panel_y),\n scales = \"free_y\", space = \"free\",\n drop = FALSE, as.table = FALSE\n )\n free_row <- FALSE\n free_column <- is_continuous_design(column_design)\n } else if (do_column_facet) {\n default_facet <- ggplot2::facet_grid(\n cols = ggplot2::vars(.data$.panel_x),\n scales = \"free_x\", space = \"free\",\n drop = FALSE, as.table = FALSE\n )\n free_row <- is_continuous_design(row_design)\n free_column <- FALSE\n } else {\n default_facet <- facet_quad(object_name(quad))\n free_row <- is_continuous_design(row_design)\n free_column <- is_continuous_design(column_design)\n }\n\n # set the facets and coord ---------------------------\n # we don't align observations for `quad_free()`\n # add default data ----------------------------------\n p <- gguse_data(p, quad_build_data(data, row_design, column_design))\n p <- gguse_linear_coord(p, object_name(quad))\n p <- ggmelt_facet(p, default_facet,\n free_row = free_row, free_column = free_column\n )\n p <- p +\n ggalign_design(\n x = column_design, y = row_design,\n xlabels = .subset(\n colnames(data),\n .subset2(column_design, \"index\")\n ),\n ylabels = .subset(\n vec_names(data),\n .subset2(row_design, \"index\")\n )\n )\n\n # add action ----------------------------------------\n p <- plot_add_schemes(p, inherit_schemes(quad@body_schemes, schemes))\n if (do_row_facet) {\n p <- p + theme(panel.spacing.y = calc_element(\"panel.spacing.y\", theme))\n }\n if (do_column_facet) {\n p <- p + theme(panel.spacing.x = calc_element(\"panel.spacing.x\", theme))\n }\n p <- p + theme_recycle()\n\n # collect all plots and sizes ----------------------\n plots <- append(plots, list(main = p), 2L)\n sizes <- append(\n sizes,\n list(main = list(width = quad@width, height = quad@height)),\n 3L\n )\n list(plots = plots, sizes = sizes)\n}\n\n#' @importFrom stats reorder\nquad_build_data <- function(data, row_design, column_design) {\n if (is.null(data) ||\n (is_continuous_design(row_design) &&\n is_continuous_design(column_design))) {\n return(data)\n }\n if (is_discrete_design(row_design)) {\n row_panel <- .subset2(row_design, \"panel\")\n row_index <- .subset2(row_design, \"index\")\n row_data <- data_frame0(\n .panel_y = row_panel,\n .index_y = row_index,\n .y = seq_along(row_index)\n )\n }\n if (is_discrete_design(column_design)) {\n column_panel <- .subset2(column_design, \"panel\")\n column_index <- .subset2(column_design, \"index\")\n column_data <- data_frame0(\n .panel_x = column_panel,\n .index_x = column_index,\n .x = seq_along(column_index)\n )\n }\n if (is_discrete_design(row_design) && is_discrete_design(column_design)) {\n panel_data <- cross_join(row_data, column_data)\n by.x <- c(\".column_index\", \".row_index\")\n by.y <- c(\".index_x\", \".index_y\")\n } else if (is_discrete_design(column_design)) {\n panel_data <- column_data\n by.x <- \".column_index\"\n by.y <- \".index_x\"\n } else {\n panel_data <- row_data\n by.x <- \".row_index\"\n by.y <- \".index_y\"\n }\n ans <- fortify_data_frame.matrix(data)\n ans <- full_join(ans, panel_data, by.x = by.x, by.y = by.y)\n if (!is.null(.subset2(ans, \".row_names\")) &&\n is_discrete_design(row_design)) {\n ans$.discrete_y <- reorder(\n .subset2(ans, \".row_names\"),\n .subset2(ans, \".y\"),\n order = FALSE\n )\n }\n if (!is.null(.subset2(ans, \".column_names\")) &&\n is_discrete_design(column_design)) {\n ans$.discrete_x <- reorder(\n .subset2(ans, \".column_names\"),\n .subset2(ans, \".x\"),\n order = FALSE\n )\n }\n ggalign_data_restore(ans, data)\n}\n"], ["/ggalign/R/ggplot-coord-circle.R", "#' Polar Coordinates with Enhanced Controls\n#'\n#' An extended version of [`coord_radial()`][ggplot2::coord_radial], providing\n#' additional customization options.\n#'\n#' @inheritParams ggplot2::coord_radial\n#' @param thetalim,rlim Limits for the `theta` and `r` axes.\n#' @param inner.radius A numeric in `[0, 1)` indicates the inner radius.\n#' @param outer.radius A numeric in `(0, 1]` indicates the outer radius.\n#' [`coord_radial()`][ggplot2::coord_radial] by default uses `0.8`.\n#' @examples\n#' ggplot(mtcars, aes(disp, mpg)) +\n#' geom_point() +\n#' coord_circle(\n#' start = -0.4 * pi, end = 0.4 * pi,\n#' inner.radius = 0.3, outer.radius = 1\n#' )\n#' ggplot(mtcars, aes(disp, mpg)) +\n#' geom_point() +\n#' coord_circle(\n#' start = -0.4 * pi, end = 0.4 * pi,\n#' inner.radius = 0.3, outer.radius = 0.5\n#' )\n#' @importFrom ggplot2 ggproto\n#' @importFrom rlang arg_match0\n#' @export\ncoord_circle <- function(theta = \"x\", start = 0, end = NULL,\n thetalim = NULL, rlim = NULL, expand = FALSE,\n direction = 1, clip = \"off\",\n r.axis.inside = NULL, rotate.angle = FALSE,\n inner.radius = 0, outer.radius = 0.95) {\n theta <- arg_match0(theta, c(\"x\", \"y\"))\n assert_number_decimal(start, allow_infinite = FALSE)\n assert_number_decimal(end, allow_infinite = FALSE, allow_null = TRUE)\n if (packageVersion(\"ggplot2\") <= \"3.5.2\") {\n assert_bool(expand)\n }\n clip <- arg_match0(clip, c(\"off\", \"on\"))\n\n valid_inside_axis <- .rlang_check_bool(r.axis.inside,\n allow_null = TRUE\n ) ||\n .rlang_check_number(r.axis.inside,\n allow_decimal = TRUE, allow_infinite = FALSE\n ) == 0L\n if (!valid_inside_axis) {\n cli_abort(\n \"{.arg r.axis.inside} must be a single boolean value or a number\"\n )\n }\n\n assert_bool(rotate.angle)\n assert_number_decimal(inner.radius,\n min = 0, max = 1,\n allow_infinite = FALSE\n )\n assert_number_decimal(outer.radius,\n min = 0, max = 1,\n allow_infinite = FALSE\n )\n if (inner.radius >= outer.radius) {\n cli_abort(\n \"{.arg outer.radius} must be larger than {.arg inner.radius}\"\n )\n }\n r <- if (theta == \"x\") \"y\" else \"x\"\n\n arc <- c(start, end %||% (start + 2 * pi))\n if (arc[1] > arc[2]) {\n n_rotate <- ((arc[1] - arc[2]) %/% (2 * pi)) + 1\n arc[1] <- arc[1] - n_rotate * 2 * pi\n }\n r.axis.inside <- r.axis.inside %||% !(abs(arc[2] - arc[1]) >= 1.999 * pi)\n inner_radius <- c(inner.radius, outer.radius) / 2\n\n ggproto(NULL, CoordCircle,\n limits = list(theta = thetalim, r = rlim),\n theta = theta,\n r = r,\n arc = arc,\n expand = expand,\n direction = sign(direction),\n r_axis_inside = r.axis.inside,\n rotate_angle = rotate.angle,\n inner_radius = inner_radius,\n clip = clip\n )\n}\n\n#' @importFrom ggplot2 ggproto_parent\ncircle_panel_params <- function(self, scale_x, scale_y, params = list()) {\n out <- ggproto_parent(ggplot2::CoordRadial, self)$setup_panel_params(\n scale_x, scale_y, params\n )\n if (packageVersion(\"ggplot2\") <= \"3.5.2\") {\n if (self$theta == \"x\") {\n xlimits <- self$limits$theta\n ylimits <- self$limits$r\n } else {\n xlimits <- self$limits$r\n ylimits <- self$limits$theta\n }\n new <- c(\n view_scales_polar(\n scale_x, self$theta, xlimits,\n expand = params$expand[c(4, 2)] %||% self$expand\n ),\n view_scales_polar(\n scale_y, self$theta, ylimits,\n expand = params$expand[c(3, 1)] %||% self$expand\n )\n )\n out[names(new)] <- new\n }\n out$bbox <- ggfun(\"polar_bbox\")(\n self$arc, margin = c(0, 0, 0, 0),\n inner_radius = self$inner_radius\n )\n out\n}\n\nview_scales_polar <- function(scale, theta, coord_limits, expand = TRUE) {\n aesthetic <- scale$aesthetics[1]\n is_theta <- theta == aesthetic\n name <- if (is_theta) \"theta\" else \"r\"\n expansion <- ggfun(\"default_expansion\")(scale, expand = expand)\n limits <- scale$get_limits()\n continuous_range <- ggfun(\"expand_limits_scale\")(\n scale, expansion, limits, coord_limits = coord_limits\n )\n primary <- ggfun(\"view_scale_primary\")(scale, limits, continuous_range)\n view_scales <- list(\n primary,\n sec = ggfun(\"view_scale_secondary\")(scale, limits, continuous_range),\n major = primary$map(primary$get_breaks()),\n minor = primary$map(primary$get_breaks_minor()),\n range = continuous_range\n )\n names(view_scales) <- c(name, paste0(name, \".\", names(view_scales)[-1]))\n view_scales\n}\n\n#' @importFrom ggplot2 ggproto\nCoordCircle <- ggproto(\n \"CoordCircle\", ggplot2::CoordRadial,\n setup_panel_params = circle_panel_params\n)\n"], ["/ggalign/R/layout-heatmap-.R", "#' Create a heatmap\n#'\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' `heatmap_layout` is a specialized version of [`quad_discrete()`], which\n#' simplifies the creation of heatmap plots by integrating essential elements\n#' for a standard heatmap layout, ensuring that the appropriate data mapping and\n#' visualization layers are automatically applied. `ggheatmap` is an alias for\n#' `heatmap_layout`.\n#'\n#' @param data `r rd_layout_data()`. By default, it will try to inherit from\n#' parent layout. [`fortify_matrix()`] will be used to convert data to a\n#' matrix.\n#' @param ... Additional arguments passed to [`fortify_matrix()`].\n#' @inheritParams quad_layout\n#' @param filling A single string of `r oxford_or(c(\"raster\", \"tile\"))` to\n#' indicate the filling style. By default, `waiver()` is used, which means that\n#' if the input matrix has more than 20,000 cells (`nrow * ncol > 20000`),\n#' [`geom_raster()`][ggplot2::geom_raster] will be used for performance\n#' efficiency; for smaller matrices, [`geom_tile()`][ggplot2::geom_tile] will be\n#' used. To customize the filling style, set this to `NULL`.\n#'\n#' For backward compatibility, a single boolean value is acceptable: `TRUE`\n#' means `waiver()`, and `FALSE` means `NULL`.\n#'\n#' By default, the classic heatmap color scheme\n#' [`scale_fill_gradient2(low = \"blue\", high = \"red\")`][ggplot2::scale_fill_gradient2]\n#' is utilized for continuous values.\n#'\n#' You can use the options\n#' `r code_quote(sprintf(\"%s.heatmap_continuous_fill\", pkg_nm()))` or\n#' `r code_quote(sprintf(\"%s.heatmap_discrete_fill\", pkg_nm()))` to modify the\n#' default heatmap body filling color scale. See\n#' [`scale_fill_continuous()`][ggplot2::scale_fill_continuous] or\n#' [`scale_fill_discrete()`][ggplot2::scale_fill_discrete] for details on\n#' option settings.\n#'\n#' @section ggplot2 specification:\n#' The data input will be converted to a matrix using [`fortify_matrix()`], and\n#' the data in the underlying main plot will contain the following columns:\n#'\n#' - `.panel_x` and `.panel_y`: the column and row panel groups.\n#'\n#' - `.x` and `.y`: an integer index of `x` and `y` coordinates\n#'\n#' - `.discrete_x` and `.discrete_y`: a factor of the data labels (only\n#' applicable when `.row_names` and `.column_names` exists).\n#'\n#' - `.row_names` and `.column_names`: A character of the row and column names\n#' of the original matrix (only applicable when names exist).\n#'\n#' - `.row_index` and `.column_index`: the row and column index of the original\n#' matrix.\n#'\n#' - `value`: the actual matrix value.\n#'\n#' @return A `HeatmapLayout` object.\n#' @examples\n#' ggheatmap(1:10)\n#' ggheatmap(letters)\n#' ggheatmap(matrix(rnorm(81), nrow = 9L))\n#' @importFrom ggplot2 aes\n#' @export\nheatmap_layout <- function(data = NULL, mapping = aes(),\n ...,\n width = NA, height = NA, filling = waiver(),\n theme = NULL, active = NULL) {\n UseMethod(\"heatmap_layout\")\n}\n\n#' @usage NULL\n#' @export\n#' @rdname heatmap_layout\nggheatmap <- heatmap_layout\n\n#' @importFrom ggplot2 aes\n#' @importFrom rlang arg_match0\n#' @export\nheatmap_layout.default <- function(data = NULL, mapping = aes(),\n ...,\n width = NA, height = NA, filling = waiver(),\n theme = NULL, active = NULL) {\n # A single boolean value for compatible with `version <= 0.0.4`\n if (isTRUE(filling)) {\n filling <- waiver()\n } else if (isFALSE(filling)) {\n filling <- NULL\n } else if (!is.waive(filling) && !is.null(filling)) {\n filling <- arg_match0(filling, c(\"tile\", \"raster\"))\n }\n data <- data %|w|% NULL\n # we need a matrix to melted into long formated data frame\n data <- fortify_matrix(data = data, ...)\n ans <- new_quad_layout(\n name = \"ggheatmap\",\n data = data,\n mapping = mapping,\n theme = theme, active = active,\n width = width, height = height,\n class = \"HeatmapLayout\"\n )\n # add default mapping\n ans@plot <- ggadd_default(ans@plot, mapping = aes(.data$.x, .data$.y)) +\n ggplot2::labs(x = NULL, y = NULL)\n ans@filling <- filling\n ans\n}\n\n# used to create the heatmap layout\n#' @keywords internal\n#' @include layout-quad-.R\nmethods::setClass(\n \"HeatmapLayout\",\n contains = \"QuadLayout\",\n list(filling = \"ANY\") # parameters for heatmap body\n)\n"], ["/ggalign/R/fortify-data-frame-dendrogram.R", "#' @inherit fortify_data_frame.default title description\n#'\n#' @param data A [`hclust`][stats::hclust] or a\n#' [`dendrogram`][stats::as.dendrogram] object.\n#' @param center A boolean value. if `TRUE`, nodes are plotted centered with\n#' respect to all leaves/tips in the branch. Otherwise (default), plot them in\n#' the middle of the direct child nodes.\n#' @param type A string indicates the plot type, `\"rectangle\"` or `\"triangle\"`.\n#' @param leaf_pos The x-coordinates of the leaf node. Must be the same length\n#' of the number of observations in `tree`.\n#' @param leaf_braches Branches of the leaf node. Must be the same length of the\n#' number of observations in `tree`. Usually come from [cutree][stats::cutree].\n#' @param reorder_branches A single boolean value, indicates whether reorder the\n#' provided `leaf_braches` based on the actual index.\n#' @param branch_gap A single numeric value indicates the gap between different\n#' branches.\n#' @param root A length one string or numeric indicates the root branch.\n#' @param priority A string of \"left\" or \"right\". if we draw from `right` to\n#' `left`, the left will override the right, so we take the `\"left\"` as the\n#' priority. If we draw from `left` to `right`, the right will override the\n#' left, so we take the `\"right\"` as priority. This is used by\n#' [`align_dendro()`] to provide support of facet operation in ggplot2.\n#' @param double A single logical value indicating whether horizontal lines\n#' should be doubled when segments span multiple branches. If `TRUE`, the\n#' horizontal lines will be repeated for each branch that the segment spans. If\n#' `FALSE`, only one horizontal line will be drawn. This is used by\n#' [`align_dendro()`] to provide support of facet operation in ggplot2.\n#' @inheritParams fortify_data_frame\n#' @return A `data frame` with the node coordinates:\n#' - `.panel`: Similar with `panel` column, but always give the correct\n#' branch for usage of the ggplot facet.\n#' - `.index`: the original index in the tree for the the node\n#' - `label`: node label text\n#' - `x` and `y`: x-axis and y-axis coordinates for the node\n#' - `branch`: which branch the node is. You can use this column to color\n#' different groups.\n#' - `panel`: which panel the node is, if we split the plot into panel\n#' using [facet_grid][ggplot2::facet_grid], this column will show\n#' which panel the node is from. Note: some nodes may\n#' fall outside panel (between two panels), so there are possible\n#' `NA` values in this column.\n#' - `leaf`: A logical value indicates whether the node is a leaf.\n#' @section ggalign attributes:\n#' `edge`: A `data frame` for edge coordinates:\n#' - `.panel`: Similar with `panel` column, but always give the correct\n#' branch for usage of the ggplot facet.\n#' - `x` and `y`: x-axis and y-axis coordinates for the start node of the edge.\n#' - `xend` and `yend`: the x-axis and y-axis coordinates of the terminal node\n#' for edge.\n#' - `branch`: which branch the edge is. You can use this column to color\n#' different groups.\n#' - `panel1` and `panel2`: The panel1 and panel2 columns have the same\n#' functionality as `panel`, but they are specifically for the `edge` data\n#' and correspond to both nodes of each edge.\n#' @examples\n#' fortify_data_frame(hclust(dist(USArrests), \"ave\"))\n#' @importFrom grid is.unit\n#' @importFrom stats order.dendrogram\n#' @importFrom rlang arg_match0\n#' @family fortify_data_frame\n#' @export\nfortify_data_frame.dendrogram <- function(data, ...,\n priority = \"right\",\n center = FALSE,\n type = \"rectangle\",\n leaf_pos = NULL,\n leaf_braches = NULL,\n reorder_branches = TRUE,\n branch_gap = NULL,\n root = NULL,\n double = TRUE,\n data_arg = NULL, call = NULL) {\n call <- call %||% current_call()\n data_arg <- data_arg %||% \"data\"\n rlang::check_dots_empty(call = call)\n assert_bool(center, call = call)\n assert_bool(reorder_branches, call = call)\n type <- arg_match0(type, c(\"rectangle\", \"triangle\"), error_call = call)\n priority <- arg_match0(priority, c(\"left\", \"right\"), error_call = call)\n N <- stats::nobs(data)\n rectangle <- type == \"rectangle\"\n if (is.null(leaf_pos)) {\n leaf_pos <- seq_len(N)\n } else if (length(leaf_pos) != N) {\n cli_abort(\n \"{.arg leaf_pos} must be of the same length of {.arg tree}\",\n call = call\n )\n }\n\n # if no branches provided, all branch will be regarded as the `root`\n if (is.null(leaf_braches)) {\n root <- root %||% \"root\"\n } else if (anyNA(leaf_braches)) {\n cli_abort(\"`NA` is not allowed in {.arg leaf_braches}\",\n call = call\n )\n } else if (length(leaf_braches) != N) {\n cli_abort(\n \"{.arg leaf_braches} must be of the same length of {.arg tree}\",\n call = call\n )\n } else if (is.character(leaf_braches)) {\n root <- root %||% \"root\"\n } else if (is.factor(leaf_braches)) {\n leaf_braches <- as.character(leaf_braches)\n root <- root %||% \"root\"\n } else if (is.numeric(leaf_braches)) {\n root <- root %||% (min(leaf_braches) - 1L)\n } else {\n cli_abort(\"{.arg leaf_braches} must be a character or numeric\",\n call = call\n )\n }\n\n if (!is.null(leaf_braches) && reorder_branches) {\n leaf_braches <- .subset(leaf_braches, order.dendrogram(data))\n }\n\n # check `branch_gap`\n if (is.numeric(branch_gap)) {\n if (!is_scalar(branch_gap)) {\n cli_abort(\"{.arg branch_gap} must be of length 1\",\n call = call\n )\n }\n } else if (is.null(branch_gap)) {\n branch_gap <- 0\n } else {\n cli_abort(\"{.arg branch_gap} must be numeric value.\",\n call = call\n )\n }\n\n # the root value shouldn't be the same of leaf branches.\n if (!is_scalar(root)) {\n cli_abort(\"{.arg root} must be of length 1\", call = call)\n } else if (anyNA(root)) {\n cli_abort(\"{.arg root} cannot be `NA`\", call = call)\n } else if (any(root == leaf_braches)) {\n cli_abort(\n \"{.arg root} cannot contain value in {.arg leaf_braches}\",\n call = call\n )\n }\n\n # initialize values\n i <- 0L # leaf index\n branch_levels <- NULL\n last_branch <- root\n total_gap <- 0\n dendrogram_data <- function(dend, from_root = TRUE) {\n if (stats::is.leaf(dend)) { # base version\n index <- as.integer(dend) # the column index of the original data\n y <- attr(dend, \"height\") %||% 0\n label <- attr(dend, \"label\") %||% NA\n i <<- i + 1L\n if (is.null(leaf_braches)) {\n branch <- root\n } else {\n branch <- .subset(leaf_braches, i)\n }\n\n x <- .subset(leaf_pos, i) + total_gap\n # for every new branch, we saved the branch for later use, in order\n # to order the branch levels, and we add a gap between two branch\n if (branch != last_branch) {\n branch_levels <<- c(branch_levels, branch)\n x <- x + branch_gap\n total_gap <<- total_gap + branch_gap\n }\n last_branch <<- branch\n\n node <- data_frame0(\n index = index, label = label,\n x = x, y = y, branch = branch,\n leaf = TRUE, panel = branch,\n ggpanel = branch\n )\n list(\n # current node\n node = node, edge = NULL,\n # current node information\n x = x, y = y,\n branch = branch,\n panel = branch,\n ggpanel = branch\n )\n } else if (inherits(dend, \"dendrogram\")) { # recursive version\n # the parent height -------------------------------------\n y <- attr(dend, \"height\")\n\n # for the children nodes ---------------------------------\n data <- list_transpose(\n lapply(dend, dendrogram_data, from_root = FALSE)\n )\n\n # node should be the direct children\n node <- vec_rbind(!!!.subset2(data, \"node\"))\n edge <- vec_rbind(!!!.subset2(data, \"edge\"))\n\n # all coordinate for direct children nodes -------------\n # following should be length 2\n direct_leaves_x <- unlist(\n .subset2(data, \"x\"),\n recursive = FALSE, use.names = FALSE\n )\n direct_leaves_y <- unlist(\n .subset2(data, \"y\"),\n recursive = FALSE, use.names = FALSE\n )\n direct_leaves_branch <- unlist(\n .subset2(data, \"branch\"),\n recursive = FALSE, use.names = FALSE\n )\n direct_leaves_panel <- unlist(\n .subset2(data, \"panel\"),\n recursive = FALSE, use.names = FALSE\n )\n direct_leaves_ggpanel <- unlist(\n .subset2(data, \"ggpanel\"),\n recursive = FALSE, use.names = FALSE\n )\n\n # prepare node data ------------------------------------\n\n # all x coordinate for children nodes --------------------\n # used if center is `TRUE`, we'll calculate the center position\n # among all children nodes\n leaves <- vec_slice(node, .subset2(node, \"leaf\")) # all leaves\n\n # we assign the `panel` for current branch node\n ranges <- split(\n .subset2(leaves, \"x\"),\n .subset2(leaves, \"panel\")\n )\n ranges <- ranges[\n order(vapply(ranges, min, numeric(1L), USE.NAMES = FALSE))\n ]\n full_panel <- names(ranges)\n\n # x coordinate for current branch: the midpoint\n if (center) {\n x <- sum(range(.subset2(leaves, \"x\"))) / 2L\n } else {\n x <- sum(direct_leaves_x) / 2L\n }\n if (is.null(leaf_braches)) { # no branches\n ggpanel <- panel <- branch <- root\n } else {\n # we assign the branch for current branch node\n branch <- unique(direct_leaves_branch)\n # if two children leaves are different, this branch should be\n # `root`, this is often used to color the segments\n if (length(branch) > 1L) branch <- root\n\n # we assign the `panel` for current branch node\n panel <- NA\n for (i in seq_along(ranges)) {\n if (x < min(.subset2(ranges, i))) {\n panel <- NA\n break\n } else if (x <= max(.subset2(ranges, i))) {\n panel <- .subset2(full_panel, i)\n break\n }\n }\n # if the node is between two panels, no panel\n # we choose the priority\n if (is.na(ggpanel <- panel)) {\n # it's not possible for an branch node live outside the\n # all panels - the left or right most. So `i` won't be 1 or\n # length(ranges). we don't need to check the argument\n ggpanel <- switch(priority,\n left = .subset(full_panel, i - 1L),\n right = .subset(full_panel, i)\n )\n }\n }\n\n # there is no node data in dendrogram root\n if (!from_root) {\n node <- vec_rbind(node, data_frame0(\n index = NA, label = NA,\n x = x, y = y, branch = branch, leaf = FALSE,\n panel = panel, ggpanel = ggpanel\n ))\n }\n\n # if it's the `rectangle`\n if (rectangle) {\n # 2 vertical lines\n vertical_lines <- data_frame0(\n x = direct_leaves_x,\n xend = direct_leaves_x,\n y = direct_leaves_y,\n yend = rep_len(y, 2L),\n branch = direct_leaves_branch,\n panel1 = direct_leaves_panel,\n panel2 = direct_leaves_panel,\n ggpanel = direct_leaves_ggpanel\n )\n # 2 horizontal lines\n # if the horizontal lines spanned multiple panels\n # we double the left line and the right line\n added_edge <- vec_rbind(\n vertical_lines,\n # left horizontal line\n make_horizontal(\n c(direct_leaves_x[1L], x),\n panels = c(direct_leaves_panel[1L], panel),\n ggpanels = c(direct_leaves_ggpanel[1L], ggpanel),\n y = y,\n branch = direct_leaves_branch[1L],\n ranges = ranges,\n full_panel = full_panel,\n double = double\n ),\n # right horizontal line\n make_horizontal(\n c(x, direct_leaves_x[2L]),\n panels = c(panel, direct_leaves_panel[2L]),\n ggpanels = c(ggpanel, direct_leaves_ggpanel[2L]),\n y = y,\n branch = direct_leaves_branch[2L],\n ranges = ranges,\n full_panel = full_panel,\n double = double\n )\n )\n } else {\n added_edge <- data_frame0(\n x = rep_len(x, 2L),\n xend = direct_leaves_x,\n y = rep_len(y, 2L),\n yend = direct_leaves_y,\n branch = direct_leaves_branch,\n panel1 = rep_len(panel, 2L),\n panel2 = direct_leaves_panel,\n ggpanel = rep_len(ggpanel, 2L)\n )\n }\n if (is.null(edge)) {\n edge <- added_edge\n } else {\n edge <- vec_rbind(edge, added_edge)\n }\n list(\n node = node, edge = edge,\n x = x, y = y, branch = branch,\n panel = panel, ggpanel = ggpanel\n )\n } else {\n cli_abort(\"Invalid {.cls dendrogram} provided in {.arg {data_arg}}\",\n call = call\n )\n }\n }\n ans <- dendrogram_data(data)\n node <- .subset2(ans, \"node\")\n edge <- .subset2(ans, \"edge\")\n\n # set factor levels for branch and panel ---------------\n panel_levels <- branch_levels\n branch_levels <- c(branch_levels, root)\n node$panel <- factor(.subset2(node, \"panel\"), panel_levels)\n node$branch <- factor(.subset2(node, \"branch\"), branch_levels)\n node$ggpanel <- factor(.subset2(node, \"ggpanel\"), panel_levels)\n if (!is.null(edge)) {\n edge$panel1 <- factor(.subset2(edge, \"panel1\"), panel_levels)\n edge$panel2 <- factor(.subset2(edge, \"panel2\"), panel_levels)\n edge$branch <- factor(.subset2(edge, \"branch\"), branch_levels)\n edge$ggpanel <- factor(.subset2(edge, \"ggpanel\"), panel_levels)\n }\n node <- rename(node, c(ggpanel = \".panel\", index = \".index\"))\n edge <- rename(edge, c(ggpanel = \".panel\"))\n ggalign_data_set(node, edge = edge)\n}\n\n#' @param ... Additional arguments passed to `dendrogram` method.\n#' @export\n#' @rdname fortify_data_frame.dendrogram\nfortify_data_frame.hclust <- function(data, ...) {\n fortify_data_frame.dendrogram(stats::as.dendrogram(data), ...)\n}\n\n#' @param ggpanels Won't be `NA`\n#' @noRd\nmake_horizontal <- function(x, panels, ggpanels, y, branch,\n ranges, full_panel = names(ranges),\n double = TRUE) {\n if (!isTRUE(double) || identical(ggpanels[1L], ggpanels[2L])) {\n # in the same panel\n data_frame0(\n x = x[1L],\n xend = x[2L],\n y = y,\n yend = y,\n branch = branch,\n panel1 = panels[1L],\n panel2 = panels[2L],\n ggpanel = ggpanels[1L]\n )\n } else {\n index <- match(ggpanels, full_panel)\n ending <- index[2L] # right index\n panel0 <- panels[1L]\n ggpanel0 <- ggpanels[1L]\n point0 <- x[1L] # the left point coordinate x\n out <- vector(\"list\", diff(index))\n right_index <- (index[1L] + 1L):ending\n for (i in seq_along(right_index)) {\n i1 <- .subset(right_index, i) # right index\n if (i1 == ending) {\n point1 <- x[2L]\n panel1 <- panels[2L]\n ggpanel1 <- ggpanels[2L]\n } else {\n point1 <- mean(range(.subset2(ranges, i1)))\n ggpanel1 <- panel1 <- .subset(full_panel, i1)\n }\n out[[i]] <- data_frame0(\n x = c(point0, point1),\n xend = c(point1, point0),\n y = y,\n yend = y,\n branch = branch,\n panel1 = c(panel0, panel1),\n panel2 = c(panel1, panel0),\n ggpanel = c(ggpanel0, ggpanel1)\n )\n point0 <- point1\n panel0 <- panel1\n ggpanel0 <- ggpanel1\n }\n vec_rbind(!!!out)\n }\n}\n"], ["/ggalign/R/craft-align-dendrogram.R", "#' Plot dendrogram tree\n#'\n#' @param ... <[dyn-dots][rlang::dyn-dots]> Additional arguments passed to\n#' [`geom_segment()`][ggplot2::geom_segment].\n#' @param plot_dendrogram A boolean value indicates whether plot the dendrogram\n#' tree.\n#' @param plot_cut_height A boolean value indicates whether plot the cut height.\n#' @section ggplot2 specification:\n#' `align_dendro` initializes a ggplot `data` and `mapping`.\n#'\n#' The internal `ggplot` object will always use a default mapping of\n#' `aes(x = .data$x, y = .data$y)`.\n#'\n#' The default ggplot data is the `node` coordinates with `edge` data attached\n#' in [`ggalign`][ggalign_attr()] attribute, in addition, a\n#' [`geom_segment`][ggplot2::geom_segment] layer with a data frame of the `edge`\n#' coordinates will be added when `plot_dendrogram = TRUE`.\n#'\n#' See [`fortify_data_frame.dendrogram()`] for details.\n#' @param merge_dendrogram A single boolean value, indicates whether we should\n#' merge multiple dendrograms, only used when previous groups have been\n#' established. Default: `FALSE`.\n#' @inheritParams align_hclust\n#' @inheritParams fortify_data_frame.dendrogram\n#' @inheritParams ggalign\n#' @inheritSection align Discrete Axis Alignment\n#' @examples\n#' # align_dendro will always add a plot area\n#' ggheatmap(matrix(rnorm(81), nrow = 9)) +\n#' anno_top() +\n#' align_dendro()\n#' ggheatmap(matrix(rnorm(81), nrow = 9)) +\n#' anno_top() +\n#' align_dendro(k = 3L)\n#'\n#' @importFrom ggplot2 aes\n#' @importFrom rlang list2\n#' @export\nalign_dendro <- function(mapping = aes(), ...,\n distance = \"euclidean\",\n method = \"complete\",\n use_missing = \"pairwise.complete.obs\",\n reorder_dendrogram = FALSE,\n merge_dendrogram = FALSE,\n reorder_group = FALSE,\n k = NULL, h = NULL, cutree = NULL,\n plot_dendrogram = TRUE,\n plot_cut_height = NULL, root = NULL,\n center = FALSE, type = \"rectangle\",\n size = NULL, data = NULL,\n no_axes = NULL, active = NULL) {\n assert_bool(plot_cut_height, allow_null = TRUE)\n assert_bool(merge_dendrogram)\n\n # setup the default value for `plot_cut_height`\n plot_cut_height <- plot_cut_height %||% (\n # we by default don't draw the height of the user-provided cutree\n # since function like `dynamicTreeCut` will merge tree\n (!is.null(k) || !is.null(h)) && is.null(cutree)\n )\n plot <- ggplot(mapping = mapping)\n if (plot_dendrogram) {\n plot <- plot + ggplot2::geom_segment(\n mapping = aes(\n x = .data$x, y = .data$y,\n xend = .data$xend, yend = .data$yend\n ),\n ...,\n stat = \"identity\",\n data = function(data) ggalign_attr(data, \"edge\")\n )\n }\n assert_active(active)\n active <- update_active(active, new_active(use = TRUE))\n .align_hclust(\n align = AlignDendro,\n distance = distance,\n method = method,\n use_missing = use_missing,\n merge_dendro = merge_dendrogram,\n plot_cut_height = plot_cut_height,\n type = type, root = root, center = center,\n reorder_dendrogram = reorder_dendrogram,\n reorder_group = reorder_group,\n schemes = default_schemes(th = theme_no_strip()),\n k = k, h = h, cutree = cutree, data = data, active = active,\n size = size, no_axes = no_axes, plot = plot\n )\n}\n\n#' @importFrom ggplot2 aes ggplot\n#' @importFrom rlang inject\n#' @include craft-align-hclust.R\nAlignDendro <- ggproto(\"AlignDendro\", AlignHclust,\n setup_plot = function(self, plot) {\n ggadd_default(plot, aes(x = .data$x, y = .data$y)) + switch_direction(\n self$direction,\n ggplot2::labs(x = \"height\"),\n ggplot2::labs(y = \"height\")\n )\n },\n build_plot = function(self, plot, design, extra_design = NULL,\n previous_design = NULL) {\n plot_cut_height <- self$plot_cut_height\n center <- self$center\n type <- self$type\n root <- self$root\n panel <- .subset2(design, \"panel\")\n index <- .subset2(design, \"index\")\n\n statistics <- .subset2(self, \"statistics\")\n direction <- self$direction\n priority <- switch_direction(direction, \"left\", \"right\")\n dendrogram_panel <- self$panel[index]\n if (!is.null(dendrogram_panel) &&\n # we allow to change the panel level name, but we prevent\n # from changing the underlying factor level (the underlying\n # ordering)\n !all(as.integer(dendrogram_panel) == as.integer(panel))) {\n cli_abort(\"you cannot do sub-splitting in dendrogram groups\")\n }\n\n if (self$multiple_tree) {\n branches <- levels(panel)\n data <- vector(\"list\", length(statistics))\n start <- 0L\n for (i in seq_along(data)) {\n tree <- .subset2(statistics, i)\n n <- stats::nobs(tree)\n end <- start + n\n data[[i]] <- fortify_data_frame(\n tree,\n priority = priority,\n center = center,\n type = type,\n leaf_pos = seq(start + 1L, end),\n leaf_braches = rep_len(.subset(branches, i), n),\n reorder_branches = FALSE,\n root = root,\n double = TRUE,\n call = self$call\n )\n start <- end\n }\n data <- lapply(\n list(\n node = data,\n edge = lapply(data, ggalign_attr, \"edge\")\n ),\n function(dat) {\n ans <- vec_rbind(!!!dat, .names_to = \"parent\")\n ans$.panel <- factor(.subset2(ans, \".panel\"), branches)\n ans\n }\n )\n edge <- .subset2(data, \"edge\")\n node <- .subset2(data, \"node\")\n } else {\n if (nlevels(panel) > 1L && type == \"triangle\" && self$in_linear) {\n cli_warn(c(paste(\n \"{.arg type} of {.arg triangle}\",\n \"is not well support for facet dendrogram\"\n ), i = \"will use {.filed rectangle} dendrogram instead\"))\n type <- \"rectangle\"\n }\n data <- fortify_data_frame(\n statistics,\n priority = priority,\n center = center,\n type = type,\n leaf_braches = as.character(panel),\n # panel has been reordered by the dendrogram index\n reorder_branches = FALSE,\n root = root,\n double = TRUE,\n call = self$call\n )\n edge <- ggalign_attr(data, \"edge\")\n node <- data\n }\n\n # add names\n if (!is.null(self$labels)) {\n node$.names <- .subset(self$labels, .subset2(node, \".index\"))\n }\n if (is_horizontal(direction)) {\n edge <- rename(\n edge,\n c(x = \"y\", xend = \"yend\", y = \"x\", yend = \"xend\")\n )\n node <- rename(node, c(x = \"y\", y = \"x\"))\n }\n\n # we do some tricks, since ggplot2 won't remove the attributes\n # we attach the `edge` data\n plot <- gguse_data(plot, ggalign_data_set(node, edge = edge))\n\n if (plot_cut_height && !is.null(height <- .subset2(self, \"height\"))) {\n plot <- plot +\n switch_direction(\n direction,\n ggplot2::geom_vline(\n xintercept = height, linetype = \"dashed\"\n ),\n ggplot2::geom_hline(\n yintercept = height, linetype = \"dashed\"\n )\n )\n }\n position <- .subset2(self, \"position\")\n if (!self$in_linear || # for circular layout\n # for bottom annotation, reverse y-axis\n (!is.null(position) && position == \"bottom\")) {\n plot <- reverse_continuous_axis(plot, \"y\")\n } else if (!is.null(position) && position == \"left\") {\n # for left annotation, reverse x-axis\n plot <- reverse_continuous_axis(plot, \"x\")\n }\n\n # always turn off clip, this is what dendrogram dependends on\n old_coord <- plot$coordinates\n if (!identical(old_coord$clip, \"off\")) {\n # to prevent from changing the input of user.\n plot$coordinates <- ggproto(NULL, old_coord, clip = \"off\")\n }\n plot\n }\n)\n\ntree_one_node <- function(index, label) {\n structure(\n index,\n class = \"dendrogram\",\n leaf = TRUE,\n height = 0,\n label = label,\n members = 1L\n )\n}\n\n# this function won't set the right `midpoint`, but `dendrogram_data` function\n# won't use it, so, it has no hurt to use.\nmerge_dendrogram <- function(parent, children) {\n if (is.null(parent)) { # if no parent, call the merge function from `stats`\n return(Reduce(function(x, y) {\n merge(x, y, adjust = \"none\")\n }, children))\n }\n children_heights <- vapply(\n children, attr, numeric(1L), \"height\",\n USE.NAMES = FALSE\n )\n parent_branch_heights <- tree_branch_heights(parent)\n cutoff_height <- max(children_heights) + min(parent_branch_heights) * 0.5\n .merge_dendrogram <- function(dend) {\n if (stats::is.leaf(dend)) { # base version, leaf should be the index\n .subset2(children, dend)\n } else { # for a branch, we should update the members, height\n attrs <- attributes(dend)\n # we recursively run for each node of current branch\n dend <- lapply(dend, .merge_dendrogram)\n heights <- vapply(dend, attr, numeric(1L), \"height\",\n USE.NAMES = FALSE\n )\n n_members <- vapply(dend, attr, integer(1L), \"members\",\n USE.NAMES = FALSE\n )\n # we update height and members\n attrs$height <- .subset2(attrs, \"height\") + max(heights)\n attrs$members <- sum(n_members)\n attributes(dend) <- attrs\n dend\n }\n }\n ans <- .merge_dendrogram(parent)\n attr(ans, \"cutoff_height\") <- cutoff_height\n ans\n}\n\n#' @importFrom stats reorder\nreorder_dendrogram <- function(dend, wts) {\n if (inherits(dend, \"hclust\")) dend <- stats::as.dendrogram(dend)\n reorder(x = dend, wts = wts, agglo.FUN = mean)\n}\n\ntree_branch_heights <- function(dend) {\n if (stats::is.leaf(dend)) {\n return(NULL)\n } else {\n c(\n attr(dend, \"height\"),\n unlist(lapply(dend, tree_branch_heights), FALSE, FALSE)\n )\n }\n}\n"], ["/ggalign/R/ggalign.R", "#' Add ggplot by Aligning discrete or continuous variable\n#'\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' `ggalign()` is similar to `ggplot` in that it initializes a `ggplot` data and\n#' `mapping`. `ggalign()` allowing you to provide data in various formats,\n#' including matrices, data frames, or simple vectors. By default, it will\n#' inherit from the layout. If a function, it will apply with the layout matrix.\n#' `ggalign()` focuses on integrating plots into a layout by aligning the axes.\n#'\n#' @param data The following options can be used:\n#' - `NULL`: No data is set.\n#' - [`waiver()`][ggplot2::waiver]: Inherits the data from the layout matrix.\n#' - A `function` (including purrr-like lambda syntax): Applied to the layout\n#' matrix to transform the data before use. To transform the final plot\n#' data, please use [`scheme_data()`].\n#' - A `matrix`, `data.frame`, or atomic vector.\n#' @inheritParams ggplot2::ggplot\n#' @param ... <[dyn-dots][rlang::dyn-dots]> Additional arguments passed to\n#' [`fortify_data_frame()`].\n#' @param size The relative size of the plot, can be specified as a\n#' [`unit()`][grid::unit]. Note that for [`circle_layout()`], all size values\n#' will be interpreted as relative sizes, as this layout type adjusts based on\n#' the available space in the circular arrangement.\n#' @param no_axes `r lifecycle::badge('experimental')` Logical; if `TRUE`,\n#' removes axes elements for the alignment axis using [`theme_no_axes()`]. By\n#' default, will use the option-\n#' `r code_quote(sprintf(\"%s.align_no_axes\", pkg_nm()))`.\n#' @param active A [`active()`] object that defines the context settings when\n#' added to a layout.\n#' @section ggplot2 specification:\n#' `ggalign` initializes a ggplot object. The underlying data is created using\n#' [`fortify_data_frame()`]. Please refer to it for more details.\n#'\n#' When aligning discrete variables, `ggalign()` always applies a default\n#' mapping for the axis of the data index in the layout. Specifically:\n#'\n#' - `aes(y = .data$.y)` is used for the horizontal `stack_layout()` (including\n#' left and right annotations).\n#' - `aes(x = .data$.x)` is used for the vertical `stack_layout()` (including\n#' top and bottom annotations) and `circle_layout()`.\n#'\n#' The following columns will be added to the data frame to align discrete\n#' variables:\n#'\n#' - `.panel`: The panel for the aligned axis. Refers to the `x-axis` for\n#' vertical `stack_layout()` (including top and bottom annotations), and the\n#' `y-axis` for horizontal `stack_layout()` (including left and right\n#' annotations).\n#'\n#' - `.names` ([`vec_names()`][vctrs::vec_names]) and `.index`\n#' ([`vec_size()`][vctrs::vec_size()]/[`NROW()`]): Character names (if\n#' available) and the integer index of the original data.\n#'\n#' - `.x`/`.y` and `.discrete_x`/`.discrete_y`: Integer indices for `x`/`y`\n#' coordinates, and a factor of the data labels (only applicable when names\n#' exist).\n#'\n#' It is recommended to use `.x`/`.y`, or `.discrete_x`/`.discrete_y` as the\n#' `x`/`y` mapping.\n#'\n#' If the data inherits from [`quad_layout()`]/[`ggheatmap()`], additional\n#' columns will be added:\n#'\n#' - `.extra_panel`: Provides the panel information for the column (left or\n#' right annotation) or row (top or bottom annotation).\n#' - `.extra_index`: The index information for the column (left or right\n#' annotation) or row (top or bottom annotation).\n#'\n#' @inheritSection align Discrete Axis Alignment\n#' @examples\n#' ggheatmap(matrix(rnorm(81), nrow = 9)) +\n#' anno_top() +\n#' ggalign() +\n#' geom_point(aes(y = value))\n#'\n#' ggheatmap(matrix(rnorm(81), nrow = 9)) +\n#' anno_top(size = 0.5) +\n#' align_dendro(k = 3L) +\n#' ggalign(data = NULL, size = 0.2) +\n#' geom_tile(aes(y = 1L, fill = .panel))\n#'\n#' @importFrom ggplot2 ggplot aes\n#' @importFrom rlang list2\n#' @export\nggalign <- function(data = waiver(), mapping = aes(), ..., size = NULL,\n no_axes = NULL, active = NULL) {\n if (inherits(data, \"uneval\")) {\n cli_abort(c(\n \"{.arg data} cannot be {.obj_type_friendly {data}}\",\n \"i\" = \"Have you misspelled the {.arg data} argument in {.fn ggalign}\"\n ))\n }\n no_axes <- no_axes %||%\n getOption(sprintf(\"%s.align_no_axes\", pkg_nm()), default = TRUE)\n assert_active(active)\n active <- update_active(active, new_active(use = TRUE))\n new_craftbox(\n AlignGg,\n input_data = allow_lambda(data),\n data_params = list2(...),\n plot = ggplot(mapping = mapping),\n size = size,\n schemes = default_schemes(data, th = theme_no_strip()),\n no_axes = no_axes, active = active\n )\n}\n\n#' @importFrom rlang inject\n#' @importFrom ggplot2 ggproto ggplot\nAlignGg <- ggproto(\"AlignGg\", Craftsman,\n interact_layout = function(self, layout) {\n layout_name <- self$layout_name\n input_data <- self$input_data\n object_name <- object_name(self)\n layout_data <- layout@data\n\n # inherit data from the layout\n if (is.function(input_data)) {\n if (is.null(layout_data)) {\n cli_abort(c(\n sprintf(\n \"{.arg data} in %s cannot be a function\",\n object_name\n ),\n i = sprintf(\"no data was found in %s\", layout_name)\n ))\n }\n data <- input_data(layout_data)\n } else if (is.waive(input_data)) {\n data <- layout_data %|w|% NULL\n # for data inherit from the layout, and the layout data is from\n # the quad-layout, we'll integrate the `extra_design`\n self$use_extra_design <- is_stack_layout(layout) &&\n isTRUE(layout@heatmap$quad_matrix)\n } else {\n data <- input_data\n }\n plot_data <- inject(\n fortify_data_frame(data, !!!self$data_params, call = self$call)\n )\n\n # for discrete design, # we need ensure the nobs is the same\n if (is_discrete_design(design <- layout@design)) {\n if (!is.null(data)) {\n if (is.null(layout_nobs <- design$nobs)) {\n layout_nobs <- NROW(data)\n if (layout_nobs == 0L) {\n cli_abort(\"{.arg data} cannot be empty\",\n call = self$call\n )\n }\n } else if (NROW(data) != layout_nobs) {\n cli_abort(sprintf(\n \"%s (nobs: %d) is not compatible with the %s (nobs: %d)\",\n object_name, NROW(data), layout_name, layout_nobs\n ))\n }\n design[\"nobs\"] <- list(layout_nobs)\n\n # we always add `.index` to align the observations\n # For matrix-like object\n if (!is.data.frame(data) &&\n vec_is(dim(data), integer(), size = 2L)) {\n plot_data$.index <- vec_rep(seq_len(NROW(data)), NCOL(data))\n } else {\n plot_data$.index <- seq_len(NROW(data))\n }\n layout@design <- design\n self$labels <- vec_names(data) %||% vec_names(layout_data)\n # always remove names, we'll add it in `build_plot()`\n plot_data$.names <- NULL\n } else {\n self$labels <- vec_names(layout_data)\n }\n self$add_mapping <- TRUE\n }\n self$data <- ggalign_data_restore(plot_data, layout_data)\n layout\n },\n setup_plot = function(self, plot) {\n direction <- self$direction\n ggadd_default(\n plot,\n mapping = if (isTRUE(self$add_mapping)) {\n switch_direction(\n direction,\n aes(y = .data$.y),\n aes(x = .data$.x)\n )\n },\n theme = if (is.null(self$data)) {\n # remove the title and text of axis vertically with the layout\n theme_no_axes(switch_direction(direction, \"x\", \"y\"))\n }\n ) + switch_direction(\n direction,\n ggplot2::labs(y = NULL),\n ggplot2::labs(x = NULL)\n )\n },\n\n #' @importFrom stats reorder\n build_plot = function(self, plot, design, extra_design = NULL,\n previous_design = NULL) {\n data <- self$data\n\n # if inherit from the parent layout\n if (isTRUE(self$use_extra_design) &&\n is_discrete_design(extra_design) &&\n !is.null(.subset2(extra_design, \"nobs\"))) {\n # if the data is inherit from the `quad_layout()`\n # the data must be a matrix\n extra_plot_data <- data_frame0(\n .extra_panel = .subset2(extra_design, \"panel\"),\n .extra_index = .subset2(extra_design, \"index\")\n )\n } else {\n extra_plot_data <- NULL\n }\n\n if (is_continuous_design(design)) {\n if (!is.null(data) && !is.null(extra_plot_data)) {\n data <- full_join(data, extra_plot_data,\n by.x = \".column_index\", by.y = \".extra_index\"\n )\n }\n return(gguse_data(plot, data))\n } else if (is.null(.subset2(design, \"nobs\"))) {\n cli_abort(c(\n sprintf(\n \"you must initialize %s before drawing %s\",\n self$layout_name, object_name(self)\n ),\n i = \"Or you should use {.fn ggfree}\"\n ), call = self$call)\n }\n direction <- self$direction\n axis <- to_coord_axis(direction)\n panel <- .subset2(design, \"panel\")\n index <- .subset2(design, \"index\")\n coord_name <- paste0(\".\", axis)\n plot_data <- data_frame0(\n .panel = panel,\n .index = index,\n # `data_frame0` will omit `NULL`\n .names = .subset(self$labels, index)\n )\n plot_data[[coord_name]] <- seq_along(index)\n if (!is.null(.subset2(plot_data, \".names\"))) {\n plot_data[[paste0(\".discrete_\", axis)]] <- reorder(\n .subset2(plot_data, \".names\"),\n .subset2(plot_data, coord_name),\n order = FALSE\n )\n }\n\n if (!is.null(extra_plot_data)) {\n plot_data <- cross_join(plot_data, extra_plot_data)\n if (!is.null(data)) {\n plot_data <- full_join(data, plot_data,\n by.x = c(\".column_index\", \".index\"),\n by.y = c(\".extra_index\", \".index\")\n )\n }\n } else if (!is.null(data)) {\n plot_data <- full_join(data, plot_data, by = \".index\")\n }\n gguse_data(plot, ggalign_data_restore(plot_data, data))\n },\n\n # let Craftsman to add schemes and theme acoordingly\n finish_plot = function(self, plot, schemes, theme) {\n direction <- self$direction\n # remove axis titles, text, ticks used for alignment\n if (isTRUE(self$no_axes)) {\n schemes$scheme_theme <- .subset2(schemes, \"scheme_theme\") +\n theme_no_axes(switch_direction(direction, \"y\", \"x\"))\n }\n plot <- plot_add_schemes(plot, schemes)\n if (is_horizontal(direction)) {\n theme <- theme(\n panel.spacing.y = calc_element(\"panel.spacing.y\", theme)\n )\n } else {\n theme <- theme(\n panel.spacing.x = calc_element(\"panel.spacing.x\", theme)\n )\n }\n plot <- plot + theme\n ggremove_margin(plot, direction) + theme_recycle()\n },\n summary = function(self, plot) {\n header <- ggproto_parent(Craftsman, self)$summary(plot)\n c(header, \" Add plot by Aligning discrete or continuous variable\")\n }\n)\n\n#' Create ggplot object with layout panel data\n#'\n#' @description\n#' `r lifecycle::badge(\"deprecated\")`\n#'\n#' This function was deprecated because we realised that it's a special case of\n#' the [`ggalign()`] function. Please use `ggalign(data = NULL)` instead.\n#' @export\n#' @keywords internal\nalign_panel <- function(...) {\n lifecycle::deprecate_stop(\"0.0.5\", \"align_panel()\", \"ggalign(data = NULL)\")\n}\n\n#' @export\n#' @rdname align_panel\nggpanel <- function(...) {\n lifecycle::deprecate_stop(\"0.0.5\", \"ggpanel()\", \"ggalign(data = NULL)\")\n}\n"], ["/ggalign/R/ggplot-facet-sector.R", "#' Polar coordinates with Facet support\n#'\n#' Draw each panel in a sector of the polar coordinate system. If\n#' `facet_sector()` is used in a ggplot, the coordinate system must be created\n#' with [`coord_circle()`] or [`coord_radial()`][ggplot2::coord_radial].\n#'\n#' @inheritParams ggplot2::facet_wrap\n#' @param sector_spacing The size of spacing between different panel. A numeric\n#' of the radians or a [`rel()`][ggplot2::rel] object.\n#' @param radial `r lifecycle::badge(\"deprecated\")` Please add the coordinate\n#' system directly to the ggplot instead.\n#' @param spacing_theta `r lifecycle::badge(\"deprecated\")` Please use\n#' `sector_spacing` instead.\n#' @examples\n#' ggplot(mtcars, aes(disp, mpg)) +\n#' geom_point() +\n#' facet_sector(vars(cyl)) +\n#' coord_circle(\n#' start = -0.4 * pi, end = 0.4 * pi, inner.radius = 0.3,\n#' outer.radius = 0.8, expand = TRUE\n#' )\n#' @importFrom ggplot2 ggproto\n#' @export\nfacet_sector <- function(facets, sector_spacing = pi / 180, drop = TRUE,\n radial = deprecated(), spacing_theta = deprecated()) {\n if (packageVersion(\"ggplot2\") > \"3.5.2\") {\n facets <- ggfun(\"compact_facets\")(facets)\n } else {\n facets <- ggfun(\"wrap_as_facets_list\")(facets)\n }\n if (inherits(sector_spacing, \"CoordRadial\") ||\n lifecycle::is_present(radial)) {\n lifecycle::deprecate_stop(\n \"1.0.2\",\n \"facet_sector(radial = )\",\n details = \"Please add the coordinate to the ggplot instead\"\n )\n }\n if (lifecycle::is_present(spacing_theta)) {\n lifecycle::deprecate_warn(\n \"1.0.2\",\n \"facet_sector(spacing_theta = )\",\n \"facet_sector(sector_spacing = )\"\n )\n sector_spacing <- spacing_theta\n }\n\n # @param strip.position By default, the labels are displayed on the\n # `\"outer\"` of the plot. Allowed values are `r oxford_or(c(\"outer\",\n # \"inner\"))`\n # strip.position <- arg_match0(strip.position, c(\"outer\", \"inner\"))\n # strip.position <- switch(strip.position,\n # outer = \"top\",\n # inner = \"bottom\"\n # )\n # labeller <- ggfun(\"fix_labeller\")(labeller)\n assert_bool(drop)\n\n # TO-DO: remove this line and update to\n # the next version of ggplot2 (> 3.5.2)\n if (packageVersion(\"ggplot2\") > \"3.5.2\") {\n dir <- \"lt\"\n } else {\n dir <- \"h\"\n }\n ggproto(\n NULL,\n FacetSector,\n sector_spacing = sector_spacing,\n params = list(\n facets = facets,\n free = list(x = TRUE, y = FALSE),\n strip.position = \"top\",\n drop = drop, ncol = NULL, nrow = 1L,\n space_free = list(x = TRUE, y = FALSE),\n labeller = ggplot2::label_value, dir = dir,\n draw_axes = list(x = TRUE, y = FALSE),\n axis_labels = list(x = TRUE, y = FALSE),\n as.table = TRUE\n )\n )\n}\n\n#' @importFrom ggplot2 ggplot_add\n#' @export\nggplot_add.FacetSector <- function(object, plot, object_name, ...) {\n plot <- NextMethod()\n if (!inherits(plot, \"ggalign_facet_sector_plot\")) {\n plot <- add_class(plot, \"ggalign_facet_sector_plot\")\n }\n plot\n}\n\n#' @importFrom ggplot2 ggplot_build ggproto ggproto_parent\n#' @export\nggplot_build.ggalign_facet_sector_plot <- function(plot, ...) {\n if (inherits(plot$facet, \"FacetSector\")) {\n if (!inherits(plot$coordinates, \"CoordRadial\")) {\n if (!isTRUE(plot$coordinates$default)) {\n cli_abort(c(\n paste(\n \"Cannot use {.fn {snake_class(plot$coordinates)}}\",\n \"coordinate with {.fn facet_sector}\"\n ),\n i = \"Please use {.fn coord_circle}/{.fn coord_radial} instead\"\n ))\n }\n plot$coordinates <- coord_circle()\n }\n ParentLayout <- plot$layout\n plot$layout <- ggproto(\n \"FacetSectorLayout\", ParentLayout,\n setup_panel_params = function(self) {\n ggproto_parent(ParentLayout, self)$setup_panel_params()\n if (is.null(ggplot2::Facet$setup_panel_params) &&\n !is.null(self$facet$setup_panel_params)) {\n self$panel_params <- self$facet$setup_panel_params(\n self$panel_params, self$coord\n )\n }\n invisible()\n }\n )\n }\n NextMethod()\n}\n\n#' @importFrom rlang inject\n#' @importFrom grid gTree editGrob viewport\n#' @importFrom ggplot2 ggproto ggproto_parent\nFacetSector <- ggproto(\n \"FacetSector\", ggplot2::FacetWrap,\n setup_panel_params = function(self, panel_params, coord, ...) {\n # total theta for panel area and panel spacing\n arc_theta <- abs(diff(coord$arc))\n sector_spacing <- self$sector_spacing\n if (inherits(sector_spacing, \"rel\")) {\n sector_spacing <- sector_spacing * arc_theta\n }\n panel_weights <- vapply(panel_params, function(panel_param) {\n abs(diff(.subset2(panel_param, \"theta.range\")))\n }, numeric(1L), USE.NAMES = FALSE)\n\n # total theta for panel area\n panel_theta <- arc_theta -\n # substract the number of spacing between panels\n sector_spacing *\n # for the whole circle, arc_theta == 2 * pi\n # there should be as many panels as the number of panel spacing\n if (abs(arc_theta - 2 * pi) < .Machine$double.eps^0.5) {\n length(panel_weights)\n } else {\n length(panel_weights) - 1L\n }\n if (panel_theta <= 0L) {\n cli_abort(\"No panel area, try to reduce {.arg sector_spacing}\")\n }\n\n # re-distribute the arc for each panel\n panel_point <- vec_interleave(\n panel_theta * panel_weights / sum(panel_weights),\n rep_len(sector_spacing, length(panel_weights))\n )\n panel_point <- cumsum(c(coord$arc[1L], utils::head(panel_point, -1L)))\n for (i in seq_along(panel_params)) {\n panel_param <- .subset2(panel_params, i)\n panel_param$arc <- panel_point[i * 2L - 1:0]\n panel_param$bbox <- ggfun(\"polar_bbox\")(\n panel_param$arc, margin = c(0, 0, 0, 0),\n inner_radius = coord$inner_radius\n )\n panel_params[[i]] <- panel_param\n }\n panel_params\n },\n draw_panels = function(self, panels, layout, x_scales, y_scales, ranges,\n coord, data, theme, params) {\n # merge different sector into one panel\n bbox <- ggfun(\"polar_bbox\")(\n coord$arc, margin = c(0, 0, 0, 0),\n inner_radius = coord$inner_radius\n )\n for (i in seq_along(panels)) {\n panel_param <- .subset2(ranges, i)\n vp <- list(\n x = scales::rescale(panel_param$bbox$x, from = bbox$x),\n y = scales::rescale(panel_param$bbox$y, from = bbox$y)\n )\n panels[[i]] <- editGrob(\n .subset2(panels, i),\n vp = viewport(\n x = vp$x[1L], y = vp$y[1L],\n width = abs(diff(vp$x)),\n height = abs(diff(vp$y)),\n just = c(0, 0),\n clip = \"off\",\n default.units = \"native\"\n )\n )\n }\n panels <- gTree(children = inject(gList(!!!panels)))\n ranges <- lapply(ranges, function(panel_param) {\n panel_param$arc <- coord$arc\n panel_param$bbox <- bbox\n panel_param\n })\n ggplot2::FacetNull$draw_panels(\n panels = list(panels),\n layout = layout, x_scales = x_scales, y_scales = y_scales,\n ranges = ranges, coord = coord, data = data,\n theme = theme, params = params\n )\n }\n)\n"], ["/ggalign/R/layout-heatmap-oncoplot.R", "#' Create an OncoPrint\n#'\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' The `ggoncoplot()` function generates `oncoPrint` visualizations that display\n#' genetic alterations in a matrix format. This function is especially useful\n#' for visualizing complex genomic data, such as mutations, copy number\n#' variations, and other genomic alterations in cancer research.\n#'\n#' @details\n#' `ggoncoplot()` is a wrapper around the [`ggheatmap()`] function, designed to\n#' simplify the creation of `OncoPrint`-style visualizations. The function\n#' automatically processes the input character matrix by splitting the encoded\n#' alterations (delimited by `r oxford_or(c(\";\", \":\", \",\", \"|\"))`) into\n#' individual genomic events and unnesting the columns for visualization.\n#'\n#' @param data A character matrix which encodes the alterations, you can use\n#' `r oxford_or(c(\";\", \":\", \",\", \"|\"))` to separate multiple alterations.\n#' @inheritParams heatmap_layout\n#' @param map_width,map_height A named numeric value defines the width/height of\n#' each alterations.\n#'\n#' @param reorder_row A boolean value indicating whether to reorder the rows\n#' based on the frequency of alterations. You can set this to `FALSE`, then add\n#' `align_order(~rowSums(!is.na(.x)), reverse = TRUE)` to achieve the same\n#' result. You may also need to set `strit = FALSE` in [`align_order()`] if\n#' there are already groups.\n#'\n#' @param reorder_column A boolean value indicating whether to reorder the\n#' columns based on the characteristics of the alterations. You can set this to\n#' `FALSE`, then add `align_order2(memo_order)` to achieve the same result. You\n#' may also need to set `strit = FALSE` in [`align_order2()`] if there are\n#' already groups.\n#'\n#' @param remove_duplicates A logical value indicating whether to remove\n#' duplicated variants within the same cell.\n#'\n#' @param filling Same as [`ggheatmap()`], but only `\"tile\"` can be used.\n#' @examples\n#' # A simple example from `ComplexHeatmap`\n#' mat <- read.table(textConnection(\n#' \"s1,s2,s3\n#' g1,snv;indel,snv,indel\n#' g2,,snv;indel,snv\n#' g3,snv,,indel;snv\"\n#' ), row.names = 1, header = TRUE, sep = \",\", stringsAsFactors = FALSE)\n#'\n#' ggoncoplot(mat, map_width = c(snv = 0.5), map_height = c(indel = 0.9)) +\n#' guides(fill = \"none\") +\n#' anno_top(size = 0.5) +\n#' ggalign() +\n#' geom_bar(aes(fill = value), data = function(x) {\n#' subset(x, !is.na(value))\n#' }) +\n#' anno_right(size = 0.5) +\n#' ggalign() +\n#' geom_bar(aes(fill = value), orientation = \"y\", data = function(x) {\n#' subset(x, !is.na(value))\n#' }) &\n#' scale_fill_brewer(palette = \"Dark2\", na.translate = FALSE)\n#' @inherit heatmap_layout return\n#' @importFrom ggplot2 aes\n#' @export\nggoncoplot <- function(data = NULL, mapping = aes(), ...,\n map_width = NULL, map_height = NULL,\n reorder_row = reorder_column,\n reorder_column = TRUE,\n remove_duplicates = FALSE,\n width = NA, height = NA, filling = waiver(),\n theme = NULL, active = NULL) {\n UseMethod(\"ggoncoplot\")\n}\n\n#' @export\nggoncoplot.NULL <- function(data = NULL, mapping = aes(), ...) {\n cli_abort(\"{.fn ggoncoplot} only accept a valid character matrix\")\n}\n\n#' @export\nggoncoplot.functon <- ggoncoplot.NULL\n\n#' @export\nggoncoplot.formula <- ggoncoplot.functon\n\n#' @importFrom ggplot2 aes\n#' @importFrom rlang arg_match0\n#' @export\n#' @rdname ggoncoplot\nggoncoplot.default <- function(data = NULL, mapping = aes(), ...,\n map_width = NULL, map_height = NULL,\n reorder_row = reorder_column,\n reorder_column = TRUE,\n remove_duplicates = FALSE,\n width = NA, height = NA, filling = waiver(),\n theme = NULL, active = NULL) {\n # prepare the matrix\n data <- fortify_matrix(data = data, ...)\n if (!is.character(data)) {\n cli_abort(\"{.arg data} must be a character matrix\")\n }\n\n assert_bool(reorder_column)\n assert_bool(reorder_row)\n assert_bool(remove_duplicates)\n\n # convert empty string into NA\n data <- trimws(data, whitespace = \"[\\\\h\\\\v]\")\n data[data == \"\"] <- NA_character_\n\n # check filling\n if (isTRUE(filling) || is.waive(filling)) {\n filling <- \"tile\"\n } else if (isFALSE(filling)) {\n filling <- NULL\n } else if (!is.null(filling)) {\n filling <- arg_match0(filling, c(\"tile\", \"raster\"))\n if (filling == \"raster\") {\n cli_warn(\"Cannot use {.fn geom_raster} in oncoplot\")\n filling <- \"tile\"\n }\n }\n\n # prepare the plot data action\n pdata <- function(data) {\n vars <- strsplit(data$value, split = \"\\\\s*[;:,|]\\\\s*\", perl = TRUE)\n if (remove_duplicates) vars <- lapply(vars, vec_unique)\n lvls <- ggalign_lvls_get(data)\n data <- vec_rep_each(data, list_sizes(vars))\n value <- unlist(vars, recursive = FALSE, use.names = FALSE)\n if (!is.null(lvls)) value <- factor(value, levels = lvls)\n data$value <- value\n data\n }\n\n # draw the oncoplot\n ans <- heatmap_layout(\n data = data, mapping = mapping,\n width = width, height = height,\n theme = theme, active = active, filling = NULL\n ) -\n # set the default `scheme_data()`\n scheme_data(data = pdata)\n\n # prepare counts matrix to reorder the column or rows\n if (reorder_column || reorder_row) {\n counts <- !is.na(data)\n storage.mode(counts) <- \"integer\"\n weights <- rowSums(counts)\n row_index <- order(weights, decreasing = TRUE)\n }\n\n if (reorder_row) {\n ans <- ans + anno_left() + align_order(row_index, reverse = TRUE)\n }\n if (reorder_column) {\n column_scores <- .memo_order(vec_slice(counts, row_index))\n ans <- ans +\n anno_top() +\n align_order(order(column_scores, decreasing = TRUE))\n }\n\n # reset the active context\n ans <- ans + quad_active()\n if (!is.null(filling)) {\n # we always make sure heatmap body has such action data\n ans <- ans + scheme_data(data = pdata)\n\n # set mapping for width and height\n tile_mapping <- aes(\n .data$.x, .data$.y,\n fill = .data$value,\n width = replace_na(map_width[.data$value], 1),\n height = replace_na(map_height[.data$value], 1)\n )\n if (!is.null(map_width)) {\n if (!rlang::is_named(map_width) || !is.numeric(map_width)) {\n cli_abort(\"{.arg map_width} must be a named numeric\")\n }\n } else {\n tile_mapping$width <- NULL\n }\n if (!is.null(map_height)) {\n if (!rlang::is_named(map_height) || !is.numeric(map_height)) {\n cli_abort(\"{.arg map_height} must be a named numeric\")\n }\n } else {\n tile_mapping$height <- NULL\n }\n # check if user has provided and manual fill mapping\n if (!is.null(.subset2(ans@plot$mapping, \"fill\"))) {\n tile_mapping$fill <- NULL\n }\n ans <- ans + ggplot2::geom_tile(tile_mapping)\n }\n ans\n}\n\n#' Sort matrix for better visualization\n#'\n#' Helper function used to order the Oncoplot samples. Typically, you would use\n#' this in combination with [`align_order2()`], e.g.,\n#' `align_order2(memo_order)`.\n#'\n#' @param x A matrix, where `NA` values will be treated as empty.\n#' @return A vector of ordering weights.\n#' @export\nmemo_order <- function(x) {\n # For `align_order2()`, rows are considered as the observations\n # `.memo_order` will regard the columns as the observations\n .memo_order(t(x), counts = FALSE, reorder_rows = TRUE)\n}\n\n# Following code is modified from\n# \n.memo_order <- function(x, counts = TRUE, reorder_rows = FALSE) {\n if (!isTRUE(counts)) {\n x <- !is.na(x)\n storage.mode(x) <- \"integer\"\n }\n if (isTRUE(reorder_rows)) {\n row_index <- order(rowSums(x), decreasing = TRUE)\n x <- vec_slice(x, row_index)\n }\n structure(\n apply(x, 2L, function(x) {\n score <- 2^(length(x) - seq_along(x))\n score[x == 0L] <- 0\n sum(score)\n }),\n class = \"memo_weights\"\n )\n}\n\n#' @export\n#' @rdname order2\norder2.memo_weights <- function(x) order(x, decreasing = TRUE)\n"], ["/ggalign/R/alignpatch-guides.R", "#' Returns a list of guide boxes collected from all plots.\n#' Each element in the list corresponds to a specific position, containing a\n#' sub-list of guide boxes, where each guide box represents a single plot.\n#' @noRd\ncollect_guides_list <- function(guides_list, empty = NULL) {\n ans <- lapply(c(.TLBR, \"inside\"), function(guide_pos) {\n guides <- lapply(guides_list, function(guides) {\n # IF no guide-box, a single `zeroGrob()` will be given\n # here, we regard each position is a `zeroGrob()`\n if (is_null_grob(guides)) return(list(guides)) # styler: off\n o <- .subset2(guides, guide_pos)\n # A guide-box should be a `zeroGrob()` or a `gtable` object\n if (maybe_guide_box(o)) {\n return(list(o))\n }\n # For other grobs, we just removed them silently\n if (is.grob(o)) {\n list(NULL)\n } else if (is.list(o)) {\n o[\n vapply(o, maybe_guide_box, # styler: off\n logical(1L), USE.NAMES = FALSE # styler: off\n )\n ]\n } else {\n list(NULL)\n }\n })\n guides <- unlist(guides, FALSE, FALSE)\n guides <- guides[\n !vapply(guides, is.null, logical(1L), USE.NAMES = FALSE)\n ]\n if (is_empty(guides)) empty else guides\n })\n names(ans) <- c(.TLBR, \"inside\")\n ans[!vapply(ans, is.null, logical(1L), USE.NAMES = FALSE)]\n}\n\n#' @param guides A list of guide-box\n#' @importFrom ggplot2 zeroGrob\n#' @importFrom gtable gtable gtable_add_grob\n#' @noRd\nassemble_guides <- function(guides, guide_pos, theme) {\n if (guide_pos == \"inside\") {\n # for `zeroGrob()`, it doesn't record the `viewport` information\n # used to identify the inside guide groups, we just removed them\n guides <- guides[\n !vapply(guides, is_null_grob, logical(1L), USE.NAMES = FALSE)\n ]\n if (is_empty(guides)) {\n guide_box <- zeroGrob()\n } else {\n positions <- justs <- vector(\"list\", length(guides))\n for (i in seq_along(guides)) {\n guide <- .subset2(guides, i)\n # for inside guides, it may contain multiple guide-box\n is_box <- grepl(\"guide-box-inside\", guide$layout$name)\n if (any(is_box)) {\n guides[[i]] <- guide$grobs[is_box]\n } else {\n guides[[i]] <- list(guide)\n }\n positions[[i]] <- lapply(guides[[i]], function(guide_box) {\n unit.c(guide_box$vp$x, guide_box$vp$y)\n })\n justs[[i]] <- lapply(guides[[i]], function(guide_box) {\n guide_box$vp$justification\n })\n }\n guides <- unlist(guides, FALSE, FALSE)\n groups <- data_frame0(\n positions = unlist(positions, FALSE, FALSE),\n justs = unlist(justs, FALSE, FALSE)\n )\n groups <- vec_group_loc(groups)\n index <- vec_seq_along(groups)\n\n # pakcage each group into a guide-box\n box_list <- vector(\"list\", vec_size(index))\n for (i in index) {\n box_list[[i]] <- assemble_box(\n guides[groups$loc[[i]]], guide_pos,\n theme = theme + theme(\n legend.position.inside = groups$key$positions[[i]],\n legend.justification.inside = groups$key$justs[[i]]\n )\n )\n }\n if (vec_size(box_list) > 1L) {\n guide_box <- gtable(unit(1L, \"npc\"), unit(1L, \"npc\"))\n guide_box <- gtable_add_grob(\n guide_box, box_list,\n t = 1L, l = 1L, clip = \"off\",\n name = paste(\"guide-box-collected-inside\", index, sep = \"-\")\n )\n } else {\n guide_box <- box_list[[1L]]\n }\n }\n } else {\n guide_box <- assemble_box(guides, guide_pos, theme = theme)\n }\n guide_box\n}\n\n#' @param guides A list of guide-box\n#' @importFrom rlang try_fetch\n#' @importFrom ggplot2 zeroGrob\n#' @noRd\nassemble_box <- function(guides, guide_pos, theme) {\n guides <- guides[\n !vapply(guides, is_null_grob, logical(1L), USE.NAMES = FALSE)\n ]\n if (is_empty(guides)) {\n zeroGrob()\n } else {\n # Remove the guide box background\n grobs <- lapply(guides, function(box) {\n box$grobs[grepl(\"guides\", box$layout$name)]\n })\n grobs <- unlist(grobs, FALSE, FALSE)\n\n # remove duplicated guides\n grobs <- collapse_guides(grobs)\n if (is_empty(grobs)) return(zeroGrob()) # styler: off\n # for every position, collect all individual guides and arrange them\n # into a guide box which will be inserted into the main gtable\n package_box <- try_fetch(\n .subset2(ggfun(\"Guides\"), \"package_box\"),\n error = function(cnd) package_box\n )\n package_box(grobs, guide_pos, theme)\n }\n}\n\n# The following code was used in earlier versions of ggplot2; \n# coverage is not calculated here.\n# nocov start\n#' @importFrom gtable gtable_add_rows gtable_add_cols\n#' @importFrom ggplot2 calc_element\n#' @importFrom grid valid.just editGrob viewport\npackage_box <- function(guides, guide_pos, theme) {\n theme <- complete_guide_theme(guide_pos, theme)\n guides <- guides_build(guides, theme)\n\n # Set the justification of the legend box\n # First value is xjust, second value is yjust\n just <- valid.just(calc_element(\"legend.justification\", theme))\n xjust <- just[1L]\n yjust <- just[2L]\n guides <- editGrob(guides,\n vp = viewport(x = xjust, y = yjust, just = c(xjust, yjust))\n )\n guides <- gtable_add_rows(guides, unit(yjust, \"null\"))\n guides <- gtable_add_rows(guides, unit(1L - yjust, \"null\"), 0L)\n guides <- gtable_add_cols(guides, unit(xjust, \"null\"), 0L)\n guides <- gtable_add_cols(guides, unit(1L - xjust, \"null\"))\n guides\n}\n\n#' @importFrom gtable gtable_width gtable_height gtable gtable_add_grob\n#' @importFrom grid editGrob heightDetails widthDetails valid.just unit.c unit\n#' @importFrom ggplot2 margin element_grob element_blank calc_element element_render\nguides_build <- function(guides, theme) {\n legend.spacing.y <- .subset2(theme, \"legend.spacing.y\")\n legend.spacing.x <- .subset2(theme, \"legend.spacing.x\")\n legend.box.margin <- calc_element(\"legend.box.margin\", theme) %||%\n margin()\n widths <- do.call(`unit.c`, lapply(guides, gtable_width))\n heights <- do.call(`unit.c`, lapply(guides, gtable_height))\n\n just <- valid.just(.subset2(theme, \"legend.box.just\"))\n xjust <- just[1]\n yjust <- just[2]\n vert <- identical(.subset2(theme, \"legend.box\"), \"horizontal\")\n guides <- lapply(guides, function(g) {\n editGrob(g, vp = viewport(\n x = xjust, y = yjust, just = c(xjust, yjust),\n height = if (vert) heightDetails(g) else 1,\n width = if (!vert) widthDetails(g) else 1\n ))\n })\n guide_ind <- seq(by = 2, length.out = length(guides))\n sep_ind <- seq(2, by = 2, length.out = length(guides) - 1)\n if (vert) {\n heights <- max(heights)\n if (length(widths) != 1) {\n w <- unit(rep_len(0, length(widths) * 2 - 1), \"mm\")\n w[guide_ind] <- widths\n w[sep_ind] <- legend.spacing.x\n widths <- w\n }\n } else {\n widths <- max(widths)\n if (length(heights) != 1) {\n h <- unit(rep_len(0, length(heights) * 2 - 1), \"mm\")\n h[guide_ind] <- heights\n h[sep_ind] <- legend.spacing.y\n heights <- h\n }\n }\n widths <- unit.c(legend.box.margin[4], widths, legend.box.margin[2])\n heights <- unit.c(legend.box.margin[1], heights, legend.box.margin[3])\n guides <- gtable_add_grob(\n gtable(widths, heights, name = \"guide-box\"),\n guides,\n t = 1 + if (!vert) guide_ind else 1,\n l = 1 + if (vert) guide_ind else 1,\n name = \"guides\"\n )\n gtable_add_grob(\n guides,\n element_render(theme, \"legend.box.background\"),\n t = 1, l = 1, b = -1, r = -1,\n z = -Inf, clip = \"off\", name = \"legend.box.background\"\n )\n}\n\n#' @importFrom ggplot2 calc_element\ncomplete_guide_theme <- function(guide_pos, theme) {\n if (guide_pos %in% c(\"top\", \"bottom\")) {\n theme$legend.box <- calc_element(\"legend.box\", theme) %||% \"horizontal\"\n theme$legend.direction <- calc_element(\"legend.direction\", theme) %||%\n \"horizontal\"\n theme$legend.box.just <- calc_element(\"legend.box.just\", theme) %||%\n c(\"center\", \"top\")\n } else {\n theme$legend.box <- calc_element(\"legend.box\", theme) %||% \"vertical\"\n theme$legend.direction <- calc_element(\"legend.direction\", theme) %||%\n \"vertical\"\n theme$legend.box.just <- calc_element(\"legend.box.just\", theme) %||%\n c(\"left\", \"top\")\n }\n theme\n}\n# nocov end\n\n################################################################ 3\n# Copied from patchwork\ncollapse_guides <- function(guides) {\n unnamed <- lapply(guides, unname_grob)\n for (i in rev(seq_along(unnamed)[-1])) {\n for (j in seq_len(i - 1)) {\n if (isTRUE(all.equal(unnamed[[i]], unnamed[[j]],\n check.names = FALSE, check.attributes = FALSE\n ))) {\n guides[i] <- NULL\n break\n }\n }\n }\n guides\n}\n\n#' @importFrom grid is.unit absolute.size\nunname_vp <- function(x) {\n if (inherits(x, \"vpTree\")) {\n x$parent <- unname_vp(x$parent)\n x$children <- lapply(x$children, unname_vp)\n } else if (inherits(x, \"viewport\")) {\n x$name <- \"\"\n if (!is.null(x$layout$widths)) {\n x$layout$widths <- absolute.size(x$layout$widths)\n }\n if (!is.null(x$layout$heights)) {\n x$layout$heights <- absolute.size(x$layout$heights)\n }\n }\n unit_elements <- vapply(x, is.unit, logical(1), USE.NAMES = FALSE)\n x[unit_elements] <- lapply(.subset(x, unit_elements), absolute.size)\n x\n}\n\n#' @importFrom grid is.grob is.unit absolute.size\n#' @importFrom gtable is.gtable\nunname_grob <- function(x) {\n if (is.gtable(x)) {\n x$name <- \"\"\n x$rownames <- NULL\n x$vp <- unname_vp(x$vp)\n names(x$grobs) <- NULL\n x$grobs <- lapply(x$grobs, unname_grob)\n } else if (is.grob(x)) {\n x$name <- \"\"\n x$vp <- unname_vp(x$vp)\n x$children <- unname(lapply(x$children, unname_grob))\n x$childrenOrder <- rep_len(\"\", length(x$childrenOrder))\n }\n unit_elements <- vapply(x, is.unit, logical(1), USE.NAMES = FALSE)\n x[unit_elements] <- lapply(.subset(x, unit_elements), absolute.size)\n x\n}\n"], ["/ggalign/R/layout-quad-upset.R", "#' Create an UpSet plot\n#'\n#' @description\n#' `r lifecycle::badge('experimental')`\n#'\n#' `ggupset` is a specialized version of [`quad_discrete()`], which simplifies\n#' the creation of Upset plot.\n#'\n#' @param data Data used to create the UpSet plot. [`fortify_matrix()`] will be\n#' used to convert the data to a matrix. Currently, only\n#' [`fortify_matrix.list_upset`] and [`fortify_matrix.matrix_upset`] are\n#' suitable for creating an UpSet plot.\n#' @param ... Additional arguments passed to [`fortify_matrix()`].\n#' @inheritParams quad_layout\n#' @param direction A string indicating the direction of the UpSet plot,\n#' `\"h\"`(`horizontal`) or `\"v\"`(`vertical`). In a vertical UpSet plot, the\n#' columns of the matrix correspond to the sets, and the rows correspond to the\n#' intersections. By default, the horizontal UpSet plot is used, where the rows\n#' of the matrix correspond to the sets and the columns correspond to the\n#' intersections.\n#' @param point A list of parameters passed to\n#' [`geom_point()`][ggplot2::geom_point()].\n#' @param line A list of parameters passed to\n#' [`geom_line()`][ggplot2::geom_line()].\n#' @param rect A list of parameters passed to\n#' [`geom_rect()`][ggplot2::geom_rect()].\n#'\n#' @inheritSection heatmap_layout ggplot2 specification\n#' @examples\n#' set.seed(123)\n#' lt <- list(\n#' a = sample(letters, 5),\n#' b = sample(letters, 10),\n#' c = sample(letters, 15)\n#' )\n#' ggupset(tune(lt)) +\n#' scale_fill_manual(values = c(\"#F0F0F0\", \"white\"), guide = \"none\") +\n#' scale_color_manual(values = c(\"grey\", \"black\"), guide = \"none\") +\n#' anno_top() +\n#' ggalign(data = function(d) ggalign_attr(d, \"intersection_sizes\")) +\n#' ggplot2::geom_bar(aes(y = .data$value), stat = \"identity\") +\n#' anno_right() +\n#' ggalign(data = function(d) ggalign_attr(d, \"set_sizes\")) +\n#' ggplot2::geom_bar(aes(x = .data$value),\n#' stat = \"identity\",\n#' orientation = \"y\"\n#' )\n#' @importFrom ggplot2 aes\n#' @export\nggupset <- function(data = NULL, mapping = aes(),\n ...,\n direction = \"h\",\n point = NULL, line = NULL, rect = NULL,\n width = NA, height = NA,\n theme = NULL, active = NULL) {\n UseMethod(\"ggupset\")\n}\n\n# Don't allow inherit from the parent layout, since data for upset plot is\n# usually different with others\n#' @export\nggupset.NULL <- function(data, ...) {\n cli_abort(\"{.arg data} must be provided to create upset plot\")\n}\n\n#' @export\nggupset.waiver <- ggupset.NULL\n\n#' @importFrom ggplot2 aes\n#' @export\nggupset.default <- function(data = NULL, mapping = aes(),\n ...,\n direction = \"h\",\n point = NULL, line = NULL, rect = NULL,\n width = NA, height = NA,\n theme = NULL, active = NULL) {\n direction <- check_direction(direction)\n # we need a matrix to melted into long formated data frame\n data <- fortify_matrix(data = data, ...)\n if (is_vertical(direction)) data <- ggalign_data_restore(t(data), data)\n ans <- new_quad_layout(\n name = \"ggupset\",\n data = data,\n mapping = mapping,\n theme = theme,\n active = active\n )\n ans@plot <- ggadd_default(ans@plot, mapping = aes(.data$.x, .data$.y)) +\n ggplot2::labs(x = NULL, y = NULL) +\n upset_rect(direction, rect) +\n upset_point(point) +\n upset_line(direction, line)\n ans\n}\n\nmerge_mapping <- function(x, y) {\n if (is.null(x)) {\n return(y)\n }\n for (i in names(y)) {\n x[[i]] <- .subset2(y, i)\n }\n x\n}\n\nmerge_data_fn <- function(plot_data, user_data) {\n if (is.null(user_data) || is.waive(user_data)) {\n plot_data\n } else if (is.function(user_data <- allow_lambda(user_data))) {\n force(plot_data)\n function(data) user_data(plot_data(data))\n } else {\n user_data\n }\n}\n\nupset_rect <- function(direction, rect) {\n if (is_horizontal(direction)) {\n rect$mapping <- merge_mapping(rect$mapping, aes(\n ymin = .data$.ymin, ymax = .data$.ymax, fill = .data$rect_group\n ))\n rect$data <- merge_data_fn(function(data) {\n column <- c(\n \".y\", \".panel_x\", \".panel_y\",\n \".row_index\", \".row_names\", \".discrete_y\"\n )\n o <- vec_unique(data[vec_set_intersect(column, names(data))])\n o$rect_group <- (.subset2(o, \".y\") %% 2L) == 0L\n o$.ymin <- o$.y - 0.5\n o$.ymax <- o$.y + 0.5\n o\n }, rect$data)\n inject(ggplot2::geom_rect(!!!rect,\n xmin = -Inf, xmax = Inf, inherit.aes = FALSE\n ))\n } else {\n rect$mapping <- merge_mapping(rect$mapping, aes(\n xmin = .data$.xmin, xmax = .data$.xmax,\n fill = .data$rect_group\n ))\n rect$data <- merge_data_fn(function(data) {\n column <- c(\n \".x\", \".panel_x\", \".panel_y\",\n \".column_index\", \".column_names\", \".discrete_x\"\n )\n o <- vec_unique(data[vec_set_intersect(column, names(data))])\n o$rect_group <- (.subset2(o, \".x\") %% 2L) == 0L\n o$.xmin <- o$.x - 0.5\n o$.xmax <- o$.x + 0.5\n o\n }, rect$data)\n inject(ggplot2::geom_rect(!!!rect,\n ymin = -Inf, ymax = Inf, inherit.aes = FALSE\n ))\n }\n}\n\nupset_point <- function(point) {\n point$mapping <- merge_mapping(point$mapping, aes(\n x = .data$.x, y = .data$.y, color = .data$point_group\n ))\n point$data <- merge_data_fn(function(data) {\n data$point_group <- .subset2(data, \"value\")\n data\n }, point$data)\n inject(ggplot2::geom_point(!!!point, inherit.aes = FALSE))\n}\n\nupset_line <- function(direction, line) {\n line$mapping <- merge_mapping(line$mapping, switch_direction(\n direction,\n aes(.data$.x, .data$.y, group = paste(.data$.panel_x, .data$.x)),\n aes(.data$.x, .data$.y, group = paste(.data$.panel_y, .data$.y))\n ))\n line$data <- merge_data_fn(function(data) {\n if (is_horizontal(direction)) {\n dlist <- vec_split(data, data[c(\".panel_x\", \".x\")])\n dlist <- lapply(.subset2(dlist, \"val\"), function(d) {\n o <- vec_slice(d, .subset2(d, \"value\"))\n if (vec_size(o) < 2L) {\n return(NULL)\n }\n vec_slice(o, c(\n which.min(.subset2(o, \".y\")),\n which.max(.subset2(o, \".y\"))\n ))\n })\n vec_rbind(!!!dlist)\n } else {\n dlist <- vec_split(data, data[c(\".panel_y\", \".y\")])\n dlist <- lapply(.subset2(dlist, \"val\"), function(d) {\n o <- vec_slice(d, .subset2(d, \"value\"))\n if (vec_size(o) < 2L) {\n return(NULL)\n }\n vec_slice(o, c(\n which.min(.subset2(o, \".x\")),\n which.max(.subset2(o, \".x\"))\n ))\n })\n vec_rbind(!!!dlist)\n }\n }, line$data)\n inject(ggplot2::geom_line(!!!line, inherit.aes = FALSE))\n}\n"], ["/ggalign/R/ggplot-geom-rect3d.R", "#' Add z-aesthetic for geom_tile\n#'\n#' @section new aesthetics:\n#' - `z`: the third dimention (in the z direction), use\n#' [`scale_z_continuous()`] to control the ranges.\n#' - `theta`: Angle between x-axis and z-axis.\n#' @inheritParams ggplot2::layer\n#' @inheritParams ggplot2::geom_polygon\n#' @inheritParams ggplot2::geom_path\n#' @aesthetics GeomRect3d\n#' @examples\n#' set.seed(123)\n#' small_mat <- matrix(rnorm(81), nrow = 9)\n#' rownames(small_mat) <- paste0(\"row\", seq_len(nrow(small_mat)))\n#' colnames(small_mat) <- paste0(\"column\", seq_len(ncol(small_mat)))\n#' ggheatmap(small_mat,\n#' filling = FALSE,\n#' theme = theme(\n#' legend.box.spacing = unit(10, \"mm\"),\n#' plot.margin = margin(t = 15, unit = \"mm\")\n#' )\n#' ) +\n#' geom_tile3d(\n#' aes(fill = value, z = value, width = 0.8, height = 0.8),\n#' color = \"black\"\n#' ) +\n#' scale_fill_viridis_c(\n#' option = \"plasma\",\n#' breaks = scales::breaks_pretty(3L)\n#' ) +\n#' coord_cartesian(clip = \"off\")\n#'\n#' @export\ngeom_rect3d <- function(mapping = NULL, data = NULL, stat = \"identity\",\n position = \"identity\", ...,\n lineend = \"butt\", linejoin = \"round\", linemitre = 10,\n na.rm = FALSE, show.legend = NA, inherit.aes = TRUE) {\n ggplot2::layer(\n data = data,\n mapping = mapping,\n stat = stat,\n geom = GeomRect3d,\n position = position,\n show.legend = show.legend,\n inherit.aes = inherit.aes,\n params = list(\n lineend = lineend,\n linejoin = linejoin,\n linemitre = linemitre,\n na.rm = na.rm, ...\n )\n )\n}\n\n#' @importFrom ggplot2 ggproto fill_alpha\nGeomRect3d <- ggproto(\n \"GeomRect3d\",\n ggplot2::GeomRect,\n required_aes = c(ggplot2::GeomRect$required_aes, \"z\"),\n non_missing_aes = c(ggplot2::GeomRect$non_missing_aes, \"z\", \"theta\"),\n setup_data = function(self, data, params) {\n theta <- data$theta %||% .subset2(params, \"theta\")\n if (!is.null(theta) && any(theta <= 0 || theta >= 90)) {\n cli_abort(\n \"value mapped to {.field theta} aesthetic must > 0 and < 90.\"\n )\n }\n data$theta <- theta %||% 60\n ggproto_parent(ggplot2::GeomRect, self)$setup_data(data, params)\n },\n draw_panel = function(self, data, panel_params, coord, lineend = \"butt\",\n linejoin = \"round\", linemitre = 10) {\n data <- setup_3d_data(data)\n # Transform to viewport coords\n coords <- coord$transform(data, panel_params)\n\n # collapse the gpar value\n data <- .subset2(\n vec_split(\n data[setdiff(names(data), c(\"x\", \"y\", \"width\", \"height\"))],\n .subset2(data, \"polygon_id\")\n ),\n \"val\"\n )\n data <- vec_rbind(!!!lapply(data, vec_unique))\n\n # Draw as grob\n grid::polygonGrob(\n x = coords$x,\n y = coords$y,\n id = coords$polygon_id,\n default.units = \"native\",\n gp = gpar(\n col = data$colour,\n fill = fill_alpha(data$fill, data$alpha),\n lwd = data$linewidth,\n lty = data$linetype,\n lineend = lineend,\n linejoin = linejoin,\n linemitre = linemitre\n )\n )\n }\n)\n\nsetup_3d_data <- function(data) {\n data <- vec_slice(\n data,\n order(\n .subset2(data, \"xmin\"),\n .subset2(data, \"ymin\"),\n decreasing = TRUE\n )\n )\n coords <- .mapply(\n function(xmin, xmax, ymin, ymax, z, theta, ...) {\n if (z == 0L) {\n # fallback to tile\n data_frame0(\n x = vec_c(xmin, xmax, xmax, xmin),\n y = vec_rep_each(c(ymin, ymax), 2L)\n )\n } else {\n offset_x <- z * cos(theta / 180 * pi)\n z_xmin <- xmin + offset_x\n z_xmax <- xmax + offset_x\n offset_y <- z * sin(theta / 180 * pi)\n z_ymin <- ymin + offset_y\n z_ymax <- ymax + offset_y\n data_frame0(\n x = vec_c(\n xmin, z_xmin, z_xmax, xmax, xmin, xmin,\n z_xmin, z_xmin, z_xmin, z_xmax, z_xmax, z_xmin\n ),\n y = vec_c(\n ymin, z_ymin, z_ymin, ymin, ymin, ymax,\n z_ymax, z_ymin, z_ymax, z_ymax, z_ymin, z_ymin\n )\n )\n }\n },\n data,\n MoreArgs = NULL\n )\n vec_cbind(\n vec_rbind(!!!coords),\n vec_rep_each(\n data[\n vec_set_difference(\n names(data),\n c(\"x\", \"xmin\", \"xmax\", \"y\", \"ymin\", \"ymax\", \"z\")\n )\n ],\n list_sizes(coords)\n ),\n polygon_id = vec_rep_each(seq_along(coords), list_sizes(coords))\n )\n}\n\n#' @aesthetics GeomTile3d\n#' @importFrom rlang list2\n#' @export\n#' @rdname geom_rect3d\ngeom_tile3d <- function(mapping = NULL, data = NULL, stat = \"identity\",\n position = \"identity\", ...,\n lineend = \"butt\", linejoin = \"round\", linemitre = 10,\n na.rm = FALSE, show.legend = NA, inherit.aes = TRUE) {\n ggplot2::layer(\n data = data,\n mapping = mapping,\n stat = stat,\n geom = GeomTile3d,\n position = position,\n show.legend = show.legend,\n inherit.aes = inherit.aes,\n params = list(\n lineend = lineend,\n linejoin = linejoin,\n linemitre = linemitre,\n na.rm = na.rm, ...\n )\n )\n}\n\n#' @importFrom ggplot2 ggproto ggproto_parent\nGeomTile3d <- ggproto(\n \"GeomTile3d\",\n ggplot2::GeomTile,\n required_aes = c(ggplot2::GeomTile$required_aes, \"z\"),\n non_missing_aes = c(ggplot2::GeomTile$non_missing_aes, \"z\", \"theta\"),\n setup_data = function(self, data, params) {\n theta <- data$theta %||% .subset2(params, \"theta\")\n if (!is.null(theta) && any(theta <= 0 || theta >= 90)) {\n cli_abort(\n \"value mapped to {.field theta} aesthetic must > 0 and < 90.\"\n )\n }\n data$theta <- theta %||% 60\n ggproto_parent(ggplot2::GeomTile, self)$setup_data(data, params)\n },\n draw_panel = function(self, data, panel_params, coord, lineend = \"butt\",\n linejoin = \"round\", linemitre = 10) {\n ggproto_parent(GeomRect3d, self)$draw_panel(\n data = data, panel_params = panel_params, coord = coord,\n lineend = lineend, linejoin = linejoin, linemitre = linemitre\n )\n }\n)\n\n#' z scales\n#'\n#' @param ... Other arguments passed on to\n#' [`continuous_scale()`][ggplot2::continuous_scale],\n#' [`binned_scale()`][ggplot2::binned_scale], or\n#' [`discrete_scale()`][ggplot2::discrete_scale] as appropriate, to control\n#' name, limits, breaks, labels and so forth.\n#' @param range Output range of z values. Must larger than 0.\n#' @inheritParams ggplot2::continuous_scale\n#' @seealso [`geom_tile3d()`]/[`geom_rect3d()`]\n#' @export\n#' @examples\n#'\n#' set.seed(7)\n#' mat <- matrix(runif(100), 10)\n#' rownames(mat) <- LETTERS[1:10]\n#' colnames(mat) <- letters[1:10]\n#' ggheatmap(mat,\n#' filling = FALSE,\n#' theme = theme(\n#' legend.box.spacing = unit(10, \"mm\"),\n#' plot.margin = margin(t = 15, unit = \"mm\")\n#' )\n#' ) +\n#' geom_tile3d(aes(fill = value, z = value, width = 0.8, height = 0.8)) +\n#' scale_z_continuous(range = c(0.2, 1)) +\n#' coord_cartesian(clip = \"off\")\n#' @export\nscale_z_continuous <- function(name = waiver(), ..., range = c(0.1, 1),\n guide = \"none\") {\n if (min(range) < 0) {\n cli_abort(\"{.arg range} must contain only positive values\")\n }\n ggplot2::continuous_scale(\"z\",\n name = name, palette = scales::pal_rescale(range), ...,\n guide = guide\n )\n}\n\n#' @rdname scale_z_continuous\n#' @export\nscale_z_binned <- function(name = waiver(), ..., range = c(0.1, 1),\n guide = \"none\") {\n if (min(range) < 0) {\n cli_abort(\"{.arg range} must contain only positive values\")\n }\n ggplot2::binned_scale(\"z\",\n name = name, palette = scales::pal_rescale(range), ...,\n guide = guide\n )\n}\n\n#' @rdname scale_z_continuous\n#' @export\nscale_z_discrete <- function(...) {\n cli_warn(\"Using {z} for a discrete variable is not advised.\")\n args <- list2(...)\n args$call <- args$call %||% current_call()\n rlang::exec(scale_z_ordinal, !!!args)\n}\n\n#' @rdname scale_z_continuous\n#' @export\nscale_z_ordinal <- function(name = waiver(), ..., range = c(0.1, 1),\n guide = \"none\") {\n if (min(range) < 0) {\n cli_abort(\"{.arg range} must contain only positive values\")\n }\n ggplot2::discrete_scale(\n \"z\",\n name = name,\n palette = function(n) seq(range[1], range[2], length.out = n),\n ...,\n gudie = guide\n )\n}\n\n#' @rdname scale_z_continuous\n#' @export\n#' @usage NULL\nscale_z_datetime <- function(name = waiver(), ..., range = c(0.1, 1),\n guide = \"none\") {\n if (min(range) < 0) {\n cli_abort(\"{.arg range} must contain only positive values\")\n }\n ggplot2::datetime_scale(\n aesthetics = \"z\", transform = \"time\", name = name,\n palette = scales::pal_rescale(range),\n ..., guide = guide\n )\n}\n\n#' @rdname scale_z_continuous\n#' @export\n#' @usage NULL\nscale_z_date <- function(name = waiver(), ..., range = c(0.1, 1),\n guide = \"none\") {\n if (min(range) < 0) {\n cli_abort(\"{.arg range} must contain only positive values\")\n }\n ggplot2::datetime_scale(\n aesthetics = \"z\", transform = \"date\", name = name,\n palette = scales::pal_rescale(range),\n ..., guide = guide\n )\n}\n"], ["/ggalign/R/craft-cross-mark.R", "#' Add a plot to annotate observations\n#'\n#' @inheritParams cross_none\n#' @inheritParams ggmark\n#'\n#' @section ggplot2 Specification:\n#' The `cross_mark` function initializes a `ggplot` object. The underlying data\n#' contains following columns:\n#'\n#' - `.panel`: the panel for the aligned axis. It means `x-axis` for vertical\n#' stack layout (including top and bottom annotation), `y-axis` for\n#' horizontal stack layout (including left and right annotation).\n#'\n#' - `.names` ([`vec_names()`][vctrs::vec_names]) and `.index`\n#' ([`vec_size()`][vctrs::vec_size()]/[`NROW()`]): a character names (only\n#' applicable when names exists) and an integer of index of the original\n#' data.\n#'\n#' - `.hand`: A factor with levels `c(\"left\", \"right\")` for horizontal stack\n#' layouts, or `c(\"top\", \"bottom\")` for vertical stack layouts, indicating\n#' the position of the linked observations.\n#'\n#' You can use [`scheme_data()`] to modify the internal data if needed.\n#'\n#' @export\ncross_mark <- function(mark, data = waiver(), ...,\n obs_size = 1, inherit_index = NULL, inherit_panel = NULL,\n inherit_nobs = NULL,\n size = NULL, active = NULL) {\n if (!inherits(mark, \"ggalign_mark_draw\")) {\n cli_abort(\"{.arg mark} must be a {.fn mark_draw} object\")\n }\n assert_obs_size(obs_size)\n assert_active(active)\n active <- update_active(active, new_active(use = TRUE))\n cross(CrossMark,\n data = data, data_params = list2(...),\n mark = mark, obs_size = obs_size,\n plot = ggplot(), size = size,\n schemes = default_schemes(th = theme_panel_border()),\n active = active,\n inherit_nobs = inherit_nobs,\n inherit_panel = inherit_panel,\n inherit_index = inherit_index\n )\n}\n\n#' @importFrom ggplot2 ggproto ggproto_parent\n#' @include craft-cross-.R\nCrossMark <- ggproto(\"CrossMark\", CraftCross,\n interact_layout = function(self, layout) {\n if (!self$in_linear) { # only used for linear coordinate\n cli_abort(c(\n sprintf(\n \"Cannot add %s to %s\",\n object_name(self), layout_name\n ),\n i = sprintf(\n \"%s can only be used in linear layout\",\n object_name(self)\n )\n ))\n }\n ggproto_parent(CraftCross, self)$interact_layout(layout)\n },\n build_plot = function(self, plot, design, extra_design = NULL,\n previous_design = NULL) {\n if (is.null(.subset2(previous_design, \"nobs\"))) {\n cli_abort(\n sprintf(\n \"layout {.field nobs} for %s before %s is not initialized \",\n self$layout_name, object_name(self)\n )\n )\n }\n if (is.null(.subset2(design, \"nobs\"))) {\n cli_abort(\n sprintf(\n \"layout {.field nobs} for %s after %s is not initialized \",\n self$layout_name, object_name(self)\n )\n )\n }\n direction <- self$direction\n\n # parse links --------------------------------------------\n mark <- self$mark\n design1 <- previous_design\n design2 <- design\n full_data1 <- split(\n seq_len(.subset2(design1, \"nobs\")),\n .subset2(design1, \"panel\")\n )\n full_data2 <- split(\n seq_len(.subset2(design2, \"nobs\")),\n .subset2(design2, \"panel\")\n )\n link_index <- make_links_data(\n .subset2(mark, \"links\"),\n design1 = design1, design2 = design2,\n labels1 = self$labels0, labels2 = self$labels\n )\n if (vec_duplicate_any(nms <- names(link_index))) { # nolint\n cli_abort(\n c(\n \"panel names must be unique in {.arg mark}\",\n i = \"duplicated names: {.val {nms[vec_duplicate_detect(nms)]}}\"\n ),\n call = self$call\n )\n }\n data_index <- lapply(link_index, function(link) {\n if (is.null(link)) {\n return(NULL)\n }\n hand1 <- .subset2(link, \"hand1\")\n hand2 <- .subset2(link, \"hand2\")\n list(\n hand1 = .subset2(design1, \"index\")[hand1],\n hand2 = .subset2(design2, \"index\")[hand2]\n )\n })\n\n # prepare data for the plot\n plot_data <- lapply(data_index, function(index) {\n if (is.null(index)) {\n return(NULL)\n }\n hand1 <- .subset2(index, \"hand1\")\n hand2 <- .subset2(index, \"hand2\")\n hand <- switch_direction(\n direction,\n c(\"left\", \"right\"),\n c(\"top\", \"bottom\")\n )\n data_frame0(\n .hand = vec_rep_each(hand, c(length(hand1), length(hand2))),\n .names = vec_c(self$labels0[hand1], self$labels[hand2]),\n .index = vec_c(hand1, hand2)\n )\n })\n plot_data <- vec_rbind(!!!plot_data, .names_to = \".panel\")\n plot_data$.panel <- factor(plot_data$.panel, names(data_index))\n plot_data$.hand <- factor(plot_data$.hand, switch_direction(\n direction, c(\"left\", \"right\"), c(\"bottom\", \"top\")\n ))\n\n # prepare data for the plot ------------------------------\n plot <- gguse_data(plot, plot_data)\n\n # set up facets\n if (nlevels(plot_data$.panel) > 1L) {\n if (inherits(plot$facet, \"FacetGrid\")) {\n facet <- switch_direction(\n direction,\n ggplot2::facet_grid(\n rows = ggplot2::vars(.data$.panel),\n scales = \"free_y\", space = \"free\",\n drop = FALSE, as.table = FALSE\n ),\n ggplot2::facet_grid(\n cols = ggplot2::vars(.data$.panel),\n scales = \"free_x\", space = \"free\",\n drop = FALSE, as.table = FALSE\n )\n )\n } else {\n facet <- switch_direction(\n direction,\n ggplot2::facet_wrap(\n facets = ggplot2::vars(.data$.panel),\n ncol = 1L, as.table = FALSE\n ),\n ggplot2::facet_wrap(\n facets = ggplot2::vars(.data$.panel),\n nrow = 1L, as.table = FALSE\n )\n )\n }\n } else {\n facet <- facet_stack(direction, object_name(self))\n }\n # `free_row` and `free_column` have nothing with `facet_stack`\n # it's safe to use it directly\n plot <- ggmelt_facet(plot, facet, free_row = TRUE, free_column = TRUE)\n plot$ggalign_link_data <- list(\n full_data1 = full_data1,\n full_data2 = full_data2,\n link_index = link_index,\n data_index = data_index,\n direction = direction,\n draw = .subset2(mark, \"draw\"),\n obs_size = self$obs_size\n )\n add_class(plot, \"ggalign_mark_plot\", \"patch_ggplot\")\n },\n finish_plot = function(self, plot, schemes, theme) {\n plot <- plot_add_schemes(plot, schemes)\n\n # save spacing for usage\n spacing <- calc_element(\n switch_direction(\n self$direction,\n \"panel.spacing.y\",\n \"panel.spacing.x\"\n ),\n theme\n ) %||% unit(0, \"mm\")\n\n # save spacing for usage\n plot$ggalign_link_data$spacing1 <-\n plot$ggalign_link_data$spacing2 <- spacing\n\n plot + theme_recycle()\n },\n summary = function(self, plot) {\n header <- ggproto_parent(CraftCross, self)$summary(plot)\n c(header, \" Add plot to annotate observations\")\n }\n)\n\nmark_use_facet <- function(plot, facet) {\n\n}\n"], ["/ggalign/R/layout-heatmap-build.R", "#' @export\nquad_build.HeatmapLayout <- function(quad, schemes = NULL, theme = NULL,\n direction = NULL) {\n ans <- NextMethod()\n\n # add heatmap filling in the first layer --------------\n if (!is.null(filling <- quad@filling)) {\n # we always ensure the filling layer has a fill mapping\n if (is.null(.subset2(ans$plots$main$mapping, \"fill\"))) {\n mapping <- aes(.data$.x, .data$.y, fill = .data$value)\n } else {\n mapping <- aes(.data$.x, .data$.y)\n }\n if (is.waive(filling)) {\n if (nrow(quad@data) * ncol(quad@data) > 20000L) {\n cli_inform(c(\">\" = \"heatmap built with {.fn geom_raster}\"))\n filling <- \"raster\"\n } else {\n cli_inform(c(\">\" = \"heatmap built with {.fn geom_tile}\"))\n filling <- \"tile\"\n }\n }\n ans$plots$main <- ans$plots$main + layer_order(switch(filling,\n raster = ggplot2::geom_raster(mapping = mapping),\n tile = ggplot2::geom_tile(mapping = mapping)\n ))\n }\n # add class to set the default color mapping --------\n ans$plots$main <- add_class(ans$plots$main, \"ggalign_heatmap\")\n ans\n}\n\n#' @importFrom ggplot2 ggplot_build\n#' @export\nggplot_build.ggalign_heatmap <- function(plot, ...) {\n with_options(\n NextMethod(),\n ggplot2.discrete.fill = heatmap_fill(\"discrete\"),\n ggplot2.continuous.fill = heatmap_fill(\"continuous\")\n )\n}\n\nheatmap_fill <- function(type) {\n opt <- sprintf(\"%s.heatmap_%s_fill\", pkg_nm(), type)\n if (is.null(ans <- getOption(opt, default = NULL))) {\n if (type == \"continuous\") {\n ans <- function(...) {\n ggplot2::scale_fill_gradient2(low = \"blue\", high = \"red\")\n }\n } else {\n ans <- getOption(\"ggplot2.discrete.fill\")\n }\n }\n ans\n}\n"], ["/ggalign/R/genomic-helper.R", "#' Calculate inter-region distances for genomic rainfall plots\n#'\n#' This function computes distances between adjacent genomic regions, grouped by\n#' chromosome. Useful for visualizing clustering or dispersion of genomic\n#' features.\n#'\n#' @param region A data frame with at least 3 columns: chromosome, start, and\n#' end.\n#' @param mode How to assign distance for intermediate regions: one of `\"min\"`,\n#' `\"max\"`, `\"mean\"`, `\"left\"`, or `\"right\"`.\n#' @details\n#' The distance between two adjacent regions is calculated as the number of\n#' bases between the **end position of the upstream region** and the\n#' **start position of the downstream region**. If two regions overlap or are\n#' adjacent (≤1 bp apart), the distance is set to `0`. The resulting distance is\n#' assigned to each region according to the selected `mode`:\n#'\n#' - `\"left\"`: assign the distance to the upstream region\n#' - `\"right\"`: assign to the downstream region\n#' - `\"min\"` / `\"max\"` / `\"mean\"`: for intermediate regions, calculate the\n#' minimum, maximum, or average of the distances to neighboring regions\n#'\n#' @return A data frame with an additional `dist` column.\n#' @export\ngenomic_dist <- function(region, mode = NULL) {\n # Check input validity\n if (is.null(mode)) {\n mode <- \"min\"\n } else {\n mode <- arg_match0(mode, c(\"min\", \"max\", \"mean\", \"left\", \"right\"))\n }\n if (!is.data.frame(region) || ncol(region) < 3L) {\n cli_abort(\"{.arg region} must have at least 3 columns: chromosome, start, and end\")\n }\n if (anyNA(region[[1L]]) || anyNA(region[[2L]]) || anyNA(region[[3L]])) {\n cli_abort(\"Columns 1, 2, and 3 of {.arg region} must not contain missing values\")\n }\n if (!is.numeric(region[[2L]]) || !is.numeric(region[[3L]])) {\n cli_abort(\"Columns 2 and 3 of {.arg region} must be numeric (start and end positions)\")\n }\n if (any(region[[2L]] > region[[3L]])) {\n cli_abort(\"Column 2 (start) must not be greater than column 3 (end) in any row of {.arg region}\")\n }\n\n # Split the region data frame by chromosome (first column)\n groups <- vec_split(region, .subset2(region, 1L))\n dist_list <- lapply(.subset2(groups, \"val\"), function(d) {\n n <- nrow(d)\n if (n < 2L) {\n d$dist <- NA_real_\n return(d)\n }\n\n # Sort regions by start, then end positions\n ordering <- order(.subset2(d, 2L), .subset2(d, 3L))\n\n # Compute distances between adjacent regions\n dists <- vapply(seq_len(n - 1L), function(i) {\n first <- vec_slice(d, ordering[i])\n second <- vec_slice(d, ordering[i + 1])\n out <- .subset2(second, 2L) - .subset2(first, 3L)\n # If overlapping or adjacent (≤1 bp), treat distance as 0\n if (out <= 1L) out <- 0L else out <- as.integer(out)\n out\n }, integer(1L), USE.NAMES = FALSE)\n\n # If only two regions, just repeat the distance\n if (n == 2L) {\n d$dist <- rep_len(dists, n)\n return(d)\n }\n\n # For intermediate regions (not first or last), choose how to assign\n # distance\n d1 <- dists[seq_len(n - 2L)]\n d2 <- dists[2:(n - 1L)]\n if (mode == \"min\") {\n body_dists <- pmin(d1, d2)\n } else if (mode == \"max\") {\n body_dists <- pmax(d1, d2)\n } else if (mode == \"mean\") {\n body_dists <- (d1 + d2) / 2L\n } else if (mode == \"left\") {\n body_dists <- d1\n } else if (mode == \"right\") {\n body_dists <- d2\n }\n\n # Combine distances: head, body, and tail\n d$dist <- c(dists[1L], body_dists, dists[n - 1L])[order(ordering)]\n d\n })\n vec_rbind(!!!dist_list)\n}\n\n#' Calculate Genomic Region Density\n#'\n#' Computes the density or count of genomic regions in sliding or fixed windows\n#' across the genome. The density can be reported as the percentage of uncovered\n#' bases or the number of overlapping regions within each window.\n#'\n#' This function splits the input by chromosome and tiles the genomic space\n#' into windows, optionally overlapping. For each window, it calculates:\n#'\n#' - the number of regions that overlap it (if `mode = \"count\"`), or\n#' - the fraction of bases covered by any region (if `mode = \"percent\"`).\n#'\n#' @param region A data frame with at least 3 columns: chromosome, start, and\n#' end.\n#' - Column 1: character or factor, chromosome name.\n#' - Column 2: numeric, start position (must be ≤ end).\n#' - Column 3: numeric, end position.\n#' @param window_size Numeric, the width of each window (default is `1e+07`).\n#' Ignored if `n_window` is specified.\n#' @param n_window Integer, the number of windows per chromosome. If provided,\n#' overrides `window_size` and evenly splits the chromosome into `n_window`\n#' (non-overlapping) or `2*n_window - 1` (overlapping) windows.\n#' @param overlap Logical, whether to use overlapping windows (default `TRUE`).\n#' Overlapping windows are spaced by half the window size.\n#' @param mode Character, either `\"coverage\"` or `\"count\"`:\n#' - `\"count\"`: reports the number of regions overlapping each window.\n#' - `\"coverage\"`: reports the fraction of each window covered by regions.\n#' @param seqlengths Optional named vector of chromosome lengths. If missing,\n#' the maximum `end` value in the input is used as the chromosome length.\n#'\n#' @return A data frame with columns:\n#' - `seqnames`: The sequence (e.g., chromosome) names.\n#' - `start`: start of each window\n#' - `end`: end of each window\n#' - `density`: the region count or covered percent, depending on `mode`\n#'\n#' @examples\n#' region <- data.frame(\n#' chr = rep(\"chr1\", 3),\n#' start = c(100, 5000000, 15000000),\n#' end = c(2000000, 7000000, 17000000)\n#' )\n#' genomic_density(region, window_size = 1e7, mode = \"count\")\n#' genomic_density(region, n_window = 3, overlap = FALSE, mode = \"coverage\")\n#'\n#' @export\ngenomic_density <- function(region, window_size = 1e+07, n_window = NULL,\n overlap = TRUE, mode = c(\"coverage\", \"count\"),\n seqlengths = NULL) {\n # Check input validity\n assert_number_whole(window_size, allow_null = TRUE, min = 1)\n assert_number_whole(n_window, allow_null = TRUE, min = 1)\n if (is.null(window_size) && is.null(n_window)) {\n cli_abort(c(\n \"Both {.arg window_size} and {.arg n_window} are {.val NULL}.\",\n \"i\" = \"You must supply at least one of these arguments to define the binning strategy.\"\n ))\n }\n assert_bool(overlap)\n if (is.null(mode)) {\n mode <- \"coverage\"\n } else {\n mode <- arg_match0(mode, c(\"coverage\", \"count\"))\n }\n if (!is.data.frame(region) || ncol(region) < 3L) {\n cli_abort(\"{.arg region} must have at least 3 columns: chromosome, start, and end\")\n }\n if (anyNA(region[[1L]]) || anyNA(region[[2L]]) || anyNA(region[[3L]])) {\n cli_abort(\"Columns 1, 2, and 3 of {.arg region} must not contain missing values\")\n }\n if (!is.numeric(region[[2L]]) || !is.numeric(region[[3L]])) {\n cli_abort(\"Columns 2 and 3 of {.arg region} must be numeric (start and end positions)\")\n }\n if (any(region[[2L]] > region[[3L]])) {\n cli_abort(\"Column 2 (start) must not be greater than column 3 (end) in any row of {.arg region}\")\n }\n\n # Split the region data frame by chromosome (first column)\n groups <- vec_split(region, .subset2(region, 1L))\n density_list <- lapply(.subset2(groups, \"val\"), function(d) {\n chr <- .subset2(d, 1L)[1L]\n if (is.null(seqlengths)) {\n max_pos <- max(.subset2(region, 3L))\n } else {\n max_pos <- seqlengths[chr]\n if (is.na(max_pos)) {\n cli_abort(\"Chromosome {.val {chr}} is not found in {.arg seqlengths}. Please check that all chromosomes in {.arg region} have corresponding sequence lengths.\")\n }\n }\n if (overlap) {\n if (is.null(n_window)) {\n # Half-step sliding windows: start at 1, step = half window size\n b <- seq(0L, max_pos, by = window_size %/% 2L)\n s <- b[-length(b)]\n s <- s[-length(s)] + 1L\n e <- s + window_size - 1L\n } else {\n b <- seq(0L, max_pos, length.out = 2L * n_window + 1L)\n s <- b[-length(b)]\n s <- s[-length(s)] + 1L\n e <- s + b[3L] - b[1L] - 1L\n }\n } else {\n if (is.null(n_window)) {\n b <- seq(0L, max_pos, by = window_size)\n s <- b[-length(b)] + 1L\n e <- s + window_size - 1L\n } else {\n b <- seq(0, max_pos, length.out = n_window + 1L)\n s <- b[-length(b)] + 1L\n e <- s + b[2L] - b[1L]\n }\n }\n s <- as.integer(s)\n e <- as.integer(e)\n region_s <- .subset2(d, 2L)\n region_e <- .subset2(d, 3L)\n if (mode == \"count\") {\n # For each window, count how many regions overlap with it\n density <- vapply(seq_along(s), function(i) {\n si <- s[i]\n ei <- e[i]\n sum(!(region_s > ei | region_e < si))\n }, integer(1L), USE.NAMES = FALSE)\n } else {\n region_s <- as.integer(ceiling(region_s))\n region_e <- as.integer(floor(region_e))\n # For each window, calculate the proportion of bases covered by\n # regions\n density <- vapply(seq_along(s), function(i) {\n si <- s[i]\n ei <- e[i]\n # Keep regions that overlap with current window\n keep <- !(region_s > ei | region_e < si)\n\n # Clip regions to fit within the current window\n region_s_used <- pmax(region_s[keep], si)\n region_e_used <- pmin(region_e[keep], ei)\n\n # If no overlapping region, coverage is zero\n if (length(region_s_used) == 0L) {\n return(0)\n }\n\n # Sort intervals by start, then end\n ordering <- order(region_s_used, region_e_used)\n region_s_used <- region_s_used[ordering]\n region_e_used <- region_e_used[ordering]\n\n # Initialize with the first interval\n start <- region_s_used[1L]\n end <- region_e_used[1L]\n\n # If there's only one interval, just compute its coverage\n if (length(region_s_used) == 1L) {\n cov <- end - start + 1L\n return(cov / (ei - si + 1L))\n }\n # Merge overlapping/adjacent intervals and compute total\n # coverage\n cov <- 0L\n for (j in 2:length(region_s_used)) {\n if (region_s_used[j] - end <= 1L) {\n end <- max(end, region_e_used[j])\n } else {\n cov <- cov + (end - start + 1L)\n start <- region_s_used[j]\n end <- region_e_used[j]\n }\n }\n cov <- cov + (end - start + 1L)\n cov / (ei - si + 1L)\n }, numeric(1L), USE.NAMES = FALSE)\n }\n data_frame0(seqnames = chr, start = s, end = e, density = density)\n })\n vec_rbind(!!!density_list)\n}\n"], ["/ggalign/R/craft-align-order2.R", "#' Reorders layout observations based on specific statistics.\n#'\n#' @details\n#' `r lifecycle::badge('experimental')`\n#'\n#' The `align_order2()` function differs from `align_order()` in that the\n#' `weights` argument in `align_order()` must return atomic weights for each\n#' observation. In contrast, the `stat` argument in `align_order2()` can\n#' return more complex structures, such as [hclust][stats::hclust] or\n#' [dendrogram][stats::as.dendrogram], among others.\n#'\n#' Typically, you can achieve the functionality of `align_order2()` using\n#' `align_order()` by manually extracting the ordering information from\n#' the statistic.\n#'\n#' @param stat A statistical function which accepts a data and returns the\n#' statistic, which we'll call [`order2()`] to extract the ordering information.\n#' @param ... <[dyn-dots][rlang::dyn-dots]> Additional arguments passed to\n#' function provided in `stat` argument.\n#' @param data A `matrix`, `data frame`, or atomic vector used as the input for\n#' the `stat` function. Alternatively, you can specify a `function` (including\n#' purrr-like lambda syntax) that will be applied to the layout matrix,\n#' transforming it as necessary for statistic calculations. By default, it will\n#' inherit from the layout matrix.\n#' @inheritParams align_order\n#' @inheritSection align Discrete Axis Alignment\n#' @examples\n#' ggheatmap(matrix(rnorm(81), nrow = 9)) +\n#' anno_left() +\n#' align_order2(hclust2)\n#' @seealso [order2()]\n#' @importFrom ggplot2 waiver\n#' @importFrom rlang list2\n#' @export\nalign_order2 <- function(stat, ..., reverse = FALSE,\n strict = TRUE, data = NULL,\n active = NULL) {\n stat <- rlang::as_function(stat)\n assert_bool(strict)\n assert_bool(reverse)\n assert_active(active)\n active <- update_active(active, new_active(use = FALSE))\n align(\n align = AlignOrder2,\n stat = stat,\n params = list2(...),\n reverse = reverse,\n strict = strict,\n active = active,\n data = data\n )\n}\n\n#' @importFrom ggplot2 ggproto\n#' @importFrom rlang inject\nAlignOrder2 <- ggproto(\"AlignOrder2\", CraftAlign,\n interact_layout = function(self, layout) {\n layout <- ggproto_parent(CraftAlign, self)$interact_layout(layout)\n layout_data <- layout@data\n if (is.null(input_data <- self$input_data) ||\n is.waive(input_data)) { # inherit from the layout\n if (is.null(data <- layout_data)) {\n cli_abort(c(\n sprintf(\n \"you must provide {.arg data} in %s\",\n object_name(self)\n ),\n i = sprintf(\"no data was found in %s\", self$layout_name)\n ))\n }\n } else if (is.function(input_data)) {\n if (is.null(layout_data)) {\n cli_abort(c(\n sprintf(\n \"{.arg data} in %s cannot be a function\",\n object_name(self)\n ),\n i = sprintf(\"no data was found in %s\", self$layout_name)\n ))\n }\n data <- input_data(layout_data)\n } else {\n data <- input_data\n }\n\n design <- layout@design\n layout_nobs <- .subset2(design, \"nobs\")\n\n # we always regard rows as the observations\n if (is.null(layout_nobs)) {\n layout_nobs <- vec_size(data)\n if (layout_nobs == 0L) {\n cli_abort(\"{.arg data} cannot be empty\", call = self$call)\n }\n design[\"nobs\"] <- list(layout_nobs)\n layout@design <- design\n } else if (vec_size(data) != layout_nobs) {\n cli_abort(sprintf(\n \"%s (nobs: %d) is not compatible with the %s (nobs: %d)\",\n object_name, vec_size(data), layout_name, layout_nobs\n ))\n }\n\n # save the labels\n self$labels <- vec_names(data) %||% vec_names(layout_data)\n self$data <- ggalign_data_restore(data, layout_data)\n layout\n },\n compute = function(self, panel, index) {\n inject(self$stat(self$data, !!!self$params))\n },\n align = function(self, panel, index) {\n index <- vec_cast(\n order2(self$statistics), integer(),\n x_arg = \"stat\", call = self$call\n )\n assert_mismatch_nobs(\n self, vec_size(self$data), vec_size(index),\n arg = \"stat\"\n )\n if (self$reverse) index <- rev(index)\n assert_reorder(self, panel, index, self$strict)\n list(panel, index)\n },\n summary_align = function(self) c(TRUE, FALSE)\n)\n\n#' Ordering Permutation\n#'\n#' `order2` returns a permutation which rearranges its first argument into\n#' ascending order.\n#' @param x Any objects can be extracting ordering.\n#' @return An integer vector unless any of the inputs has `2^31` or more\n#' elements, when it is a double vector.\n#' @examples\n#' order2(hclust2(matrix(rnorm(100L), nrow = 10L)))\n#' @export\norder2 <- function(x) UseMethod(\"order2\")\n\n#' @export\n#' @rdname order2\norder2.hclust <- function(x) x$order\n\n#' @importFrom stats order.dendrogram\n#' @export\n#' @rdname order2\norder2.dendrogram <- function(x) order.dendrogram(x)\n\n#' @export\n#' @rdname order2\norder2.ser_permutation_vector <- function(x) {\n rlang::check_installed(\n \"seriation\", \"to extract order from `ser_permutation_vector`\"\n )\n getExportedValue(\"seriation\", \"get_order\")(x)\n}\n\n#' @export\n#' @rdname order2\norder2.ser_permutation <- function(x) {\n rlang::check_installed(\n \"seriation\", \"to extract order from `ser_permutation`\"\n )\n getExportedValue(\"seriation\", \"get_order\")(x)\n}\n\n#' @export\n#' @rdname order2\norder2.phylo <- function(x) {\n second <- x$edge[, 2L, drop = TRUE]\n second[second <= length(x$tip.label)]\n}\n"], ["/ggalign/R/scheme-.R", "new_schemes <- function(...) {\n default <- list(\n new_scheme_data(),\n new_scheme_align(),\n new_scheme_theme()\n )\n names(default) <- vapply(default, ggalign_scheme_name,\n character(1L),\n USE.NAMES = FALSE\n )\n for (i in seq_len(...length())) {\n scheme <- ...elt(i)\n default[[ggalign_scheme_name(scheme)]] <- scheme\n }\n default\n}\n\nnew_scheme <- function(name, data, ..., class = character()) {\n structure(data,\n `__ggalign.scheme_name__` = name, ...,\n class = c(class, \"ggalign_scheme\")\n )\n}\n\nggalign_scheme_name <- function(x) {\n attr(x, \"__ggalign.scheme_name__\", exact = TRUE)\n}\n\n#' @importFrom ggplot2 theme\ndefault_schemes <- function(data = NULL, th = theme()) {\n if (!is.waive(data)) data <- NULL\n new_schemes(\n new_scheme_data(data),\n new_scheme_theme(th)\n )\n}\n\n###############################################################\n#' Used to update global data\n#' @noRd\nupdate_scheme <- function(new, old, object_name) {\n UseMethod(\"update_scheme\", old)\n}\n\n#' @export\nupdate_scheme.default <- function(new, old, object_name) new\n\nupdate_layout_scheme <- function(object, layout, object_name) {\n name <- ggalign_scheme_name(object)\n layout@schemes[name] <- list(update_scheme(\n object, .subset2(layout@schemes, name), object_name\n ))\n layout\n}\n\n###############################################################\ninherit_scheme <- function(scheme, pscheme) {\n UseMethod(\"inherit_scheme\", pscheme)\n}\n\n# If no parent scheme, use child scheme directly\n#' @export\ninherit_scheme.NULL <- function(scheme, pscheme) scheme\n\ninherit_schemes <- function(schemes, pschemes) {\n nms <- vapply(pschemes,\n ggalign_scheme_name, character(1L),\n USE.NAMES = FALSE\n )\n ans <- lapply(nms, function(opt) {\n inherit_scheme(.subset2(schemes, opt), .subset2(pschemes, opt))\n })\n names(ans) <- nms\n ans\n}\n\n###############################################################\nplot_add_scheme <- function(plot, scheme) UseMethod(\"plot_add_scheme\", scheme)\n\n#' @export\nplot_add_scheme.NULL <- function(plot, scheme) plot\n\nplot_add_schemes <- function(plot, schemes) {\n for (i in seq_along(schemes)) {\n plot <- plot_add_scheme(plot, scheme = .subset2(schemes, i))\n }\n plot\n}\n"], ["/ggalign/R/grid-grob-channel.R", "#' Create a Grob That Spans Multiple Viewports\n#'\n#' This function initializes a communication channel to share location signals\n#' across different viewports. It returns a `channelSenderGrob` object, which\n#' can transmit multiple signals using its `$signal` method (see the \"Signal\"\n#' section below for details). When drawn, all collected signals are passed to\n#' the `make_content` function to generate the final [`grob`][grid::grob].\n#'\n#' @param make_content A function that accepts the list of signal locations and\n#' returns a [`grob`][grid::grob].\n#' @param ... Additional arguments passed to `make_content`.\n#' @inheritParams grid::grob\n#'\n#' @section Signal:\n#' A `channelSenderGrob` can emit multiple location signals using the `$signal`\n#' method. This method accepts the following arguments:\n#'\n#' - `x`: X-coordinate.\n#' - `y`: Y-coordinate.\n#' - `default.units`: The default units for `x` and `y`.\n#' - `tag`: A character string used to identify the location.\n#' - `name`: A name for the returned grob.\n#' - `vp`: A [`viewport`][grid::viewport] for the returned grob.\n#'\n#' The `$signal` method returns a `channelSignalGrob`.\n#'\n#' @return A `channelSenderGrob` object.\n#' @examples\n#' # we create a new channel, we will emit two singals\n#' # here: we just add a line between the two signals\n#' channel <- channelGrob(function(locations) {\n#' # you can also use `tag` to identify the locations\n#' loc1 <- .subset2(locations, 1L)\n#' loc2 <- .subset2(locations, 2L)\n#' grid::segmentsGrob(loc1$x, loc1$y, loc2$x, loc2$y)\n#' })\n#'\n#' gt <- gtable::gtable(unit(1:2, c(\"cm\")), unit(5, \"cm\"))\n#' gt <- gtable::gtable_add_grob(\n#' gt,\n#' list(\n#' grid::rectGrob(gp = gpar(color = \"black\", fill = NA)),\n#' channel$signal(0.5, 0.5, \"npc\")\n#' ),\n#' t = 1, l = 1, name = c(\"rect1\", \"signal1\")\n#' )\n#' gt <- gtable::gtable_add_grob(\n#' gt,\n#' list(\n#' grid::rectGrob(gp = gpar(color = \"red\", fill = NA)),\n#' channel$signal(0.5, 0.5, \"npc\")\n#' ),\n#' t = 1, l = 2, name = c(\"rect2\", \"signal2\")\n#' )\n#' grid::grid.newpage()\n#' grid::grid.draw(gt)\n#' @importFrom grid unit is.unit grob\n#' @importFrom rlang list2\n#' @export\nchannelGrob <- function(make_content, ..., name = NULL, vp = NULL) {\n make_content <- allow_lambda(make_content)\n if (!is.function(make_content)) {\n cli_abort(\"{.arg make_content} must be a function\")\n }\n # Used to communicate between different signals\n channel <- new.env(parent = emptyenv())\n channel$make_content <- make_content\n channel$dots <- list2(...)\n channel$n <- 0L # total number of signals\n grob(\n channel = channel,\n name = name,\n vp = vp,\n\n # method used to release signal and retutn a new grob\n signal = function(self, x, y, default.units = \"native\",\n tag = NULL, name = NULL, vp = NULL) {\n if (!is.unit(x)) x <- unit(x, default.units)\n if (!is.unit(y)) y <- unit(y, default.units)\n if (length(x) != length(y)) {\n cli_abort(\"{.arg x} and {.arg y} must have the same length\")\n }\n assert_string(tag, allow_empty = FALSE, allow_null = TRUE)\n signal <- list(list(x = x, y = y))\n if (!is.null(tag)) names(signal) <- tag\n channel <- .subset2(self, \"channel\")\n channel$signals <- c(channel$signals, signal)\n i <- channel$n <- channel$n + 1L\n grob(\n channel = channel,\n i = i,\n name = name,\n vp = vp,\n cl = c(\"channelSignalGrob\", \"channelGrob\")\n )\n },\n # Grob used to send signals\n cl = c(\"channelSenderGrob\", \"channelGrob\")\n )\n}\n\n#' @export\n`$.channelGrob` <- function(self, name) {\n field <- .subset2(self, name)\n if (!is.function(field)) {\n return(field)\n }\n args <- formals(field)\n # is.null is a fast path for a common case; the %in% check is slower but\n # also catches the case where there's a `self = NULL` argument.\n has_self <- !is.null(args[[\"self\"]]) || \"self\" %in% names(args)\n\n # We assign the method with its correct name and construct a call to it to\n # make errors reported as coming from the method name rather than `field()`\n assign(name, field, envir = environment())\n args <- list(quote(...))\n if (has_self) {\n args$self <- quote(self)\n }\n rlang::new_function(alist(... = ), rlang::call2(name, !!!args))\n}\n\n#' @export\n`[[.channelGrob` <- `$.channelGrob`\n\n# https://www.stat.auckland.ac.nz/~paul/Reports/CustomGrobs/custom-grob.html\n# preDraw:\n# - makeContext\n# - pushvpgp\n# - preDrawDetails: by default, do noting\n# makeContent:\n# drawDetails:\n# postDraw:\n# - postDrawDetails: by default, do noting\n# - popgrobvp\n#' @importFrom grid makeContent drawDetails viewport is.grob gTree grob\n#' @export\nmakeContent.channelGrob <- function(x) {\n channel <- .subset2(x, \"channel\")\n # If no signals, do nothing\n if (channel$n == 0L) return(x) # styler: off\n\n if (inherits(x, \"channelSenderGrob\")) {\n # we use the viewport from the signals sender\n channel$vp <- grid::current.viewport()\n } else if (inherits(x, \"channelSignalGrob\")) {\n if (is.null(channel$locations)) {\n channel$locations <- vector(\"list\", channel$n)\n names(channel$locations) <- names(channel$signals)\n }\n\n # convert the viewport coordinates to the device coordinates\n i <- .subset2(x, \"i\")\n signal <- .subset2(channel$signals, i)\n channel$locations[[i]] <- grid::deviceLoc(signal$x, signal$y)\n if (all(!vapply(channel$locations, is.null, logical(1L), # styler: off\n USE.NAMES = FALSE))) { # styler: off\n # When all locations have been prepared\n # we output the grob with all device locations\n x <- grob(\n channel = channel,\n vp = .subset2(x, \"vp\"), # Don't change the viewport\n cl = c(\"channelReceiverGrob\", \"channelGrob\")\n )\n }\n }\n x\n}\n\n#' @export\ndrawDetails.channelGrob <- function(x, recording) {\n}\n\n#' @importFrom grid grid.draw viewport gTree is.grob\n#' @export\ndrawDetails.channelReceiverGrob <- function(x, recording) {\n # we always reset the locations after drawing\n old <- grid::current.viewport()$name\n on.exit(grid::seekViewport(old), add = TRUE)\n channel <- .subset2(x, \"channel\")\n locations <- channel$locations\n on.exit(channel$locations <- NULL, add = TRUE)\n if (!is.null(vp <- channel$vp)) {\n grid::seekViewport(vp$name)\n # convert the device cooridnates into the drawing viewport coordinates\n trans <- solve(grid::current.transform())\n locations <- lapply(locations, grid_solve_loc, trans = trans)\n } else { # If no viewport, we use the `ROOT` viewport\n grid::upViewport(0)\n grid::pushViewport(viewport())\n }\n grob <- rlang::inject(channel$make_content(locations, !!!channel$dots))\n if (is.gList(grob)) grob <- gTree(children = grob)\n if (is.grob(grob)) grid.draw(grob, recording = recording)\n}\n"], ["/ggalign/R/ggplot-geom-subrect.R", "#' Subdivide Rectangles\n#'\n#' @description\n#' These geoms subdivide rectangles with shared borders into a grid. Both geoms\n#' achieve the same result but differ in how the rectangles are parameterized:\n#' - **`geom_subrect()`**: Defines rectangles using their four corners (`xmin`,\n#' `xmax`, `ymin`, `ymax`).\n#' - **`geom_subtile()`**: Defines rectangles using the center (`x`, `y`) and\n#' dimensions (`width`, `height`).\n#'\n#' @param byrow A single boolean value indicates whether we should arrange the\n#' divided rectangles in the row-major order.\n#' @param nrow,ncol A single positive integer specifying the number of rows or\n#' columns in the layout of the subdivided cell. By default, the layout\n#' dimensions are determined automatically using logic similar to\n#' [`facet_wrap()`][ggplot2::facet_wrap].\n#' @param direction `r lifecycle::badge(\"deprecated\")` A string specifying the\n#' arrangement direction:\n#' - `\"h\"`(`horizontal`): Creates a single row (one-row layout).\n#' - `\"v\"`(`vertical`): Creates a single column (one-column layout).\n#' @inheritParams ggplot2::geom_rect\n#' @inheritParams ggplot2::geom_segment\n#' @aesthetics GeomSubrect\n#' @examples\n#' # arranges by row\n#' ggplot(data.frame(value = letters[seq_len(5)])) +\n#' geom_subtile(aes(x = 1, y = 1, fill = value), byrow = TRUE)\n#'\n#' # arranges by column\n#' ggplot(data.frame(value = letters[seq_len(9)])) +\n#' geom_subtile(aes(x = 1, y = 1, fill = value))\n#'\n#' # one-row\n#' ggplot(data.frame(value = letters[seq_len(4)])) +\n#' geom_subtile(aes(x = 1, y = 1, fill = value), nrow = 1)\n#'\n#' # one-column\n#' ggplot(data.frame(value = letters[seq_len(4)])) +\n#' geom_subtile(aes(x = 1, y = 1, fill = value), ncol = 1)\n#'\n#' @importFrom rlang list2\n#' @export\ngeom_subrect <- function(mapping = NULL, data = NULL,\n stat = \"identity\", position = \"identity\",\n ...,\n byrow = FALSE, nrow = NULL, ncol = NULL,\n lineend = \"butt\", linejoin = \"mitre\",\n na.rm = FALSE, show.legend = NA, inherit.aes = TRUE,\n direction = deprecated()) {\n assert_bool(byrow)\n assert_number_whole(nrow, min = 1, allow_null = TRUE)\n assert_number_whole(ncol, min = 1, allow_null = TRUE)\n if (lifecycle::is_present(direction)) {\n lifecycle::deprecate_warn(\n \"1.0.2\",\n \"geom_subtile(direction = )\",\n details = \"Please use the `nrow`/`ncol` argument instead.\"\n )\n if (is_horizontal(direction)) {\n nrow <- 1L\n ncol <- NULL\n } else {\n nrow <- NULL\n ncol <- 1L\n }\n }\n ggplot2::layer(\n data = data,\n mapping = mapping,\n stat = stat,\n geom = GeomSubrect,\n position = position,\n show.legend = show.legend,\n inherit.aes = inherit.aes,\n params = list2(\n byrow = byrow,\n nrow = nrow,\n ncol = ncol,\n lineend = lineend,\n linejoin = linejoin,\n na.rm = na.rm,\n ...\n )\n )\n}\n\n#' @importFrom ggplot2 ggproto ggproto_parent wrap_dims\nGeomSubrect <- ggproto(\n \"GeomSubrect\",\n ggplot2::GeomRect,\n extra_params = c(ggplot2::GeomRect$extra_params, \"byrow\", \"nrow\", \"ncol\"),\n setup_data = function(self, data, params) {\n data <- ggproto_parent(ggplot2::GeomRect, self)$setup_data(data, params)\n indices <- vec_group_loc(data[c(\"xmin\", \"xmax\", \"ymin\", \"ymax\")])\n data_list <- vec_chop(data, indices = .subset2(indices, \"loc\"))\n max_n_tiles <- max(list_sizes(data_list))\n if (max_n_tiles == 1L) return(data) # styler: off\n cli_inform(paste(\n \"{.fn {snake_class(self)}} subdivide tile into a maximal\",\n \"of {max_n_tiles} rectangles\"\n ))\n nrow <- .subset2(params, \"nrow\")\n ncol <- .subset2(params, \"ncol\")\n vec_rbind(!!!lapply(data_list, function(data) {\n n <- vec_size(data)\n if (n == 1L) return(data) # styler: off\n dims <- wrap_dims(n, nrow = nrow, ncol = ncol)\n n_rows <- dims[1L]\n n_cols <- dims[2L]\n one_row <- vec_slice(data, 1L)\n width <- (one_row$xmax - one_row$xmin) / n_cols\n height <- (one_row$ymax - one_row$ymin) / n_rows\n\n if (.subset2(params, \"byrow\")) {\n # we arrange the rectangles from from left to\n # right, then from top to bottom\n data$xmin <- data$xmin +\n vec_rep(width * (seq_len(n_cols) - 1L), n_rows)[\n seq_len(n)\n ]\n data$xmax <- data$xmax -\n vec_rep(width * rev(seq_len(n_cols) - 1L), n_rows)[\n seq_len(n)\n ]\n\n data$ymin <- data$ymin +\n vec_rep_each(height * rev(seq_len(n_rows) - 1L), n_cols)[\n seq_len(n)\n ]\n data$ymax <- data$ymax -\n vec_rep_each(height * (seq_len(n_rows) - 1L), n_cols)[\n seq_len(n)\n ]\n } else {\n # we arrange the rectangles from top to bottom,\n # then from left to right\n data$xmin <- data$xmin +\n vec_rep_each(width * (seq_len(n_cols) - 1L), n_rows)[\n seq_len(n)\n ]\n data$xmax <- data$xmax -\n vec_rep_each(width * rev(seq_len(n_cols) - 1L), n_rows)[\n seq_len(n)\n ]\n\n data$ymin <- data$ymin +\n vec_rep(height * rev(seq_len(n_rows) - 1L), n_cols)[\n seq_len(n)\n ]\n data$ymax <- data$ymax -\n vec_rep(height * (seq_len(n_rows) - 1L), n_cols)[\n seq_len(n)\n ]\n }\n\n data\n }))\n }\n)\n\n#' @aesthetics GeomSubtile\n#' @importFrom rlang list2\n#' @export\n#' @rdname geom_subrect\ngeom_subtile <- function(mapping = NULL, data = NULL,\n stat = \"identity\", position = \"identity\",\n ...,\n byrow = TRUE, nrow = NULL, ncol = NULL,\n lineend = \"butt\", linejoin = \"mitre\",\n na.rm = FALSE, show.legend = NA, inherit.aes = TRUE,\n direction = deprecated()) {\n assert_bool(byrow)\n assert_number_whole(nrow, min = 1, allow_null = TRUE)\n assert_number_whole(ncol, min = 1, allow_null = TRUE)\n if (lifecycle::is_present(direction)) {\n lifecycle::deprecate_warn(\n \"1.0.2\",\n \"geom_subtile(direction = )\",\n details = \"Please use the `nrow`/`ncol` argument instead.\"\n )\n if (is_horizontal(direction)) {\n nrow <- 1L\n ncol <- NULL\n } else {\n nrow <- NULL\n ncol <- 1L\n }\n }\n ggplot2::layer(\n data = data,\n mapping = mapping,\n stat = stat,\n geom = GeomSubtile,\n position = position,\n show.legend = show.legend,\n inherit.aes = inherit.aes,\n params = list2(\n byrow = byrow,\n nrow = nrow,\n ncol = ncol,\n lineend = lineend,\n linejoin = linejoin,\n na.rm = na.rm,\n ...\n )\n )\n}\n\n#' @importFrom ggplot2 ggproto ggproto_parent\nGeomSubtile <- ggproto(\n \"GeomSubtile\",\n ggplot2::GeomTile,\n extra_params = c(ggplot2::GeomRect$extra_params, \"byrow\", \"nrow\", \"ncol\"),\n setup_data = function(self, data, params) {\n data <- ggproto_parent(ggplot2::GeomTile, self)$setup_data(data, params)\n ggproto_parent(GeomSubrect, self)$setup_data(data, params)\n }\n)\n"], ["/ggalign/R/layout-chain-stack-composer.R", "#' @keywords internal\nstack_composer <- function(direction) {\n structure(\n list(\n t = integer(), l = integer(),\n b = integer(), r = integer(),\n plots = list(), sizes = list(),\n direction = direction,\n align = 1L,\n # attributes used by `stack_layout()`\n left_or_top = FALSE, right_or_bottom = FALSE\n ),\n class = \"stack_composer\"\n )\n}\n\nstack_composer_add_plot <- function(composer, plot, t, l, b = t, r = l) {\n composer$t <- c(.subset2(composer, \"t\"), t)\n composer$l <- c(.subset2(composer, \"l\"), l)\n composer$b <- c(.subset2(composer, \"b\"), b)\n composer$r <- c(.subset2(composer, \"r\"), r)\n composer$plots <- c(.subset2(composer, \"plots\"), list(plot))\n composer\n}\n\n#' @importFrom rlang is_empty\nstack_composer_align_plot <- function(composer, plot, size) {\n if (is.null(plot)) {\n return(composer)\n }\n if (is_horizontal(.subset2(composer, \"direction\"))) {\n r_border <- .subset2(composer, \"r\")\n if (is_empty(r_border)) {\n l <- 1L\n } else {\n l <- max(r_border) + 1L\n }\n t <- .subset2(composer, \"align\")\n } else {\n b_border <- .subset2(composer, \"b\")\n if (is_empty(b_border)) {\n t <- 1L\n } else {\n t <- max(b_border) + 1L\n }\n l <- .subset2(composer, \"align\")\n }\n composer$sizes <- c(.subset2(composer, \"sizes\"), list(size))\n stack_composer_add_plot(composer, plot, t, l)\n}\n\nstack_composer_add <- function(plot, stack, composer, ...) {\n UseMethod(\"stack_composer_add\")\n}\n\n#' @importFrom utils packageVersion\n#' @export\nstack_composer_add.CraftBox <- function(plot, stack, composer, design, ...,\n schemes, theme,\n released_spaces,\n direction, position) {\n size <- plot@size\n\n # for `released_spaces`, release the `free_spaces` in a single plot\n plot_schemes <- inherit_schemes(plot@schemes, schemes)\n if (!is.null(released_spaces)) {\n plot_spaces <- .subset2(\n .subset2(plot_schemes, \"scheme_align\"), \"free_spaces\"\n )\n if (is_string(plot_spaces)) {\n plot_spaces <- setdiff_position(plot_spaces, released_spaces)\n if (!nzchar(plot_spaces)) plot_spaces <- NULL\n plot_schemes$scheme_align[\"free_spaces\"] <- list(plot_spaces)\n }\n }\n\n # let `Align` to determine how to build the plot\n craftsman <- plot@craftsman # `Craftsman` object\n plot <- plot@plot\n if (!craftsman$free_facet && is_discrete_design(design)) {\n if (nlevels(.subset2(design, \"panel\")) > 1L) {\n if (is_horizontal(direction)) {\n facet <- ggplot2::facet_grid(\n rows = ggplot2::vars(.data$.panel),\n scales = \"free_y\", space = \"free\",\n drop = FALSE, as.table = FALSE\n )\n free_row <- FALSE\n free_column <- TRUE\n } else {\n facet <- ggplot2::facet_grid(\n cols = ggplot2::vars(.data$.panel),\n scales = \"free_x\", space = \"free\",\n drop = FALSE, as.table = FALSE\n )\n free_row <- TRUE\n free_column <- FALSE\n }\n } else {\n facet <- facet_stack(direction, craftsman$layout_name)\n }\n plot <- ggmelt_facet(plot, facet,\n free_row = free_row, free_column = free_column\n )\n }\n if (!craftsman$free_coord) {\n plot <- gguse_linear_coord(plot, layout_name = craftsman$layout_name)\n }\n\n # set limits and default scales\n if (!craftsman$free_limits) {\n if (is_horizontal(direction)) {\n plot <- plot + ggalign_design(\n y = design,\n ylabels = .subset(craftsman$labels, .subset2(design, \"index\"))\n )\n } else {\n plot <- plot + ggalign_design(\n x = design,\n xlabels = .subset(craftsman$labels, .subset2(design, \"index\"))\n )\n }\n }\n\n # let `Craftsman` add other components\n plot <- craftsman$build_plot(plot, design = design, ...)\n plot <- craftsman$finish_plot(plot, plot_schemes, theme)\n\n # Let layout finally modify the plot\n plot <- chain_decorate(stack, plot)\n\n # add the plot to the composer\n stack_composer_align_plot(composer, plot, size)\n}\n\n#' @importFrom grid unit.c unit\nstack_composer_add.QuadLayout <- function(plot, stack, composer, schemes, theme,\n direction, ...) {\n patches <- quad_build(plot, schemes, theme, direction)\n plots <- .subset2(patches, \"plots\")\n sizes <- .subset2(patches, \"sizes\")\n\n if (is_horizontal(.subset2(composer, \"direction\"))) {\n composer$left_or_top <- .subset2(composer, \"left_or_top\") ||\n !is.null(.subset2(plots, \"top\"))\n composer$right_or_bottom <- .subset2(composer, \"right_or_bottom\") ||\n !is.null(.subset2(plots, \"bottom\"))\n composer <- stack_composer_align_plot(\n composer,\n .subset2(plots, \"left\"),\n .subset2(sizes, \"left\")\n )\n composer <- stack_composer_align_plot(\n composer,\n .subset2(plots, \"main\"),\n .subset2(.subset2(sizes, \"main\"), \"width\")\n )\n l <- max(.subset2(composer, \"r\"))\n if (!is.null(top <- .subset2(plots, \"top\"))) {\n if (.subset2(composer, \"align\") == 1L) {\n composer$t <- .subset2(composer, \"t\") + 1L\n composer$b <- .subset2(composer, \"b\") + 1L\n composer$align <- .subset2(composer, \"align\") + 1L\n }\n if (!is_null_unit(size <- .subset2(sizes, \"top\"))) {\n attr(top, \"vp\")$height <- size\n }\n composer <- stack_composer_add_plot(composer, top, t = 1L, l = l)\n }\n if (!is.null(bottom <- .subset2(plots, \"bottom\"))) {\n if (!is_null_unit(size <- .subset2(sizes, \"bottom\"))) {\n attr(bottom, \"vp\")$height <- size\n }\n composer <- stack_composer_add_plot(composer, bottom,\n t = .subset2(composer, \"align\") + 1L, l = l\n )\n }\n composer <- stack_composer_align_plot(\n composer,\n .subset2(plots, \"right\"),\n .subset2(sizes, \"right\")\n )\n } else {\n composer$left_or_top <- .subset2(composer, \"left_or_top\") ||\n !is.null(.subset2(plots, \"left\"))\n composer$right_or_bottom <- .subset2(composer, \"right_or_bottom\") ||\n !is.null(.subset2(plots, \"right\"))\n composer <- stack_composer_align_plot(\n composer,\n .subset2(plots, \"top\"),\n .subset2(sizes, \"top\")\n )\n composer <- stack_composer_align_plot(\n composer,\n .subset2(plots, \"main\"),\n .subset2(.subset2(sizes, \"main\"), \"height\")\n )\n t <- max(.subset2(composer, \"b\"))\n if (!is.null(left <- .subset2(plots, \"left\"))) {\n if (.subset2(composer, \"align\") == 1L) {\n composer$l <- .subset2(composer, \"l\") + 1L\n composer$r <- .subset2(composer, \"r\") + 1L\n composer$align <- .subset2(composer, \"align\") + 1L\n }\n if (!is_null_unit(size <- .subset2(sizes, \"left\"))) {\n attr(left, \"vp\")$width <- size\n }\n composer <- stack_composer_add_plot(composer, left, t = t, l = 1L)\n }\n if (!is.null(right <- .subset2(plots, \"right\"))) {\n if (!is_null_unit(size <- .subset2(sizes, \"right\"))) {\n attr(right, \"vp\")$width <- size\n }\n composer <- stack_composer_add_plot(composer, right,\n t = t, l = .subset2(composer, \"align\") + 1L\n )\n }\n composer <- stack_composer_align_plot(\n composer,\n .subset2(plots, \"bottom\"),\n .subset2(sizes, \"bottom\")\n )\n }\n composer\n}\n\n#' @export\nstack_composer_add.list <- function(plot, stack, composer, ...) {\n for (p in plot) {\n composer <- stack_composer_add(\n plot = p, stack = stack, composer = composer, ...\n )\n }\n composer\n}\n"], ["/ggalign/R/fortify-data-frame-.R", "#' Build a data frame\n#'\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' This function converts various objects to a data frame.\n#'\n#' @param data An object to be converted to a data frame.\n#' @param ... Arguments passed to methods.\n#' @inheritParams fortify_matrix\n#' @return A data frame.\n#' @eval\n#' rd_collect_family(\"fortify_data_frame\",\n#' \"`fortify_data_frame` method collections\"\n#' )\n#' @export\nfortify_data_frame <- function(data, ..., data_arg = NULL, call = NULL) {\n UseMethod(\"fortify_data_frame\")\n}\n\n#' @inherit fortify_data_frame title description\n#' @param ... Additional arguments passed to [`fortify()`][ggplot2::fortify].\n#' @inheritParams fortify_data_frame\n#' @details\n#' By default, it calls [`fortify()`][ggplot2::fortify] to build the\n#' data frame.\n#' @family fortify_data_frame\n#' @export\nfortify_data_frame.default <- function(data, ..., data_arg = NULL,\n call = NULL) {\n ggplot2::fortify(model = data, ...)\n}\n\n#' @inherit fortify_data_frame.default title description\n#' @param data An object to be converted to a data frame.\n#' @inheritParams rlang::args_dots_empty\n#' @inheritParams fortify_data_frame\n#' @return A data frame with following columns:\n#'\n#' - `.names`: the names for the vector (only applicable if names exist).\n#' - `value`: the actual value of the vector.\n#'\n#' @family fortify_data_frame\n#' @export\nfortify_data_frame.character <- function(data, ..., data_arg = NULL,\n call = NULL) {\n call <- call %||% current_call()\n rlang::check_dots_empty(call = call)\n ans <- list(.names = vec_names(data), value = data)\n if (is.null(.subset2(ans, \".names\"))) ans$.names <- NULL\n new_data_frame(ans)\n}\n\n#' @rdname fortify_data_frame.character\n#' @export\nfortify_data_frame.numeric <- fortify_data_frame.character\n\n#' @rdname fortify_data_frame.character\n#' @export\nfortify_data_frame.logical <- fortify_data_frame.character\n\n#' @rdname fortify_data_frame.character\n#' @export\nfortify_data_frame.complex <- fortify_data_frame.character\n\n#' @export\nfortify_data_frame.waiver <- function(data, ..., data_arg = NULL,\n call = NULL) {\n call <- call %||% current_call()\n rlang::check_dots_empty(call = call)\n data\n}\n\n#' @export\nfortify_data_frame.NULL <- fortify_data_frame.waiver\n\n#' @inherit fortify_data_frame.default title description\n#' @param data An object to be converted to a data frame.\n#' @inheritParams fortify_data_frame\n#' @return A data frame with at least following columns:\n#'\n#' - `seqnames`: The sequence (e.g., chromosome) names.\n#' - `start`: The start positions of the ranges.\n#' - `end`: The end positions of the ranges.\n#' - `width`: The width of each range.\n#'\n#' @family fortify_data_frame\n#' @export\nfortify_data_frame.GRanges <- function(data, ..., data_arg = NULL,\n call = NULL) {\n as.data.frame(data, ...)\n}\n\n#' @inherit fortify_data_frame.default title description\n#' @param data A matrix-like object.\n#' @param lvls A logical value indicating whether to restore factor levels using\n#' those stored in [`ggalign_lvls()`], or a character vector specifying custom\n#' levels for the `value` column. If levels are provided or restored, the\n#' `value` column will be returned as a factor.\n#' @inheritParams rlang::args_dots_empty\n#' @inheritParams fortify_data_frame\n#' @return\n#' Matrix will be transformed into a long-form data frame, where each row\n#' represents a unique combination of matrix indices and their corresponding\n#' values. The resulting data frame will contain the following columns:\n#'\n#' - `.row_names` and `.row_index`: the row names (only applicable when names\n#' exist) and an integer representing the row index of the original matrix.\n#'\n#' - `.column_names` and `.column_index`: the column names (only applicable\n#' when names exist) and column index of the original matrix.\n#'\n#' - `value`: the matrix value, returned as a factor if levels are specified or\n#' restored.\n#'\n#' @family fortify_data_frame\n#' @export\nfortify_data_frame.matrix <- function(data, lvls = NULL, ...,\n data_arg = NULL, call = NULL) {\n call <- call %||% current_call()\n rlang::check_dots_empty(call = call)\n row_nms <- vec_names(data)\n col_nms <- colnames(data)\n if (isFALSE(lvls)) {\n lvls <- NULL\n } else if (isTRUE(lvls)) {\n lvls <- ggalign_lvls_get(lvls)\n } else if (!is.null(lvls) && !is.character(lvls)) {\n cli_abort(\n \"{.arg lvls} must be a single boolean value or a character\",\n call = call\n )\n }\n data <- new_data_frame(list(\n .row_index = vec_rep(seq_len(nrow(data)), ncol(data)),\n .column_index = vec_rep_each(seq_len(ncol(data)), nrow(data)),\n value = c(data)\n ))\n if (!is.null(row_nms)) data$.row_names <- row_nms[data$.row_index]\n if (!is.null(col_nms)) data$.column_names <- col_nms[data$.column_index]\n if (!is.null(lvls)) data$value <- factor(data$value, levels = lvls)\n data\n}\n\n#' @export\n#' @rdname fortify_data_frame.matrix\nfortify_data_frame.DelayedMatrix <- function(data, ...) {\n fortify_data_frame(as.matrix(data), ...)\n}\n\n#' @export\n#' @rdname fortify_data_frame.matrix\nfortify_data_frame.Matrix <- function(data, ...) {\n fortify_data_frame(as.matrix(data), ...)\n}\n"], ["/ggalign/R/utils-assert.R", "# `assert_*()` functions will do the side effects\n# `check_*()` functions will return the arguments\n#' @importFrom rlang caller_arg caller_call\nassert_gp <- function(gp, arg = caller_arg(gp), call = caller_call()) {\n assert_s3_class(gp, \"gpar\", arg = arg, call = call)\n}\n\n#' @importFrom rlang caller_arg caller_call\nassert_mapping <- function(mapping, arg = caller_arg(mapping),\n call = caller_call()) {\n if (!inherits(mapping, \"uneval\")) {\n cli_abort(c(\"{.arg {arg}} must be created with {.fn aes}.\",\n x = \"You've supplied {.obj_type_friendly {mapping}}.\"\n ), call = call)\n }\n}\n\nassert_mismatch_nobs <- function(align, n, nobs, arg) {\n if (n != nobs) {\n cli_abort(sprintf(\n \"{.arg %s} (nobs: %d) of %s is not compatible with the %s (nobs: %d)\",\n arg, nobs, object_name(align), align$layout_name, n\n ))\n }\n}\n\nassert_sub_split <- function(align, panel) {\n if (!is.null(panel)) {\n cli_abort(c(\n sprintf(\"%s cannot do sub-split\", object_name(align)),\n i = sprintf(\n \"Group of layout %s-axis already exists\",\n to_coord_axis(align$direction)\n )\n ), call = align$call)\n }\n}\n\nassert_reorder <- function(align, panel, index, strict) {\n if (!is.null(panel) && nlevels(panel) > 1L && strict &&\n !all(index == reorder_index(panel, index))) {\n layout_name <- align$layout_name\n object_name <- object_name(align)\n cli_abort(c(\n sprintf(\"Cannot add %s to %s\", object_name, layout_name),\n i = sprintf(\n \"Group of %s will disrupt the ordering index of %s\", layout_name, object_name\n ),\n i = \"try to set {.code strict = FALSE} to reorder within each group\"\n ), call = align$call)\n }\n}\n\nassert_position <- function(position, arg = caller_arg(position),\n call = caller_call()) {\n assert_string(position, empty_ok = FALSE, arg = arg, call = call)\n if (grepl(\"[^tlbr]\", position)) {\n cli_abort(sprintf(\n \"{.arg {arg}} can only contain the %s characters\",\n oxford_and(.tlbr)\n ), call = call)\n }\n}\n\nassert_guides <- function(guides, arg = caller_arg(guides),\n call = caller_call()) {\n assert_string(guides, empty_ok = FALSE, arg = arg, call = call)\n if (grepl(\"[^tlbri]\", guides)) {\n cli_abort(sprintf(\n \"{.arg {arg}} can only contain the %s characters\",\n oxford_and(c(.tlbr, \"i\"))\n ), call = call)\n }\n}\n\nassert_layout_position <- function(position, arg = caller_arg(position),\n call = caller_call()) {\n if (!is.waive(position) && !is.null(position)) {\n assert_position(position, arg = arg, call = call)\n }\n}\n\nassert_layout_guides <- function(guides, arg = caller_arg(guides),\n call = caller_call()) {\n if (!is.waive(guides) && !is.null(guides)) {\n assert_guides(guides, arg = arg, call = call)\n }\n}\n\n#' @importFrom grid is.unit\ncheck_stack_sizes <- function(sizes, arg = caller_arg(sizes),\n call = caller_call()) {\n if (!(all(is.na(sizes)) || is.numeric(sizes) || is.unit(sizes))) {\n cli_abort(\n \"{.arg {arg}} must be a numeric or {.cls unit} object\",\n call = call\n )\n }\n l <- length(sizes)\n if (l != 1L && l != 3L) {\n cli_abort(\n \"{.arg {arg}} must have size `1` or `3`, not size {l}\",\n call = call\n )\n }\n if (!is.unit(sizes)) sizes <- unit(sizes, \"null\")\n sizes\n}\n\n#' @importFrom rlang arg_match0\ncheck_direction <- function(direction, arg = caller_arg(direction),\n call = caller_call()) {\n direction <- arg_match0(direction, c(\"h\", \"v\"),\n arg_nm = arg, error_call = call\n )\n switch(direction, h = \"horizontal\", v = \"vertical\") # styler: off\n}\n\nassert_limits <- function(limits, allow_null = TRUE, arg = caller_arg(limits),\n call = caller_call()) {\n if (is.null(limits) && allow_null) {\n return(invisible(NULL))\n }\n if (!inherits(limits, \"continuous_limits\")) {\n cli_abort(\n \"{.arg {arg}} must be specified with {.fn continuous_limits}\",\n call = call\n )\n }\n if (rlang::is_named(limits)) {\n cli_abort(\n \"{.arg {arg}} shouldn't be created with {.arg x}/{.arg y} argument in {.fn continuous_limits}\",\n call = call\n )\n }\n}\n\n#' @importFrom grid is.unit\ncheck_size <- function(size, arg = caller_arg(size), call = caller_call()) {\n if (!is_scalar(size) &&\n !(is.na(size) || is.numeric(size) || is.unit(size))) {\n cli_abort(\n \"{.arg {arg}} must be a single numeric or unit object\",\n call = call\n )\n }\n if (!is.unit(size)) size <- unit(size, \"null\")\n size\n}\n\ncheck_scheme_data <- function(data, arg = caller_arg(data),\n call = caller_call()) {\n if (!is.waive(data) && !is.null(data) &&\n !is.function(data <- allow_lambda(data))) {\n cli_abort(paste(\n \"{.arg {arg}} must be a function,\",\n \"{.code NULL} or {.fn waiver}\"\n ), call = call)\n }\n data\n}\n\ncheck_stack_context <- function(what, arg = caller_arg(what),\n call = caller_call()) {\n if (is.null(what)) return(what) # styler: off\n if (.rlang_check_number(what, allow_decimal = FALSE, min = 1) != 0L &&\n !is_string(what)) {\n cli_abort(\n \"{.arg {arg}} must be a single positive integer number or string\",\n call = call\n )\n }\n what\n}\n\ncheck_order <- function(order, arg = caller_arg(order), call = caller_call()) {\n if (is.null(order)) {\n NA_integer_\n } else if (.rlang_check_number(order, allow_decimal = FALSE) == 0L) {\n as.integer(order)\n } else {\n cli_abort(\"{.arg {arg}} must be single integer number\", call = call)\n }\n}\n\nassert_align <- function(x, arg = caller_arg(x), call = caller_call()) {\n if (!inherits(x, \"scheme_align\")) {\n cli_abort(\n \"{.arg {arg}} must be created by {.fn scheme_align}\",\n call = call\n )\n }\n}\n\nassert_active <- function(x, allow_null = TRUE,\n arg = caller_arg(x), call = caller_call()) {\n if (is.null(x) && allow_null) {\n return(invisible(NULL))\n }\n if (!inherits(x, \"ggalign_active\")) {\n cli_abort(\n \"{.arg {arg}} must be created by {.fn active}\",\n call = call\n )\n }\n}\n\nassert_obs_size <- function(obs_size, arg = caller_arg(obs_size),\n call = caller_call()) {\n if (.rlang_check_number(obs_size, allow_decimal = TRUE, # styler: off\n .Machine$double.eps, 1) != 0L) { # styler: off\n cli_abort(\n \"{.arg {arg}} must be a single number in `(0, 1]`\",\n call = call\n )\n }\n}\n"], ["/ggalign/R/ggmark.R", "#' Add a plot to annotate selected observations\n#'\n#' @param mark A [`mark_draw()`] object to define how to draw the links. Like\n#' [`mark_line()`], [`mark_tetragon()`]. Note the names of the pair links will\n#' be used to define the panel names so must be unique.\n#' @inheritParams ggalign\n#' @param group1,group2 A single boolean value indicating whether to use the\n#' panel group information from the layout as the paired groups. By default,\n#' if no specific observations are selected in `mark`, `ggmark()` will\n#' automatically connect all observations and group them according to the\n#' layout's defined groups.\n#' @param obs_size A single numeric value that indicates the size of a single\n#' observation, ranging from `(0, 1]`.\n#' @section ggplot2 specification:\n#' `ggmark` initializes a ggplot object. The underlying data is created using\n#' [`fortify_data_frame()`]. Please refer to it for more details.\n#'\n#' In addition, the following columns will be added to the data frame:\n#'\n#' - `.panel`: the panel for the aligned axis. It means `x-axis` for vertical\n#' stack layout (including top and bottom annotation), `y-axis` for\n#' horizontal stack layout (including left and right annotation).\n#'\n#' - `.names` ([`vec_names()`][vctrs::vec_names]) and `.index`\n#' ([`vec_size()`][vctrs::vec_size()]/[`NROW()`]): a character names (only\n#' applicable when names exists) and an integer of index of the original\n#' data.\n#'\n#' - `.hand`: A factor with levels `c(\"left\", \"right\")` for horizontal stack\n#' layouts, or `c(\"top\", \"bottom\")` for vertical stack layouts, indicating\n#' the position of the linked observations.\n#'\n#' @examples\n#' set.seed(123)\n#' small_mat <- matrix(rnorm(56), nrow = 7)\n#' rownames(small_mat) <- paste0(\"row\", seq_len(nrow(small_mat)))\n#' colnames(small_mat) <- paste0(\"column\", seq_len(ncol(small_mat)))\n#'\n#' # mark_line\n#' ggheatmap(small_mat) +\n#' theme(axis.text.x = element_text(hjust = 0, angle = -60)) +\n#' anno_right() +\n#' align_kmeans(3L) +\n#' ggmark(mark_line(I(1:3) ~ NULL)) +\n#' geom_boxplot(aes(.names, value)) +\n#' theme(plot.margin = margin(l = 0.1, t = 0.1, unit = \"npc\"))\n#'\n#' # mark_tetragon\n#' ggheatmap(small_mat) +\n#' theme(axis.text.x = element_text(hjust = 0, angle = -60)) +\n#' anno_right() +\n#' align_kmeans(3L) +\n#' ggmark(mark_tetragon(I(1:3) ~ NULL)) +\n#' geom_boxplot(aes(.names, value)) +\n#' theme(plot.margin = margin(l = 0.1, t = 0.1, unit = \"npc\"))\n#' @importFrom rlang list2\n#' @export\nggmark <- function(mark, data = waiver(), mapping = aes(), ...,\n group1 = NULL, group2 = NULL,\n obs_size = 1, size = NULL, active = NULL) {\n if (!inherits(mark, \"ggalign_mark_draw\")) {\n cli_abort(\"{.arg mark} must be a {.fn mark_draw} object\")\n }\n assert_obs_size(obs_size)\n assert_active(active)\n active <- update_active(active, new_active(use = TRUE))\n assert_bool(group1, allow_null = TRUE)\n assert_bool(group2, allow_null = TRUE)\n new_craftbox(\n MarkGg,\n # fields added to `MarkGg`\n input_data = allow_lambda(data), # used by AlignGg\n params = list2(...), # used by AlignGg\n mark = mark, # used by MarkGg\n group1 = group1, group2 = group2,\n obs_size = obs_size,\n\n # slot\n plot = ggplot(mapping = mapping),\n size = size,\n schemes = default_schemes(data, th = theme_panel_border()),\n active = active\n )\n}\n\n#' @importFrom ggplot2 ggproto ggplot margin element_rect\nMarkGg <- ggproto(\"MarkGg\", Craftsman,\n free_facet = TRUE,\n free_limits = TRUE,\n interact_layout = function(self, layout) {\n layout_name <- self$layout_name\n if (!self$in_linear) { # only used for linear coordinate\n cli_abort(c(\n sprintf(\n \"Cannot add %s to %s\",\n object_name(self), layout_name\n ),\n i = sprintf(\n \"%s can only be used in linear layout\",\n object_name(self)\n )\n ))\n }\n if (is_layout_continuous(layout)) { # only used for discrete variable\n # ggmark special for discrete variables\n cli_abort(c(\n sprintf(\"Cannot add %s to %s\", object_name(self), layout_name),\n i = sprintf(\"%s cannot align discrete variables\", layout_name)\n ))\n }\n ans <- ggproto_parent(AlignGg, self)$interact_layout(layout)\n self$labels0 <- self$labels # CrossMark uses `labels0`\n ans\n },\n build_plot = function(self, plot, design, extra_design = NULL,\n previous_design = NULL) {\n if (is.null(.subset2(design, \"nobs\"))) {\n cli_abort(sprintf(\n \"you must initialize %s before drawing %s\",\n self$layout_name, object_name(self)\n ), call = self$call)\n }\n mark <- self$mark\n\n # parse links --------------------------------------------\n links <- .subset2(mark, \"links\")\n group1 <- self$group1\n group2 <- self$group2\n position <- self$position\n if (is_empty(links) && is.null(group1) && is.null(group2)) {\n # guess group1 and group2 from position\n if (is.null(position)) { # a normal stack layout\n group1 <- TRUE\n } else if (any(position == c(\"top\", \"left\"))) {\n group2 <- TRUE\n } else {\n group1 <- TRUE\n }\n }\n full_data <- split(\n seq_len(.subset2(design, \"nobs\")),\n .subset2(design, \"panel\")\n )\n if (isTRUE(group1) && isTRUE(group2)) {\n extra_links <- mapply(function(l1, l2) {\n new_pair_link(I(l1), I(l2))\n }, full_data, full_data, SIMPLIFY = FALSE)\n } else if (isTRUE(group1)) {\n extra_links <- lapply(full_data, function(l) {\n new_pair_link(hand1 = I(l))\n })\n } else if (isTRUE(group2)) {\n extra_links <- lapply(full_data, function(l) {\n new_pair_link(hand2 = I(l))\n })\n } else {\n extra_links <- NULL\n }\n\n # unlock the object\n self$unlock()\n self$mark$links <- vec_c(extra_links, links)\n on.exit(self$mark <- mark, add = TRUE) # restore the original `mark`\n on.exit(self$lock(), add = TRUE)\n\n # setup the plot\n plot <- ggproto_parent(CrossMark, self)$build_plot(\n plot,\n design,\n extra_design,\n previous_design %||% design\n )\n plot_data <- plot$data\n\n # prepare data for the plot ------------------------------\n if (!is.null(data <- self$data)) {\n plot_data <- inner_join(plot_data, data, by = \".index\")\n }\n gguse_data(plot, ggalign_data_restore(plot_data, data))\n },\n finish_plot = function(self, plot, schemes, theme) {\n ggproto_parent(CrossMark, self)$finish_plot(plot, schemes, theme)\n },\n summary = function(self, plot) {\n header <- ggproto_parent(Craftsman, self)$summary(plot)\n c(header, \" Add plot to annotate observations\")\n }\n)\n"], ["/ggalign/R/ggplot-theme.R", "#' @importFrom ggplot2 theme_bw element_blank\ndefault_theme <- function() {\n if (is_theme_unset()) {\n theme_bw() +\n theme(\n axis.text = ggplot2::element_text(color = \"black\"),\n strip.text = ggplot2::element_text(color = \"black\"),\n panel.border = element_blank(),\n panel.grid = element_blank()\n )\n } else {\n theme_get()\n }\n}\n\n# Check if user has set the theme\nis_theme_unset <- function() {\n isTRUE(all.equal(\n complete_theme(ggfun(\"ggplot_global\")$theme_default),\n complete_theme(theme_get())\n ))\n}\n\nis_theme_complete <- function(x) isTRUE(attr(x, \"complete\", exact = TRUE))\n\n#' @importFrom ggplot2 rel element_blank\ntheme_no_strip <- function() {\n theme(\n strip.text = element_blank(),\n strip.background = element_blank()\n )\n}\n\ntheme_panel_border <- function() theme(panel.border = element_rect(fill = NA))\n\n#' @importFrom utils packageVersion\n#' @importFrom rlang try_fetch\ncomplete_theme <- function(theme) {\n if (packageVersion(\"ggplot2\") > \"3.5.2\") {\n ggfun(\"complete_theme\")(theme)\n } else {\n ggfun(\"plot_theme\")(list(theme = theme))\n }\n}\n\n#' @importFrom ggplot2 register_theme_elements el_def element_line\ntheme_elements <- function() {\n register_theme_elements(\n ggalign.line = element_line(\n color = \"black\",\n linewidth = 0.5,\n linetype = 1,\n lineend = \"butt\",\n linejoin = \"round\"\n ),\n ggalign.polygon = element_polygon(\n fill = NA,\n color = \"black\",\n linewidth = 0.5,\n linetype = 1,\n alpha = NA,\n lineend = \"butt\",\n linejoin = \"round\",\n linemitre = 10\n ),\n element_tree = list(\n plot.patch_title = el_def(\"element_text\", \"text\"),\n plot.patch_title.top = el_def(\"element_text\", \"text\"),\n plot.patch_title.left = el_def(\"element_text\", \"text\"),\n plot.patch_title.bottom = el_def(\"element_text\", \"text\"),\n plot.patch_title.right = el_def(\"element_text\", \"text\"),\n plot.patch_title.position = el_def(\"character\"),\n plot.patch_title.position.top = el_def(\"character\"),\n plot.patch_title.position.left = el_def(\"character\"),\n plot.patch_title.position.bottom = el_def(\"character\"),\n plot.patch_title.position.right = el_def(\"character\"),\n panel.spacing.r = el_def(c(\"unit\", \"rel\"), \"panel.spacing\"),\n ggalign.line = el_def(\"element_line\"),\n ggalign.curve = el_def(\"element_curve\"),\n ggalign.polygon = el_def(\"element_polygon\")\n )\n )\n}\n\n#' Used to match theme\n#'\n#' @keywords internal\n#' @noRd\ntheme_recycle <- function() structure(list(), class = \"theme_recycle\")\n\n#' @importFrom ggplot2 ggplot_add ggproto ggproto_parent\n#' @export\nggplot_add.theme_recycle <- function(object, plot, object_name, ...) {\n ParentFacet <- plot$facet\n if (!inherits(ParentFacet, c(\"FacetGrid\", \"FacetWrap\"))) {\n return(plot)\n }\n # recycle axis theme elements\n plot$facet <- ggproto(\n NULL, ParentFacet,\n draw_panels = function(self, panels, layout,\n x_scales = NULL, y_scales = NULL,\n ranges, coord, data = NULL, theme, params) {\n # we recycle the theme elements of the guide axis\n theme <- recycle_theme_axis(\"x\", theme, x_scales)\n theme <- recycle_theme_axis(\"y\", theme, y_scales)\n ParentCoord <- coord\n h_tick0 <- h_text0 <- 0L\n v_tick0 <- v_text0 <- 0L\n # subset theme for each panel\n coord <- ggproto(NULL, ParentCoord,\n # `align_scales` will attach the `.__plot_index__`\n render_axis_h = function(self, panel_params, theme) {\n scale <- (.subset2(panel_params, \"x\") %||%\n .subset2(panel_params, \"theta\")\n )$scale\n h_tick1 <- h_tick0 + length(scale$get_breaks())\n h_text1 <- h_text0 + length(scale$get_labels())\n theme <- subset_theme_axis(\n \"x\", theme, h_tick0, h_text0, h_tick1, h_text1\n )\n h_tick0 <<- h_tick1\n h_text0 <<- h_text1\n ggproto_parent(ParentCoord, self)$render_axis_h(\n panel_params, theme\n )\n },\n render_axis_v = function(self, panel_params, theme) {\n scale <- (.subset2(panel_params, \"y\") %||%\n .subset2(panel_params, \"r\")\n )$scale\n v_tick1 <- v_tick0 + length(scale$get_breaks())\n v_text1 <- v_text0 + length(scale$get_labels())\n theme <- subset_theme_axis(\n \"y\", theme, v_tick0, v_text0, v_tick1, v_text1\n )\n v_tick0 <<- v_tick1\n v_text0 <<- v_text1\n ggproto_parent(ParentCoord, self)$render_axis_v(\n panel_params, theme\n )\n }\n )\n ggproto_parent(ParentFacet, self)$draw_panels(\n panels = panels, layout = layout,\n x_scales = x_scales, y_scales = y_scales,\n ranges = ranges, coord = coord, data = data,\n theme = theme, params = params\n )\n }\n )\n plot\n}\n\n#################################################################\n# Apply a function to the vectorized field of the theme object\ntheme_vec <- function(.th, .el, .fn, ...) {\n element <- calc_element(.el, .th)\n if (inherits(element, \"element\")) {\n .th[[.el]] <- element_vec(element, .fn, ...)\n } else if (!is.null(element)) {\n .th[[.el]] <- .fn(element, ...)\n }\n .th\n}\n\nrecycle_theme_axis <- function(axis, theme, scales) {\n breaks <- unlist(lapply(scales, function(s) s$get_breaks()), FALSE, FALSE)\n labels <- unlist(lapply(scales, function(x) x$get_labels()), FALSE, FALSE)\n align_theme_axis(axis, theme,\n tick_fn = function(v, arg) rep(v, length.out = length(breaks)),\n text_fn = function(v, arg) rep(v, length.out = length(labels))\n )\n}\n\nsubset_theme_axis <- function(axis, theme, tick0, text0, tick1, text1) {\n tick_index <- (tick0 + 1L):tick1\n text_index <- (text0 + 1L):text1\n align_theme_axis(\n axis, theme,\n tick_fn = function(value) vec_slice(value, tick_index),\n text_fn = function(value) vec_slice(value, text_index)\n )\n}\n\nalign_theme_axis <- function(axis, theme, text_fn, tick_fn) {\n if (axis == \"y\") {\n positions <- c(\"left\", \"right\")\n } else {\n positions <- c(\"top\", \"bottom\")\n }\n # only apply the function when the element values is not a scalar\n .text_fn <- function(v) if (length(v) > 1L) text_fn(v) else v\n .tick_fn <- function(v) if (length(v) > 1L) tick_fn(v) else v\n for (element in paste(\"axis.text\", axis, positions, sep = \".\")) {\n theme <- theme_vec(theme, element, .text_fn)\n }\n for (element in paste(\"axis.ticks\", axis, positions, sep = \".\")) {\n theme <- theme_vec(theme, element, .tick_fn)\n }\n for (element in paste(\"axis.ticks.length\", axis, positions, sep = \".\")) {\n theme <- theme_vec(theme, element, .tick_fn)\n }\n theme\n}\n"], ["/ggalign/R/alignpatch-patchwork.R", "########################################\n#' @importFrom utils modifyList getFromNamespace\n#' @export\nalignpatch.patchwork <- function(x) {\n rlang::check_installed(\"patchwork\", \"to align patchwork\")\n get_patches <- getFromNamespace(\"get_patches\", \"patchwork\")\n # patchwork will keep the class when extracting patches from it.\n # we removed the classes for patchwork, added behind patchwork\n # in this way, the last plot won't have class like `free_align`,\n # `free_border`, `free_lab`, et al. which is added for the patchwork\n sub_patchwork_cls <- which(class(x) == \"patchwork\") - 1L # nolint\n if (sub_patchwork_cls > 0L) {\n class(x) <- class(x)[-seq_len(sub_patchwork_cls)]\n }\n x <- get_patches(x)\n plots <- .subset2(x, \"plots\")\n layout <- .subset2(x, \"layout\")\n annotation <- .subset2(x, \"annotation\")\n default <- getFromNamespace(\"default_layout\", \"patchwork\")\n layout <- modifyList(default, layout[\n !vapply(layout, is.null, logical(1L), USE.NAMES = FALSE)\n ])\n if (identical(.subset2(layout, \"guides\"), \"collect\")) {\n layout$guides <- .TLBR\n } else {\n layout$guides <- NULL\n }\n alignpatch(AlignPatches(\n plots,\n layout = layout,\n titles = .subset(annotation, names(layout_title())),\n theme = .subset2(annotation, \"theme\")\n ))\n}\n\n#' @export\nalignpatch.free_plot <- function(x) {\n if (inherits(x, \"patchwork\")) {\n free_settings <- attr(x, \"patchwork_free_settings\")\n } else {\n free_settings <- attr(x, \"free_settings\")\n }\n free_settings <- split(\n names(free_settings),\n factor(free_settings, rev(unique(free_settings)))\n )\n class(x) <- vec_set_difference(class(x), \"free_plot\")\n for (type in names(free_settings)) {\n side <- paste(.subset2(free_settings, type), collapse = \"\")\n x <- switch(type,\n panel = free_align(x, side),\n label = free_lab(x, side),\n space = free_space(free_border(x, side), side),\n )\n }\n alignpatch(x)\n}\n\n######################################\n# `patch` from `patchwork`: patchwork::plot_spacer\n#' @importFrom ggplot2 ggproto\n#' @export\nalignpatch.patch <- function(x) {\n rlang::check_installed(\n \"patchwork\", sprintf(\"to align %s plot\", obj_type_friendly(x))\n )\n ggproto(NULL, PatchPatchworkPatch, plot = x)\n}\n\n#' @importFrom ggplot2 ggproto\nPatchPatchworkPatch <- ggproto(\n \"PatchPatchworkPatch\", Patch,\n # `patch` from `patchwork`: patchwork::plot_spacer\n #' @importFrom gtable gtable_add_rows gtable_add_cols\n #' @importFrom ggplot2 find_panel\n patch_gtable = function(self, theme, guides, plot = self$plot) {\n guides <- if (length(guides)) \"collect\" else \"keep\"\n ans <- patchwork::patchGrob(patch, guides = guides)\n for (border in .TLBR) {\n panel_pos <- find_panel(ans)\n if (border == \"top\") {\n h <- .subset2(panel_pos, \"t\") - 4L # above original xlab\n ans <- gtable_add_rows(ans, unit(0L, \"mm\"), pos = h)\n } else if (border == \"left\") {\n v <- .subset2(panel_pos, \"l\") - 4L # left of the ylab\n ans <- gtable_add_cols(ans, unit(0, \"mm\"), pos = v)\n } else if (border == \"bottom\") {\n h <- .subset2(panel_pos, \"b\") + 3L # below original xlab\n ans <- gtable_add_rows(ans, unit(0L, \"mm\"), pos = h)\n } else if (border == \"right\") {\n v <- .subset2(panel_pos, \"r\") + 3L # right of the ylab\n ans <- gtable_add_cols(ans, unit(0, \"mm\"), pos = v)\n }\n }\n ans\n }\n)\n\n#' @export\nalignpatch.spacer <- function(x) NULL\n\n#########################################\n# `patch` from `patchwork`: patchwork::wrap_elements\n#' @export\nalignpatch.wrapped_patch <- alignpatch.patch\n"], ["/ggalign/R/layout-operator.R", "#' Layout operator\n#'\n#' @description\n#' `r lifecycle::badge('experimental')`\n#'\n#' - `+`: Adds elements to the active plot in the active layout.\n#' - `&`: Applies elements to all plots in the layout.\n#' - `-`: Adds elements to multiple plots in the layout.\n#'\n#' @details\n#' The `+` operator is straightforward and should be used as needed.\n#'\n#' In order to reduce code repetition `ggalign` provides two operators for\n#' adding ggplot elements (geoms, themes, facets, etc.) to multiple/all plots in\n#' `r rd_layout()`: `-` and `&`.\n#'\n#' @param e1 A `r rd_layout()`.\n#' @param e2 An object to be added to the plot.\n#' @return A modified `Layout` object.\n#' @examples\n#' set.seed(123)\n#' small_mat <- matrix(rnorm(56), nrow = 7)\n#' ggheatmap(small_mat) +\n#' anno_top() +\n#' ggalign() +\n#' geom_point(aes(y = value))\n#'\n#' # `&` operator apply it to all plots\n#' ggheatmap(small_mat) +\n#' anno_top() +\n#' align_dendro() &\n#' theme(panel.border = element_rect(\n#' colour = \"red\", fill = NA, linewidth = unit(2, \"mm\")\n#' ))\n#'\n#' # If the active layout is the annotation stack, the `-` operator will only\n#' # add the elements to all plots in the active annotation stack:\n#' ggheatmap(small_mat) +\n#' anno_left(size = 0.2) +\n#' align_dendro(aes(color = branch), k = 3L) +\n#' align_dendro(aes(color = branch), k = 3L) -\n#' # Modify the the color scales of all plots in the left annotation\n#' scale_color_brewer(palette = \"Dark2\")\n#'\n#' # If the active layout is the `stack_layout()` itself, `-`\n#' # applies the elements to all plots in the layout except the nested\n#' # `ggheatmap()`/`quad_layout()`.\n#' stack_alignv(small_mat) +\n#' align_dendro() +\n#' ggtitle(\"I'm from the parent stack\") +\n#' ggheatmap() +\n#' # remove any active context\n#' stack_active() +\n#' align_dendro() +\n#' ggtitle(\"I'm from the parent stack\") -\n#' # Modify the the color scales of all plots in the stack layout except the\n#' # heatmap layout\n#' scale_color_brewer(palette = \"Dark2\") -\n#' # set the background of all plots in the stack layout except the heatmap\n#' # layout\n#' theme(plot.background = element_rect(fill = \"red\"))\n#'\n#' @name layout-operator\nNULL\n\nutils::globalVariables(\".Generic\")\n\nmethods::setMethod(\"Ops\", c(\"LayoutProto\", \"ANY\"), function(e1, e2) {\n if (missing(e2)) {\n cli_abort(c(\n \"Cannot use {.code {.Generic}} with a single argument.\",\n \"i\" = \"Did you accidentally put {.code {.Generic}} on a new line?\"\n ))\n }\n\n if (is.null(e2)) return(e1) # styler: off\n\n # Get the name of what was passed in as e2, and pass along so that it\n # can be displayed in error messages\n e2name <- deparse(substitute(e2))\n switch(.Generic, # nolint\n `+` = layout_add(e1, e2, e2name),\n `-` = layout_subtract(e1, e2, e2name),\n `&` = layout_and_add(e1, e2, e2name),\n stop_incompatible_op(.Generic, e1, e2)\n )\n})\n\n#################################################################\nlayout_add <- function(layout, object, object_name) {\n UseMethod(\"layout_add\")\n}\n\n#' @export\nlayout_add.QuadLayout <- function(layout, object, object_name) {\n quad_layout_add(object, layout, object_name)\n}\n\n#' @export\nlayout_add.ChainLayout <- function(layout, object, object_name) {\n chain_layout_add(object, layout, object_name)\n}\n\n#################################################################\nlayout_subtract <- function(layout, object, object_name) {\n UseMethod(\"layout_subtract\")\n}\n\n#' @export\nlayout_subtract.QuadLayout <- function(layout, object, object_name) {\n quad_layout_subtract(object, layout, object_name)\n}\n\n#' @export\nlayout_subtract.ChainLayout <- function(layout, object, object_name) {\n chain_layout_subtract(object, layout, object_name)\n}\n\n#################################################################\n# we use and_add suffix here, since `and` is very similar with `add`.\nlayout_and_add <- function(layout, object, object_name) {\n UseMethod(\"layout_and_add\")\n}\n\n#' @export\nlayout_and_add.QuadLayout <- function(layout, object, object_name) {\n quad_layout_and_add(object, layout, object_name)\n}\n\n#' @export\nlayout_and_add.ChainLayout <- function(layout, object, object_name) {\n chain_layout_and_add(object, layout, object_name)\n}\n\n# For objects cannot be used with `-` or `&`\n#' @include layout-quad-operator.R\n#' @include layout-chain-operator.R\nlapply(\n c(\n \"quad_layout_subtract\", \"chain_layout_subtract\",\n \"quad_layout_and_add\", \"chain_layout_and_add\"\n ),\n function(genname) {\n params <- .subset2(strsplit(genname, \"_\"), 1L)\n\n # function argument list\n pairlist <- rlang::pairlist2(object = , layout = , object_name = )\n names(pairlist) <- c(\"object\", .subset(params, 1L), \"object_name\")\n operator <- switch(.subset(params, 3L),\n subtract = \"-\",\n and = \"&\"\n )\n # styler: off\n for (class in c(\"ggplot\", \"quad_active\", \"quad_anno\", \"layout_title\",\n \"layout_theme\", \"CraftBox\", \"ChainLayout\",\n \"QuadLayout\", \"continuous_limits\")) {\n # styler: on\n registerS3method(\n genname, class,\n rlang::new_function(pairlist, substitute(\n {\n cli_abort(c(\n sprintf(\n \"Cannot add %s with {.code %s}\",\n name, operator\n ),\n i = \"Try to use {.code +} instead\"\n ))\n },\n list(\n name = switch(class,\n CraftBox = ,\n ChainLayout = ,\n QuadLayout = quote(object_name(object)),\n # for all others\n \"{.var {object_name}}\"\n ),\n operator = operator\n )\n ))\n )\n }\n }\n)\n"], ["/ggalign/R/fortify-matrix-maftools.R", "#' Build a Matrix for OncoPrint\n#'\n#' @description\n#' Convert `MAF` object to a matrix:\n#' - `fortify_matrix.MAF`: Extract genomic alterations for genes.\n#' - `fortify_matrix.MAF_pathways`: Extract genomic alterations for pathways.\n#' [`tune.MAF()`] helps convert `MAF` object to a `MAF_pathways` object.\n#'\n#' @inheritParams rlang::args_dots_empty\n#' @param data A [`MAF`][maftools::read.maf] object.\n#' @param genes An atomic character defines the genes to draw.\n#' @param n_top A single number indicates how many top genes to be drawn.\n#' @param remove_empty_genes A single boolean value indicats whether to drop\n#' genes without any genomic alterations.\n#' @param remove_empty_samples A single boolean value indicats whether to drop\n#' samples without any genomic alterations.\n#' @param collapse_vars A single boolean value indicating whether to collapse\n#' multiple alterations in the same sample and gene into a single value\n#' `\"Multi_Hit\"`. Alternatively, you can provide a single string indicates the\n#' collapsed values.\n#' @param use_syn A single boolean value indicates whether to include synonymous\n#' variants when Classifies SNPs into transitions and transversions.\n#' @param missing_genes A string, either `\"error\"` or `\"remove\"`, specifying the\n#' action for handling missing genes.\n#' @inheritParams fortify_matrix\n#' @section ggalign attributes:\n#' For `fortify_matrix.MAF`:\n#' - `gene_summary`: A data frame of gene summary informations. See\n#' `maftools::getGeneSummary()` for details.\n#' - `sample_summary`: A data frame of sample summary informations. See\n#' `maftools::getSampleSummary()` for details.\n#' - `sample_anno`: A data frame of sample clinical informations. See\n#' `maftools::getClinicalData()` for details.\n#' - `variant_weights`: A data frame of variant weights. Each gene in a sample\n#' is assigned a total weight of `1`. When multiple variants occur in the\n#' same gene-sample pair, the weight for each variant reflects its proportion\n#' of the total.\n#' - `n_genes`: Total number of genes.\n#' - `n_samples`: Total number of samples.\n#' - `titv`: A list of data frame with Transitions and Transversions\n#' summary. See `maftools::titv()` for details.\n#'\n#' The levels of `Variant_Classification` will be stored in [`ggalign_lvls()`].\n#' If they do not exist, alphabetical ordering will be used.\n#'\n#' @family fortify_matrix\n#' @importFrom utils getFromNamespace\n#' @importFrom rlang is_string\n#' @export\nfortify_matrix.MAF <- function(data, ..., genes = NULL, n_top = NULL,\n remove_empty_genes = TRUE,\n remove_empty_samples = TRUE,\n collapse_vars = TRUE, use_syn = TRUE,\n missing_genes = \"error\",\n data_arg = NULL, call = NULL) {\n call <- call %||% current_call()\n rlang::check_dots_empty(call = call)\n rlang::check_installed(\n \"maftools\", \"to make alterations matrix from `MAF` object\"\n )\n # prepare arguments\n missing_genes <- arg_match0(\n missing_genes, c(\"error\", \"remove\"),\n error_call = call\n )\n if (isTRUE(collapse_vars)) {\n collapse_vars <- \"Multi_Hit\"\n } else if (isFALSE(collapse_vars)) {\n collapse_vars <- NULL\n } else if (is_string(collapse_vars)) {\n if (collapse_vars == \"\") {\n cli_abort(\"{.arg collapse_vars} cannot be an empty string\",\n call = call\n )\n }\n } else {\n cli_abort(\n paste(\n \"{.arg collapse_vars} must be a single boolean value or a string,\",\n \"but you provide {.obj_type_friendly {collapse_vars}}\"\n ),\n call = call\n )\n }\n\n getSampleSummary <- getExportedValue(\"maftools\", \"getSampleSummary\")\n getGeneSummary <- getExportedValue(\"maftools\", \"getGeneSummary\")\n getClinicalData <- getExportedValue(\"maftools\", \"getClinicalData\")\n\n # if `maftools` is installed, `data.table` must have been installed\n # No need to check if `data.table` is installed\n dcast <- getExportedValue(\"data.table\", \"dcast\")\n setDT <- getExportedValue(\"data.table\", \"setDT\")\n setDF <- getExportedValue(\"data.table\", \"setDF\")\n\n sample_summary <- new_data_frame(getSampleSummary(data))\n gene_summary <- new_data_frame(getGeneSummary(data))\n sample_anno <- new_data_frame(getClinicalData(data))\n\n titv <- getExportedValue(\"maftools\", \"titv\")\n titv <- titv(data, useSyn = use_syn, plot = FALSE)\n titv <- lapply(titv, new_data_frame)\n\n # we transform the data into a normal data frame\n data <- new_data_frame(data@data)[\n c(\"Tumor_Sample_Barcode\", \"Hugo_Symbol\", \"Variant_Classification\")\n ]\n n_genes <- vec_unique_count(.subset2(data, \"Hugo_Symbol\"))\n n_samples <- vec_unique_count(.subset2(data, \"Tumor_Sample_Barcode\"))\n\n # filter by genes --------------------------------------\n if (!is.null(genes)) {\n # reorder the gene annotation based on the provided genes\n genes <- vec_cast(genes, character())\n if (vec_any_missing(genes)) {\n cli_abort(\n \"{.arg genes} cannot contain missing values\",\n call = call\n )\n }\n if (vec_duplicate_any(genes)) {\n cli_abort(\n \"{.arg genes} cannot contain duplicated values\",\n call = call\n )\n }\n if (identical(missing_genes, \"remove\")) {\n genes <- genes[genes %in% .subset2(gene_summary, \"Hugo_Symbol\")]\n }\n if (is_empty(genes)) {\n cli_abort(\n \"No {.arg genes} remain after removing missing genes\",\n call = call\n )\n }\n gene_summary <- vec_slice(\n gene_summary,\n vec_as_location(\n genes,\n n = vec_size(gene_summary),\n names = .subset2(gene_summary, \"Hugo_Symbol\"),\n missing = \"error\"\n )\n )\n }\n genes <- .subset2(gene_summary, \"Hugo_Symbol\")\n if (!is.null(n_top)) {\n n_top <- min(n_top, vec_size(genes))\n index <- vec_slice(\n order(gene_summary$AlteredSamples, decreasing = TRUE),\n seq_len(n_top)\n )\n index <- sort(index) # don't change the order, we do only subset\n genes <- vec_slice(genes, index)\n gene_summary <- vec_slice(gene_summary, index)\n }\n data <- vec_slice(data, .subset2(data, \"Hugo_Symbol\") %in% genes)\n\n # Group variants --------------------------------------\n indices <- vec_group_loc(data[c(\"Tumor_Sample_Barcode\", \"Hugo_Symbol\")])\n vars <- .subset2(data, \"Variant_Classification\")\n lvls <- levels(vars) %||% sort(vec_unique(vars))\n nlvls <- vec_size(lvls)\n var_list <- vec_chop(as.character(vars), indices = .subset2(indices, \"loc\"))\n\n # calcualte the variant weights -----------------------\n variant_weights <- lapply(var_list, function(var) {\n o <- numeric(nlvls)\n names(o) <- lvls\n counts <- vec_count(var)\n o[.subset2(counts, \"key\")] <- .subset2(counts, \"count\") /\n sum(.subset2(counts, \"count\"))\n o\n })\n variant_weights <- inject(rbind(!!!variant_weights))\n gene_indices <- vec_group_loc(\n .subset2(.subset2(indices, \"key\"), \"Hugo_Symbol\")\n )\n variant_weights <- lapply(\n vec_chop(variant_weights, indices = .subset2(gene_indices, \"loc\")),\n colSums\n )\n variant_weights <- vec_cbind(\n Hugo_Symbol = .subset2(gene_indices, \"key\"),\n vec_rbind(!!!variant_weights)\n )\n\n # collapse the vars ------------------------------------\n if (is.null(collapse_vars)) {\n vars <- vapply(var_list, function(var) {\n if (length(var) > 1L) {\n paste(var, collapse = \";\")\n } else {\n var\n }\n }, character(1L), USE.NAMES = FALSE)\n } else {\n vars <- vapply(var_list, function(var) {\n if (vec_unique_count(var) > 1L) {\n collapse_vars\n } else if (length(var) > 1L) {\n paste(var, collapse = \";\")\n } else {\n var\n }\n }, character(1L), USE.NAMES = FALSE)\n if (any(vars == collapse_vars)) lvls <- c(lvls, collapse_vars)\n }\n ans <- vec_cbind(\n .subset2(indices, \"key\"),\n new_data_frame(list(Variant_Classification = vars))\n )\n\n # restore all samples, this will introduce `NA` in `Hugo_Symbol`\n ans <- right_join(ans, data_frame0(\n Tumor_Sample_Barcode = vec_unique(sample_summary$Tumor_Sample_Barcode)\n ))\n setDT(ans)\n ans <- dcast(ans, Hugo_Symbol ~ Tumor_Sample_Barcode,\n value.var = \"Variant_Classification\"\n )\n setDF(ans)\n ans <- vec_slice(ans, !is.na(.subset2(ans, \"Hugo_Symbol\")))\n\n # convert data into a matrix\n if (remove_empty_genes) {\n # convert to a matrix\n ans <- as.matrix(column_to_rownames(ans, \"Hugo_Symbol\"))\n\n # reorder the rows based on the `genes` specified\n index <- match(genes, rownames(ans))\n ans <- vec_slice(ans, index[!is.na(index)])\n } else {\n # restore all genes\n ans <- right_join(ans, data_frame0(Hugo_Symbol = genes))\n\n # convert to a matrix\n ans <- as.matrix(column_to_rownames(ans, \"Hugo_Symbol\"))\n\n # reorder the rows based on the `genes` specified\n ans <- vec_slice(ans, genes)\n }\n\n # filter samples when necessary\n if (remove_empty_samples) {\n keep <- colSums(!is.na(ans)) > 0L\n ans <- ans[, keep, drop = FALSE]\n }\n\n # reorder the rows based on the gene ordering\n gene_summary <- vec_slice(\n gene_summary,\n vec_as_location(\n rownames(ans),\n n = vec_size(gene_summary),\n names = vec_cast(gene_summary$Hugo_Symbol, character())\n )\n )\n variant_weights <- vec_slice(\n variant_weights,\n vec_as_location(\n rownames(ans),\n n = vec_size(variant_weights),\n names = variant_weights$Hugo_Symbol\n )\n )\n\n # reorder columns based on the sample ordering\n sample_summary <- vec_slice(\n sample_summary,\n vec_as_location(\n colnames(ans),\n n = vec_size(sample_summary),\n names = vec_cast(sample_summary$Tumor_Sample_Barcode, character())\n )\n )\n sample_anno <- vec_slice(\n sample_anno,\n vec_as_location(\n colnames(ans),\n n = vec_size(sample_anno),\n names = sample_anno$Tumor_Sample_Barcode\n )\n )\n titv <- lapply(titv, function(data) {\n data <- left_join(\n data_frame0(Tumor_Sample_Barcode = colnames(ans)),\n data\n )\n vec_slice(data, vec_as_location(\n colnames(ans),\n n = vec_size(data),\n names = vec_cast(data$Tumor_Sample_Barcode, character())\n ))\n })\n ggalign_data_set(ans,\n sample_summary = sample_summary,\n gene_summary = gene_summary,\n sample_anno = sample_anno,\n variant_weights = variant_weights,\n n_samples = n_samples, n_genes = n_genes, titv = titv,\n .lvls = lvls\n )\n}\n\n#' Convert the shape of a MAF for fortify method\n#'\n#' @param data A [`MAF`][maftools::read.maf] object.\n#' @param shape Not used currently.\n#' @seealso [`fortify_matrix.MAF_pathways()`]\n#' @family tune\n#' @export\ntune.MAF <- function(data, shape = NULL) {\n if (!is.null(shape)) {\n cli_abort(\"{.arg shape} cannot be used currently for {.cls MAF} object\")\n }\n new_tune(data, class = \"MAF_pathways\")\n}\n\n#' @param pathdb A string of `r oxford_or(c(\"smgbp\", \"sigpw\"))`, or a named list\n#' of genes to define the pathways.\n#' @param remove_empty_pathways A single boolean value indicats whether to drop\n#' pathways without any genomic alterations.\n#' @section ggalign attributes:\n#' For `fortify_matrix.MAF_pathways`:\n#' - `gene_list`: the pathway contents.\n#' - `pathway_summary`: pathway summary informations. See\n#' `maftools::pathways()` for details.\n#' - `sample_summary`: sample summary informations. See\n#' `maftools::getSampleSummary()` for details.\n#' - `sample_anno`: sample clinical informations. See\n#' `maftools::getClinicalData()` for details.\n#' @export\n#' @rdname fortify_matrix.MAF\nfortify_matrix.MAF_pathways <- function(data, ..., pathdb = \"smgbp\",\n remove_empty_pathways = TRUE,\n remove_empty_samples = TRUE,\n data_arg = NULL,\n call = NULL) {\n call <- call %||% current_call()\n rlang::check_dots_empty(call = call)\n rlang::check_installed(\n \"maftools\", \"to make alterations matrix from `MAF` object\"\n )\n get_pw_summary <- getFromNamespace(\"get_pw_summary\", \"maftools\")\n maf <- tune_data(data)\n if (rlang::is_string(pathdb)) {\n pathdb <- arg_match0(pathdb, c(\"sigpw\", \"smgbp\"))\n pathway_summary <- get_pw_summary(maf, pathways = pathdb)\n } else if (is.data.frame(pathdb)) {\n cli_abort(\"{.arg pathdb} cannot be a data frame\", call = call)\n } else if (is.list(pathdb)) {\n if (!rlang::is_named(pathdb)) {\n cli_abort(sprintf(\n \"{.arg pathdb} must be a named list of a single string of %s\",\n oxford_or(c(\"sigpw\", \"smgbp\"))\n ), call = call)\n }\n pathdb <- data_frame0(\n Pathway = factor(\n vec_rep_each(names(pathdb), lengths(pathdb)),\n names(pathdb)\n ),\n Gene = unlist(pathdb, FALSE, FALSE)\n )\n pathdb <- vec_unique(pathdb)\n pathway_summary <- get_pw_summary(maf, pathways = pathdb)\n }\n getSampleSummary <- getExportedValue(\"maftools\", \"getSampleSummary\")\n getClinicalData <- getExportedValue(\"maftools\", \"getClinicalData\")\n sample_summary <- new_data_frame(getSampleSummary(maf))\n sample_anno <- new_data_frame(getClinicalData(maf))\n\n gene_list <- attr(pathway_summary, \"genes\") # a list of genes\n ans <- new_data_frame(maf@data)[\n c(\"Tumor_Sample_Barcode\", \"Hugo_Symbol\", \"Variant_Classification\")\n ]\n full_genes <- unlist(gene_list, FALSE, FALSE)\n ans$pathways <- vec_slice(\n vec_set_names(\n vec_rep_each(names(gene_list), lengths(gene_list)),\n full_genes\n ),\n if_else(ans$Hugo_Symbol %in% full_genes,\n ans$Hugo_Symbol, NA_character_\n )\n )\n ans$Alt <- if_else(is.na(.subset2(ans, \"pathways\")), NA_character_, \"Alt\")\n ans <- vec_unique(ans[c(\"Tumor_Sample_Barcode\", \"pathways\", \"Alt\")])\n\n # if `maftools` is installed, `data.table` must have been installed\n # No need to check if `data.table` is installed\n dcast <- getExportedValue(\"data.table\", \"dcast\")\n setDT <- getExportedValue(\"data.table\", \"setDT\")\n setDF <- getExportedValue(\"data.table\", \"setDF\")\n setDT(ans)\n ans <- dcast(ans, pathways ~ Tumor_Sample_Barcode,\n value.var = \"Alt\", fill = NA_character_\n )\n setDF(ans)\n ans <- vec_slice(ans, !is.na(.subset2(ans, \"pathways\")))\n\n # convert data into a matrix\n if (remove_empty_pathways) {\n # convert to a matrix\n ans <- as.matrix(column_to_rownames(ans, \"pathways\"))\n\n # reorder the rows based on the `pathways` specified\n index <- match(names(gene_list), rownames(ans))\n gene_list <- gene_list[!is.na(index)]\n ans <- vec_slice(ans, index[!is.na(index)])\n } else {\n # restore all pathways\n ans <- right_join(ans, data_frame0(pathways = names(gene_list)))\n\n # convert to a matrix\n ans <- as.matrix(column_to_rownames(ans, \"pathways\"))\n\n # reorder the rows based on the `pathways` specified\n ans <- vec_slice(ans, names(gene_list))\n }\n\n # filter samples when necessary\n if (remove_empty_samples) {\n keep <- colSums(!is.na(ans)) > 0L\n ans <- ans[, keep, drop = FALSE]\n }\n\n # reorder the rows based on the pathways ordering\n setDF(pathway_summary)\n pathway_summary <- vec_slice(\n pathway_summary,\n vec_as_location(\n rownames(ans),\n n = vec_size(pathway_summary),\n names = vec_cast(pathway_summary$Pathway, character())\n )\n )\n\n # reorder columns based on the sample ordering\n sample_summary <- vec_slice(\n sample_summary,\n vec_as_location(\n colnames(ans),\n n = vec_size(sample_summary),\n names = vec_cast(sample_summary$Tumor_Sample_Barcode, character())\n )\n )\n sample_anno <- vec_slice(\n sample_anno,\n vec_as_location(\n colnames(ans),\n n = vec_size(sample_anno),\n names = sample_anno$Tumor_Sample_Barcode\n )\n )\n ggalign_data_set(ans,\n gene_list = gene_list,\n pathway_summary = pathway_summary,\n sample_summary = sample_summary,\n sample_anno = sample_anno\n )\n}\n\n#' Build a matrix from a maftools object\n#'\n#' @inheritParams rlang::args_dots_empty\n#' @param data A [`GISTIC`][maftools::readGistic] object.\n#' @param n_top A single number indicates how many top bands to be drawn.\n#' @param bands An atomic character defines the bands to draw.\n#' @param ignored_bands An atomic character defines the bands to be ignored.\n#' @param sample_anno A data frame of sample clinical features to be added.\n#' @param remove_empty_samples A single boolean value indicating whether to drop\n#' samples without any genomic alterations.\n#' @inheritParams fortify_matrix\n#' @section ggalign attributes:\n#' - `sample_anno`: sample clinical informations provided in `sample_anno`.\n#' - `sample_summary`: sample copy number summary informations. See\n#' `data@@cnv.summary` for details.\n#' - `cytoband_summary`: cytoband summary informations. See\n#' `data@@cytoband.summary` for details.\n#' - `gene_summary`: gene summary informations. See\n#' `data@@gene.summary` for details.\n#' - `summary`: A data frame of summary information. See `data@@summary` for\n#' details.\n#' @family fortify_matrix\n#' @export\nfortify_matrix.GISTIC <- function(data, ..., n_top = NULL, bands = NULL,\n ignored_bands = NULL, sample_anno = NULL,\n remove_empty_samples = TRUE,\n data_arg = NULL,\n call = NULL) {\n call <- call %||% current_call()\n rlang::check_dots_empty(call = call)\n rlang::check_installed(\n \"maftools\",\n \"to make CNV matrix from `GISTIC` object\"\n )\n assert_number_whole(n_top,\n allow_null = TRUE,\n call = call\n )\n assert_character(bands,\n allow_null = TRUE,\n call = call\n )\n assert_character(ignored_bands,\n allow_null = TRUE,\n call = call\n )\n assert_s3_class(sample_anno, \"data.frame\",\n allow_null = TRUE,\n call = call\n )\n assert_bool(remove_empty_samples,\n call = call\n )\n cn_mat <- data@cnMatrix\n if (is.null(bands)) {\n bands <- rownames(cn_mat)\n } else {\n bands <- intersect(bands, rownames(cn_mat))\n }\n if (!is.null(ignored_bands)) {\n bands <- setdiff(bands, ignored_bands)\n }\n if (!is.null(bands)) {\n cn_mat <- vec_slice(cn_mat, rownames(cn_mat) %in% bands)\n }\n if (!is.null(n_top)) {\n cn_mat <- vec_slice(cn_mat, seq_len(min(n_top, nrow(cn_mat))))\n }\n if (remove_empty_samples) {\n keep <- colSums(cn_mat != \"\") > 0L\n cn_mat <- cn_mat[, keep, drop = FALSE]\n }\n if (!is.null(sample_anno)) {\n loc <- vec_locate_matches(\n colnames(cn_mat),\n .subset2(sample_anno, \"Tumor_Sample_Barcode\") %||%\n .subset2(sample_anno, 1L),\n relationship = \"one-to-one\",\n needles_arg = \"data\",\n haystack_arg = \"sample_anno\",\n error_call = call\n )\n sample_anno <- vec_slice(sample_anno, .subset2(loc, \"haystack\"))\n }\n sample_summary <- new_data_frame(data@cnv.summary)\n sample_summary <- vec_slice(\n sample_summary,\n vec_as_location(\n colnames(cn_mat),\n n = vec_size(sample_summary),\n names = vec_cast(sample_summary$Tumor_Sample_Barcode, character())\n )\n )\n gene_summary <- new_data_frame(data@gene.summary)\n cytoband_sumamry <- new_data_frame(data@cytoband.summary)\n cytoband_sumamry <- vec_slice(\n cytoband_sumamry,\n vec_as_location(\n rownames(cn_mat),\n n = vec_size(cytoband_sumamry),\n names = vec_cast(cytoband_sumamry$Unique_Name, character())\n )\n )\n ggalign_data_set(cn_mat,\n sample_anno = sample_anno,\n sample_summary = sample_summary,\n cytoband_sumamry = cytoband_sumamry,\n gene_summary = gene_summary,\n sumamry = data@summary\n )\n}\n"], ["/ggalign/R/layout-chain-stack-cross.R", "#' Arrange plots crosswise horizontally or vertically\n#'\n#' @description\n#' `r lifecycle::badge('experimental')`\n#'\n#' The `stack_cross` function is derived from [`stack_discrete()`] and allows\n#' for different layout ordering indices within a single layout.\n#'\n#' Two aliases are provided for convenience:\n#' - `stack_crossv`: A special case of `stack_cross` that sets\n#' `direction = \"v\"` for vertical alignment.\n#' - `stack_crossh`: A special case of `stack_cross` that sets\n#' `direction = \"h\"` for horizontal alignment.\n#'\n#' @param data `r rd_layout_data()`, [`fortify_matrix()`] will be used to\n#' convert the data to a matrix.\n#' @param ... Additional arguments passed to [`fortify_matrix()`].\n#' @inheritParams stack_layout\n#' @seealso [`ggcross()`]\n#' @export\nstack_cross <- function(direction, data = NULL, ...,\n theme = NULL, sizes = NA) {\n UseMethod(\"stack_cross\", data)\n}\n\n#' @export\n#' @rdname stack_cross\nstack_crossv <- function(data = NULL, ...) {\n stack_cross(data = data, direction = \"v\", ...)\n}\n\n#' @export\n#' @rdname stack_cross\nstack_crossh <- function(data = NULL, ...) {\n stack_cross(data = data, direction = \"h\", ...)\n}\n\n#' @include layout-chain-stack-.R\nmethods::setClass(\n \"StackCross\",\n contains = \"StackLayout\",\n # A list of old design\n list(odesign = \"list\", cross_points = \"integer\", break_points = \"integer\"),\n prototype = list(\n odesign = list(),\n cross_points = integer(),\n break_points = integer()\n )\n)\n\n#' @export\nstack_cross.default <- function(direction, data = NULL, ...) {\n ans <- stack_discrete(data = data, direction = direction, ...)\n ans <- methods::as(ans, \"StackCross\")\n ans@name <- \"stack_cross\"\n ans\n}\n\n#' @importFrom grid unit.c\n#' @importFrom rlang is_empty is_string\nresolve_stack_layout.StackCross <- function(stack, schemes, theme,\n extra_design) {\n # check if we should initialize the layout observations\n layout_design <- stack@design\n if (is_discrete_design(layout_design) &&\n is.null(.subset2(layout_design, \"nobs\")) &&\n any(vapply(plot_list, is_cross_plot, logical(1L), USE.NAMES = FALSE))) {\n cli_abort(sprintf(\n \"You must initialize the layout observations to plot the %s\",\n object_name(stack)\n ))\n }\n plot_list <- stack@plot_list\n\n direction <- stack@direction\n position <- .subset2(stack@heatmap, \"position\")\n plot_list <- vec_chop(\n plot_list,\n sizes = diff(c(0L, stack@cross_points, length(plot_list)))\n )\n design_list <- c(stack@odesign, list(layout_design))\n\n # build the stack\n composer <- stack_composer(direction)\n\n # for `free_spaces`, if we have applied it in the whole stack layout we\n # shouln't use it for a single plot. Otherwise, the guide legends collected\n # by the layout will overlap with the axis of the plot in the layout.\n #\n # this occurs in the annotation stack (`position` is not `NULL`).\n stack_spaces <- .subset2(.subset2(schemes, \"scheme_align\"), \"free_spaces\")\n if (is_string(stack_spaces) && !is.null(position)) {\n released_spaces <- stack_spaces\n } else {\n released_spaces <- NULL\n }\n previous_design <- NULL\n for (i in seq_along(plot_list)) {\n plots <- .subset2(plot_list, i)\n\n # prepare design for current group\n design <- .subset2(design_list, i)\n design <- setup_design(design)\n\n if (is_empty(plots)) {\n previous_design <- design\n next\n }\n\n # we remove the plot without actual plot area\n keep <- vapply(plots, function(plot) {\n # we remove objects without plot area\n # Now, only `CraftBox` will contain `NULL`\n !is_craftbox(plot) || !is.null(plot@plot)\n }, logical(1L), USE.NAMES = FALSE)\n plots <- .subset(plots, keep)\n\n if (is_empty(plots)) {\n previous_design <- design\n next\n }\n\n # we reorder the plots based on the `order` slot\n plot_order <- vapply(plots, function(plot) {\n # always keep cross() in the start\n if (is_cross_plot(plot)) {\n 1L\n } else if (is_craftbox(plot)) {\n .subset2(plot@active, \"order\")\n } else {\n .subset2(plot@plot_active, \"order\")\n }\n }, integer(1L), USE.NAMES = FALSE)\n plots <- .subset(plots, make_order(plot_order))\n composer <- stack_composer_add(\n plots,\n stack = stack,\n composer,\n schemes = schemes,\n theme = theme,\n design = design,\n extra_design = extra_design,\n direction = direction,\n position = position,\n released_spaces = released_spaces,\n previous_design = previous_design\n )\n previous_design <- design\n }\n composer\n}\n"], ["/ggalign/R/alignpatch-align_plots.R", "#' Arrange multiple plots into a grid\n#'\n#' @param ... <[dyn-dots][rlang::dyn-dots]> A list of plots, ususally the\n#' ggplot object. Use `NULL` to indicate an empty spacer.\n#' @param ncol,nrow The dimensions of the grid to create - if both are `NULL` it\n#' will use the same logic as [`facet_wrap()`][ggplot2::facet_wrap] to set the\n#' dimensions\n#' @param byrow If `FALSE` the plots will be filled in in column-major order.\n#' @param widths,heights The relative widths and heights of each column and row\n#' in the grid. Will get repeated to match the dimensions of the grid. The\n#' special value of `NA` will behave as `1null` unit unless a fixed aspect plot\n#' is inserted in which case it will allow the dimension to expand or contract\n#' to match the aspect ratio of the content.\n#' @param area Specification of the location of areas in the layout. Can\n#' either be specified as a text string or by concatenating calls to\n#' [`area()`] together.\n#' @param guides A string with one or more of `r oxford_and(c(.tlbr, \"i\"))`\n#' indicating which side of guide legends should be collected. Defaults to\n#' [`waiver()`][ggplot2::waiver()], which inherits from the parent layout. If\n#' there is no parent layout, or if `NULL` is provided, no guides will be\n#' collected.\n#' @param theme A [`theme()`][ggplot2::theme] object used to customize various\n#' elements of the layout. By default, the theme will inherit from the parent\n#' `layout`.\n#' @param design An alias for `area`, retained for backward compatibility.\n#' @return An `AlignPatches` object.\n#' @seealso\n#' - [layout_design()]\n#' - [layout_title()]\n#' - [layout_theme()]\n#' @examples\n#' # directly copied from patchwork\n#' p1 <- ggplot(mtcars) +\n#' geom_point(aes(mpg, disp))\n#' p2 <- ggplot(mtcars) +\n#' geom_boxplot(aes(gear, disp, group = gear))\n#' p3 <- ggplot(mtcars) +\n#' geom_bar(aes(gear)) +\n#' facet_wrap(~cyl)\n#' p4 <- ggplot(mtcars) +\n#' geom_bar(aes(carb))\n#' p5 <- ggplot(mtcars) +\n#' geom_violin(aes(cyl, mpg, group = cyl))\n#'\n#' # Either add the plots as single arguments\n#' align_plots(p1, p2, p3, p4, p5)\n#'\n#' # Or use bang-bang-bang to add a list\n#' align_plots(!!!list(p1, p2, p3), p4, p5)\n#'\n#' # Match plots to areas by name\n#' area <- \"#BB\n#' AA#\"\n#' align_plots(B = p1, A = p2, area = area)\n#'\n#' # Compare to not using named plot arguments\n#' align_plots(p1, p2, area = area)\n#' @export\nalign_plots <- function(..., ncol = NULL, nrow = NULL, byrow = TRUE,\n widths = NA, heights = NA, area = NULL,\n guides = waiver(), theme = NULL, design = NULL) {\n plots <- rlang::dots_list(..., .ignore_empty = \"all\", .named = NULL)\n nms <- names(plots)\n area <- area %||% design\n if (!is.null(nms) && is.character(area)) {\n area_names <- unique(trimws(.subset2(strsplit(area, \"\"), 1L)))\n area_names <- sort(vec_set_difference(area_names, c(\"\", \"#\")))\n if (all(nms %in% area_names)) {\n plot_list <- vector(\"list\", length(area_names))\n names(plot_list) <- area_names\n plot_list[nms] <- plots\n plots <- plot_list\n }\n }\n\n for (plot in plots) {\n if (!has_method(plot, \"alignpatch\", default = FALSE)) {\n cli_abort(\"Cannot align {.obj_type_friendly {plot}}\")\n }\n }\n\n # setup layout parameters\n layout <- layout_design(\n ncol = ncol, nrow = nrow, byrow = byrow,\n widths = widths, heights = heights, area = area,\n guides = guides\n )\n AlignPatches(plots = plots, layout = layout, theme = theme)\n}\n\n#' @importFrom ggplot2 is_theme\n#' @importFrom S7 new_object S7_object prop prop<-\nAlignPatches <- S7::new_class(\"AlignPatches\",\n properties = list(\n plots = S7::new_property(\n S7::class_list,\n setter = function(self, value) {\n if (!is.null(prop(self, \"plots\"))) {\n cli_abort(\"'@plots' is read-only\")\n }\n prop(self, \"plots\", check = FALSE) <- value\n self\n }\n ),\n layout = S7::new_property(\n S7::class_list,\n setter = function(self, value) {\n if (!inherits(value, \"layout_design\")) {\n cli_abort(\"'@layout' must be a {.fn layout_design} object\")\n }\n old <- prop(self, \"layout\") %||% list(\n ncol = NULL, nrow = NULL, byrow = TRUE,\n widths = NA, heights = NA, area = NULL,\n guides = waiver()\n )\n guides <- .subset2(value, \"guides\")\n value$guides <- NULL # guides need special consideration\n old <- update_non_waive(old, value)\n if (is.null(guides) || is.waive(guides)) {\n old[\"guides\"] <- list(guides)\n } else if (!identical(guides, NA)) {\n old[\"guides\"] <- list(setup_guides(guides))\n }\n prop(self, \"layout\", check = FALSE) <- old\n self\n }\n ),\n titles = S7::new_property(\n S7::class_list,\n setter = function(self, value) {\n if (!inherits(value, \"layout_title\")) {\n cli_abort(\"'@titles' must be a {.fn layout_title} object'\")\n }\n old <- prop(self, \"titles\") %||%\n list(title = NULL, subtitle = NULL, caption = NULL)\n prop(self, \"titles\", check = FALSE) <- update_non_waive(\n old, value\n )\n self\n }\n ),\n theme = S7::new_property(\n S7::class_any,\n setter = function(self, value) {\n if (!is.null(value) && !is_theme(value)) {\n cli_abort(\"'@theme' must be a {.cls theme} object'\")\n }\n if (is.null(prop(self, \"theme\")) || is.null(value)) {\n prop(self, \"theme\", check = FALSE) <- value\n } else {\n prop(self, \"theme\", check = FALSE) <- prop(self, \"theme\") +\n value\n }\n self\n },\n default = NULL\n )\n ),\n constructor = function(plots = list(), layout = NULL,\n titles = NULL, theme = NULL) {\n out <- new_object(\n S7_object(),\n plots = plots,\n layout = layout %||% layout_design(),\n titles = titles %||% layout_title(),\n theme = theme\n )\n # for backward compatibility\n add_class(out, \"alignpatches\")\n }\n)\n\n#' @importFrom rlang caller_env\nlocal(\n S7::method(`+`, list(AlignPatches, S7::class_any)) <-\n function(e1, e2) {\n # Get the name of what was passed in as e2, and pass along so that\n # it can be displayed in error messages\n if (missing(e2)) {\n cli_abort(c(\n \"Cannot use {.code +} with a single argument.\",\n \"i\" = \"Did you accidentally put {.code +} on a new line?\"\n ))\n }\n e2name <- deparse(substitute(e2, env = caller_env(2)))\n alignpatches_add(e2, e1, e2name)\n }\n)\n\n#' @importFrom S7 S7_dispatch\nalignpatches_add <- S7::new_generic(\n \"alignpatches_add\", \"object\",\n function(object, patches, objectname) S7_dispatch()\n)\n\nS7::method(alignpatches_add, S7::class_any) <-\n function(object, patches, objectname) {\n if (is.null(object)) return(patches) # styler: off\n cli_abort(c(\n \"Cannot add {objectname}\",\n \"x\" = \"Only other layout elements or compatible objects can be added.\"\n ))\n }\n\n#############################################################\n#' Define the grid to compose plots in\n#'\n#' To control how different plots are laid out, you need to add a layout design\n#' specification. If you are nesting grids, the layout is scoped to the current\n#' nesting level.\n#' @inheritParams align_plots\n#' @return A `layout_design` object.\n#' @examples\n#' p1 <- ggplot(mtcars) +\n#' geom_point(aes(mpg, disp))\n#' p2 <- ggplot(mtcars) +\n#' geom_boxplot(aes(gear, disp, group = gear))\n#' p3 <- ggplot(mtcars) +\n#' geom_bar(aes(gear)) +\n#' facet_wrap(~cyl)\n#' align_plots(p1, p2, p3) +\n#' layout_design(nrow = 1L)\n#' align_plots(p1, p2, p3) +\n#' layout_design(ncol = 1L)\n#' @importFrom ggplot2 waiver\n#' @export\nlayout_design <- function(ncol = waiver(), nrow = waiver(), byrow = waiver(),\n widths = waiver(), heights = waiver(),\n area = waiver(), guides = NA, design = waiver()) {\n if (!is.waive(ncol)) {\n assert_number_whole(ncol, min = 1, allow_na = TRUE, allow_null = TRUE)\n }\n if (!is.waive(nrow)) {\n assert_number_whole(nrow, min = 1, allow_na = TRUE, allow_null = TRUE)\n }\n if (!is.waive(byrow)) assert_bool(byrow)\n area <- area %|w|% design\n if (!is.waive(area)) area <- as_areas(area)\n if (!identical(guides, NA) && !is.waive(guides) && !is.null(guides)) {\n assert_guides(guides)\n }\n structure(\n list(\n ncol = ncol,\n nrow = nrow,\n byrow = byrow,\n widths = widths,\n heights = heights,\n area = area,\n guides = guides\n ),\n class = c(\"layout_design\", \"plot_layout\")\n )\n}\n\nS3_layout_design <- S7::new_S3_class(\"layout_design\")\n\nS7::method(alignpatches_add, S3_layout_design) <-\n function(object, patches, objectname) {\n patches@layout <- object\n patches\n }\n\nS7::method(alignpatches_add, S7::new_S3_class(\"plot_layout\")) <-\n function(object, patches, objectname) {\n object$area <- object$design # pathwork use `design`\n object <- .subset(object, names(layout_design()))\n if (is.waive(object$guides)) {\n object$guides <- NA\n } else if (identical(object$guides, \"auto\")) {\n object$guides <- waiver()\n } else if (identical(object$guides, \"collect\")) {\n object$guides <- \"tlbr\"\n } else if (identical(object$guides, \"keep\")) {\n object[\"guides\"] <- list(NULL)\n }\n alignpatches_add(add_class(object, \"layout_design\"), patches)\n }\n\n##############################################################\n#' Annotate the whole layout\n#'\n#' @inheritParams ggplot2::labs\n#' @return A `layout_title` object.\n#' @examples\n#' p1 <- ggplot(mtcars) +\n#' geom_point(aes(mpg, disp))\n#' p2 <- ggplot(mtcars) +\n#' geom_boxplot(aes(gear, disp, group = gear))\n#' p3 <- ggplot(mtcars) +\n#' geom_bar(aes(gear)) +\n#' facet_wrap(~cyl)\n#' align_plots(p1, p2, p3) +\n#' layout_title(title = \"I'm title\")\n#' @importFrom ggplot2 waiver\n#' @export\nlayout_title <- function(title = waiver(), subtitle = waiver(),\n caption = waiver()) {\n if (!is.waive(title)) assert_string(title, allow_null = TRUE)\n if (!is.waive(subtitle)) assert_string(subtitle, allow_null = TRUE)\n if (!is.waive(caption)) assert_string(caption, allow_null = TRUE)\n structure(\n list(title = title, subtitle = subtitle, caption = caption),\n class = c(\"layout_title\", \"plot_annotation\")\n )\n}\n\nS3_layout_title <- S7::new_S3_class(\"layout_title\")\n\nS7::method(alignpatches_add, S3_layout_title) <-\n function(object, patches, objectname) {\n patches@titles <- object\n patches\n }\n\n##############################################################\n#' Modify theme of the layout\n#'\n#' @inherit ggplot2::theme\n#' @param ... A [`theme()`][ggplot2::theme] object or additional element\n#' specifications not part of base ggplot2. In general, these should also be\n#' defined in the `element tree` argument. [`Splicing`][rlang::splice] a list\n#' is also supported.\n#'\n#' @details\n#' A [`theme()`][ggplot2::theme] object used to customize various elements of\n#' the layout, including `guides`, `title`, `subtitle`, `caption`, `margins`,\n#' `panel.border`, and `background`. By default, the theme will inherit from the\n#' parent `layout`.\n#'\n#' - `guides`, `panel.border`, and `background` will always be used even for the\n#' nested `alignpatches` object.\n#'\n#' - `title`, `subtitle`, `caption`, and `margins` will be added for the\n#' top-level `alignpatches` object only.\n#'\n#' @examples\n#' p1 <- ggplot(mtcars) +\n#' geom_point(aes(mpg, disp))\n#' p2 <- ggplot(mtcars) +\n#' geom_boxplot(aes(gear, disp, group = gear))\n#' p3 <- ggplot(mtcars) +\n#' geom_bar(aes(gear)) +\n#' facet_wrap(~cyl)\n#' align_plots(\n#' p1 + theme(plot.background = element_blank()),\n#' p2 + theme(plot.background = element_blank()),\n#' p3 + theme(plot.background = element_blank())\n#' ) +\n#' layout_theme(plot.background = element_rect(fill = \"red\"))\n#' @importFrom ggplot2 theme\n#' @export\nlayout_theme <- rlang::new_function(\n # We utilize editor completion by listing all `theme()` arguments here.\n # By placing `...` at the beginning, we can check if the first\n # following argument is a `theme()` object rather than individual theme\n # elements.\n c(\n rlang::exprs(... = ),\n .subset(\n rlang::fn_fmls(theme),\n vec_set_difference(names(rlang::fn_fmls(theme)), \"...\")\n )\n ),\n quote({\n elements <- ggfun(\"find_args\")(..., complete = NULL, validate = NULL)\n ans <- theme(!!!elements)\n th <- NULL\n for (i in seq_len(...length())) {\n if (inherits(t <- ...elt(i), \"theme\")) {\n th <- ggfun(\"add_theme\")(th, t)\n }\n }\n add_class(ggfun(\"add_theme\")(th, ans), \"layout_theme\")\n })\n)\n\nS3_layout_theme <- S7::new_S3_class(\"layout_theme\")\n\nS7::method(alignpatches_add, S3_layout_theme) <-\n function(object, patches, objectname) {\n patches@theme <- object\n patches\n }\n\nS7::method(alignpatches_add, S7::new_S3_class(\"plot_annotation\")) <-\n function(object, patches, objectname) {\n patches@titles <- .subset(object, names(layout_title()))\n patches@theme <- .subset2(object, \"theme\")\n patches\n }\n\nupdate_layout_theme <- function(old, new) {\n if (is.null(old) || is.null(new)) return(new) # styler: off\n old + new\n}\n\n#' Add layout annotation (internal use)\n#'\n#' This function is a placeholder for future extensions.\n#' If you're trying to apply a theme, use [layout_theme()] instead.\n#'\n#' @param ... Currently unused. May accept a theme in the future.\n#' @param theme A theme object. If not `waiver()`, an error will be raised.\n#'\n#' @return None. This function is used for input validation.\n#' @importFrom ggplot2 is_theme\n#' @export\n#' @keywords internal\nlayout_annotation <- function(..., theme = waiver()) {\n if (is_theme(...elt(1)) || !is.waive(theme)) {\n cli_abort(\"Please use {.fn layout_theme} instead; {.fn layout_annotation} is reserved for future extensions.\")\n }\n}\n"], ["/ggalign/R/craft-align-hclust.R", "#' Reorder or Group observations based on hierarchical clustering\n#'\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' This function aligns observations within the layout according to a\n#' hierarchical clustering tree, enabling reordering or grouping of elements\n#' based on clustering results.\n#'\n#' @param data A matrix-like object. By default, it inherits from the layout\n#' `matrix`.\n#' @inheritParams align\n#' @inheritParams hclust2\n#' @param reorder_dendrogram A single boolean value indicating whether to\n#' reorder the dendrogram based on the means. Alternatively, you can provide a\n#' custom function that accepts an [`hclust`][stats::hclust] object and the data\n#' used to generate the tree, returning either an [`hclust`][stats::hclust] or\n#' [`dendrogram`][stats::as.dendrogram] object. Default is `FALSE`.\n#' @param reorder_group A single boolean value, indicates whether we should do\n#' Hierarchical Clustering between groups, only used when previous groups have\n#' been established. Default: `FALSE`.\n#' @param k An integer scalar indicates the desired number of groups.\n#' @param h A numeric scalar indicates heights where the tree should be cut.\n#' @param cutree A function used to cut the [`hclust`][stats::hclust] tree. It\n#' should accept four arguments: the [`hclust`][stats::hclust] tree object,\n#' `distance` (only applicable when `method` is a string or a function for\n#' performing hierarchical clustering), `k` (the number of clusters), and `h`\n#' (the height at which to cut the tree). By default,\n#' [`cutree()`][stats::cutree()] is used.\n#' @inheritSection align Discrete Axis Alignment\n#' @seealso [`hclust2()`]\n#' @examples\n#' # align_hclust won't add a dendrogram\n#' ggheatmap(matrix(rnorm(81), nrow = 9)) +\n#' anno_top() +\n#' align_hclust(k = 3L)\n#' @export\nalign_hclust <- function(distance = \"euclidean\",\n method = \"complete\",\n use_missing = \"pairwise.complete.obs\",\n reorder_dendrogram = FALSE,\n reorder_group = FALSE,\n k = NULL, h = NULL, cutree = NULL,\n data = NULL, active = NULL) {\n assert_active(active)\n active <- update_active(active, new_active(use = FALSE))\n .align_hclust(\n align = AlignHclust,\n distance = distance,\n method = method,\n use_missing = use_missing,\n reorder_dendrogram = reorder_dendrogram,\n reorder_group = reorder_group,\n k = k, h = h, cutree = cutree, data = data, active = active\n )\n}\n\n.align_hclust <- function(align, ..., plot = NULL,\n distance = \"euclidean\",\n method = \"complete\",\n use_missing = \"pairwise.complete.obs\",\n reorder_dendrogram = FALSE,\n reorder_group = FALSE,\n k = NULL, h = NULL, cutree = NULL,\n data = NULL, schemes = NULL, active = NULL,\n call = caller_call()) {\n reorder_dendrogram <- allow_lambda(reorder_dendrogram)\n if (!rlang::is_bool(reorder_dendrogram) &&\n !is.null(reorder_dendrogram) &&\n !is.function(reorder_dendrogram)) {\n cli_abort(\n \"{.arg reorder_dendrogram} must be a single boolean value or a function\",\n call = call\n )\n }\n assert_number_whole(k, allow_null = TRUE, call = call)\n assert_number_decimal(h, allow_null = TRUE, call = call)\n assert_bool(reorder_group, call = call)\n cutree <- allow_lambda(cutree)\n assert_(cutree, is.function, \"a function\", allow_null = TRUE, call = call)\n if (inherits(method, \"hclust\")) {\n if (vec_size(.subset2(method, \"order\")) == 0L) {\n cli_abort(\"{.cls hclust} defined in {.arg method} cannot be empty\",\n call = call\n )\n }\n } else if (inherits(method, \"dendrogram\")) {\n if (stats::nobs(method) == 0L) {\n cli_abort(\n \"{.cls dendrogram} defined in {.arg method} cannot be empty\",\n call = call\n )\n }\n }\n\n if (isTRUE(reorder_dendrogram)) {\n reorder_dendrogram <- function(tree, data) {\n if (!inherits(tree, \"dendrogram\")) {\n tree <- stats::as.dendrogram(tree)\n }\n reorder(x = tree, wts = rowMeans(data), agglo.FUN = mean)\n }\n } else if (is.function(reorder_dendrogram)) {\n user_reorder <- reorder_dendrogram\n reorder_dendrogram <- function(tree, data) {\n # we ensure, what we input for user is a `hclust` object.\n if (!inherits(tree, \"hclust\")) tree <- stats::as.hclust(tree)\n ans <- user_reorder(tree, data)\n if (!inherits(ans, \"hclust\") &&\n !inherits(ans, \"dendrogram\")) {\n cli_abort(\n \"{.fn reorder_dendrogram} must return a {.cls hclust} or {.cls dendrogram} object\",\n call = call\n )\n }\n ans\n }\n }\n\n align(\n align = align,\n distance = distance, method = method,\n use_missing = use_missing,\n reorder_dendrogram = reorder_dendrogram,\n reorder_group = reorder_group,\n k = k, h = h, cutree = cutree,\n active = active,\n ..., # additional fields to be added, used by align_dendro\n schemes = schemes %||% default_schemes(),\n data = data,\n plot = plot,\n call = call\n )\n}\n\n#' @importFrom ggplot2 ggproto aes\nAlignHclust <- ggproto(\"AlignHclust\", CraftAlign,\n interact_layout = function(self, layout) {\n if (inherits(self$method, \"hclust\") ||\n inherits(self$method, \"dendrogram\")) {\n layout <- ggproto_parent(CraftAlign, self)$interact_layout(layout)\n if (inherits(self$method, \"hclust\")) {\n nobs <- vec_size(.subset2(self$method, \"order\"))\n } else {\n nobs <- stats::nobs(self$method)\n }\n\n if (is.null(layout_nobs <- .subset2(layout@design, \"nobs\"))) {\n layout@design[\"nobs\"] <- list(nobs)\n } else {\n assert_mismatch_nobs(self, layout_nobs, nobs, arg = \"method\")\n }\n } else {\n layout <- ggproto_parent(AlignOrder2, self)$interact_layout(layout)\n }\n\n # initialize the internal parameters\n self$multiple_tree <- FALSE\n self$height <- NULL\n self$panel <- NULL\n layout\n },\n compute = function(self, panel, index) {\n if (!is.null(self$data) && vec_size(self$data) < 2L) {\n cli_abort(c(\n \"Cannot do Hierarchical Clustering\",\n i = \"must have >= 2 observations to cluster\"\n ), call = self$call)\n }\n\n # if the old panel exist, we do sub-clustering\n if (!is.null(panel) && is.null(self$k) && is.null(self$h) &&\n is.null(self$cutree)) {\n # in this way, we prevent sub-clustering\n if (inherits(self$method, \"hclust\") ||\n inherits(self$method, \"dendrogram\")) {\n cli_abort(\n \"{.arg method} cannot be a {.cls hclust} or {.cls dendrogram} when previous layout panel groups exist\",\n call = self$call\n )\n }\n children <- vector(\"list\", nlevels(panel))\n names(children) <- levels(panel)\n labels <- vec_names(self$data)\n\n # we do clustering within each group ---------------\n for (g in levels(panel)) {\n idx <- which(panel == g)\n gdata <- vec_slice(self$data, idx)\n if (vec_size(gdata) == 1L) {\n children[[g]] <- tree_one_node(idx, .subset(labels, idx))\n } else {\n child <- stats::as.dendrogram(hclust2(\n gdata,\n distance = self$distance,\n method = self$method,\n use_missing = self$use_missing\n ))\n # we restore the actual index of the original matrix\n child <- stats::dendrapply(child, function(x) {\n if (stats::is.leaf(x)) {\n ans <- .subset(idx, x)\n attributes(ans) <- attributes(x)\n ans\n } else {\n x\n }\n })\n if (is.function(self$reorder_dendrogram)) {\n child <- self$reorder_dendrogram(child, gdata)\n }\n children[[g]] <- child\n }\n }\n return(children) # can be a list of `dendrogram` or `hclust` or mix\n }\n hclust2(self$data, self$distance, self$method, self$use_missing)\n },\n #' @importFrom stats order.dendrogram\n align = function(self, panel, index) {\n statistics <- self$statistics\n if (!is.null(panel) && is.null(self$k) && is.null(self$h) &&\n is.null(self$cutree)) {\n # reordering the dendrogram ------------------------\n if (nlevels(panel) > 1L && self$reorder_group) {\n parent_levels <- levels(panel)\n parent_data <- t(sapply(parent_levels, function(g) {\n colMeans(vec_slice(self$data, panel == g), na.rm = TRUE)\n }))\n rownames(parent_data) <- parent_levels\n parent <- hclust2(\n parent_data,\n distance = self$distance,\n method = self$method,\n use_missing = self$use_missing\n )\n # reorder parent based on the parent tree\n if (is.function(self$reorder_dendrogram)) {\n parent <- self$reorder_dendrogram(parent, parent_data)\n }\n # we always ensure the parent is a dendrogram\n # since we'll call `merge_dendrogram()` which requires a\n # dendrogram\n parent <- stats::as.dendrogram(parent)\n panel <- factor(panel, parent_levels[order.dendrogram(parent)])\n # we don't cutree, so we won't draw the height line\n # self$draw_params$height <- attr(ans, \"cutoff_height\")\n } else {\n parent <- NULL\n }\n\n # merge children tree ------------------------------\n if (nlevels(panel) == 1L) {\n statistics <- .subset2(statistics, 1L)\n } else if (isTRUE(self$merge_dendro)) {\n # we have a function named merge_dendrogram(), so we use\n # `merge_dendro` as the argument name\n # `merge_dendrogram` will follow the order of the parent\n statistics <- lapply(statistics, stats::as.dendrogram)\n statistics <- merge_dendrogram(parent, statistics)\n } else {\n # if no parent tree, and we havn't merged the tree\n # we must manually reorder the dendrogram\n if (!is.null(parent)) {\n statistics <- .subset(statistics, levels(panel))\n }\n self$multiple_tree <- TRUE\n }\n } else {\n # hclust2() will attach the distance used\n distance <- attr(statistics, \"distance\")\n if (is.function(self$reorder_dendrogram)) {\n statistics <- self$reorder_dendrogram(statistics, self$data)\n }\n if (!is.null(self$k) || !is.null(self$h) || !is.null(self$cutree)) {\n if (is.null(cutree <- self$cutree)) {\n cutree <- function(tree, dist, k, h) {\n if (!is.null(k)) {\n stats::cutree(tree, k = k)\n } else {\n stats::cutree(tree, h = h)\n }\n }\n }\n # we need `hclust` object to cutree\n statistics <- stats::as.hclust(statistics)\n panel <- cutree(statistics, distance, self$k, self$h)\n # For `cutree`, we always respect the height user specified\n # For user defined function, we always calculate\n # height from the number of `panels`\n if (isTRUE(self$plot_cut_height)) {\n self$height <- self$h %||% cutree_k_to_h(\n statistics, vec_unique_count(panel)\n )\n }\n }\n }\n # save the modified `statistics`\n self$statistics <- statistics\n if (self$multiple_tree) {\n index <- unlist(lapply(statistics, order2), FALSE, FALSE)\n } else {\n index <- order2(statistics)\n }\n # reorder panel factor levels to following the dendrogram order\n if (!is.null(panel)) {\n panel <- factor(panel, unique(panel[index]))\n # save panel information, in case of user change it\n self$panel <- panel\n }\n list(panel, index)\n },\n summary_align = function(self, ...) {\n c(TRUE, !is.null(self$k) || !is.null(self$h) || !is.null(self$cutree))\n }\n)\n\n#' Generate Tree Structures with Hierarchical Clustering\n#'\n#' @param matrix A numeric matrix, or data frame.\n#' @param distance A string of distance measure to be used. This must be one of\n#' `\"euclidean\"`, `\"maximum\"`, `\"manhattan\"`, `\"canberra\"`, `\"binary\"` or\n#' `\"minkowski\"`. Correlation coefficient can be also used, including\n#' `\"pearson\"`, `\"spearman\"` or `\"kendall\"`. In this way, `1 - cor` will be used\n#' as the distance. In addition, you can also provide a [`dist`][stats::dist]\n#' object directly or a function return a [`dist`][stats::dist] object. Use\n#' `NULL`, if you don't want to calculate the distance.\n#' @param method A string of the agglomeration method to be used. This should be\n#' (an unambiguous abbreviation of) one of `\"ward.D\"`, `\"ward.D2\"`, `\"single\"`,\n#' `\"complete\"`, `\"average\"` (= UPGMA), `\"mcquitty\"` (= WPGMA), `\"median\"` (=\n#' WPGMC) or `\"centroid\"` (= UPGMC). You can also provide a function which\n#' accepts the calculated distance (or the input matrix if `distance` is `NULL`)\n#' and returns a [`hclust`][stats::hclust] object. Alternative, you can supply\n#' an object which can be coerced to [`hclust`][stats::hclust].\n#' @param use_missing An optional character string giving a method for computing\n#' covariances in the presence of missing values. This must be (an abbreviation\n#' of) one of the strings `\"everything\"`, `\"all.obs\"`, `\"complete.obs\"`,\n#' `\"na.or.complete\"`, or `\"pairwise.complete.obs\"`. Only used when `distance`\n#' is a correlation coefficient string.\n#' @seealso\n#' - [cor()][stats::cor]\n#' - [dist()][stats::dist]\n#' - [hclust()][stats::hclust]\n#' @examples\n#' hclust2(dist(USArrests), method = \"ward.D\")\n#' @return A [hclust][stats::hclust] object.\n#' @importFrom rlang is_string try_fetch\n#' @export\nhclust2 <- function(matrix, distance = \"euclidean\", method = \"complete\",\n use_missing = \"pairwise.complete.obs\") {\n method <- allow_lambda(method)\n if (!is_string(method) && !is.function(method)) {\n ans <- try_fetch(\n stats::as.hclust(method),\n error = function(cnd) {\n cli_abort(paste(\n \"{.arg method} can only be a {.cls string},\",\n \"{.cls function} or an object which can be coerced to\",\n \"{.cls hclust}.\"\n ), parent = cnd)\n }\n )\n return(ans)\n }\n if (is.null(distance)) {\n d <- matrix\n } else {\n d <- make_dist(matrix, distance, use_missing)\n }\n if (is_string(method)) {\n ans <- stats::hclust(d, method = method)\n } else if (is.function(method)) {\n ans <- method(d)\n ans <- try_fetch(\n stats::as.hclust(ans),\n error = function(cnd) {\n cli_abort(paste(\n \"{.arg method} must return an object which\",\n \"can be coerced to {.cls hclust}\"\n ), parent = cnd)\n }\n )\n }\n if (!is.null(distance)) attr(ans, \"distance\") <- d\n ans\n}\n\n#' @importFrom rlang arg_match0\nmake_dist <- function(matrix, distance, use_missing,\n arg = caller_arg(distance), call = caller_call()) {\n distance <- allow_lambda(distance)\n if (is_string(distance)) {\n distance <- arg_match0(distance, c(\n \"euclidean\", \"maximum\", \"manhattan\", \"canberra\",\n \"binary\", \"minkowski\", \"pearson\", \"spearman\", \"kendall\"\n ), arg_nm = arg, error_call = call)\n d <- switch(distance,\n euclidean = ,\n maximum = ,\n manhattan = ,\n canberra = ,\n binary = ,\n minkowski = stats::dist(matrix, method = distance),\n pearson = ,\n spearman = ,\n kendall = stats::as.dist(\n 1 - stats::cor(t(matrix), use = use_missing, method = distance)\n ),\n cli_abort(\"Unsupported {.arg {arg}} specified\", call = call)\n )\n } else if (is.function(distance)) {\n if (!inherits(d <- distance(matrix), \"dist\")) {\n cli_abort(\n \"{.arg {arg}} must return a {.cls dist} object\",\n call = call\n )\n }\n } else if (inherits(distance, \"dist\")) {\n d <- distance\n } else {\n cli_abort(paste(\n \"{.arg {arg}} can only be a {.cls string}, {.cls dist}\",\n \"object, or a {.cls function} return {.cls dist}\"\n ), call = call)\n }\n d\n}\n\ncutree_k_to_h <- function(tree, k) {\n if (is.null(n1 <- nrow(tree$merge)) || n1 < 1) {\n cli_abort(\"invalid {.arg tree} ({.field merge} component)\")\n }\n n <- n1 + 1\n if (is.unsorted(tree$height)) {\n cli_abort(\n \"the 'height' component of 'tree' is not sorted (increasingly)\"\n )\n }\n mean(tree$height[c(n - k, n - k + 1L)])\n}\n"], ["/ggalign/R/layout-quad-.R", "#' Arrange plots in the quad-side of a main plot\n#'\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' This function arranges plots around the quad-sides of a main plot, aligning\n#' both horizontal and vertical axes, and can handle either discrete or\n#' continuous variables.\n#'\n#' - If `xlim` is provided, a continuous variable will be required and aligned\n#' in the vertical direction. Otherwise, a discrete variable will be required\n#' and aligned.\n#' - If `ylim` is provided, a continuous variable will be required and aligned\n#' in the horizontal direction. Otherwise, a discrete variable will be\n#' required and aligned.\n#'\n#' The `quad_discrete` is a special case where both `xlim` and `ylim` are not\n#' provided.\n#'\n#' The `quad_continuous` is a special case where both `xlim` and `ylim` are\n#' provided.\n#'\n#' For historical reasons, the following aliases are available:\n#' - `quad_alignh`: Align discrete variables in the horizontal direction and\n#' continuous variables in vertical direction.\n#' - `quad_alignv`: Align discrete variables in the vertical direction and\n#' continuous variables in horizontal direction.\n#' - `quad_alignb` is an alias for `quad_discrete`.\n#' - `quad_free` is an alias for `quad_continuous`.\n#'\n#' @param data `r rd_layout_data()`. By default, this will attempt\n#' to inherit from the parent layout.\n#'\n#' If both `xlim` and `ylim` are provided, a `data frame` is required, and\n#' [`fortify_data_frame()`] will be used to convert the data to a data frame.\n#' When inherited by an annotation stack, no transposition will be applied.\n#'\n#' Otherwise, a `matrix` is required, and [`fortify_matrix()`] will be used to\n#' convert the data to a matrix. When inherited by the column annotation\n#' stack, the data will be transposed.\n#' @param mapping Default list of aesthetic mappings to use for main plot in the\n#' layout. If not specified, must be supplied in each layer added to the main\n#' plot.\n#' @param xlim,ylim A [`continuous_limits()`] object specifying the left/lower\n#' limit and the right/upper limit of the scale. Used to align the continuous\n#' axis.\n#' @param width,height The relative width/height of the main plot, can be a\n#' [`unit`][grid::unit] object.\n#' @inheritParams stack_layout\n#' @inheritParams align\n#' @return A `QuadLayout` object.\n#' @section ggplot2 specification:\n#' If either `xlim` or `ylim` is not provided, the data input will be converted\n#' to a matrix using [`fortify_matrix()`], and the data in the underlying main\n#' plot will contain the following columns:\n#'\n#' - `.panel_x` and `.panel_y`: the column and row panel groups.\n#'\n#' - `.x` and `.y`: an integer index of `x` and `y` coordinates\n#'\n#' - `.discrete_x` and `.discrete_y`: a factor of the data labels (only\n#' applicable when `.row_names` and `.column_names` exists).\n#'\n#' - `.row_names` and `.column_names`: A character of the row and column names\n#' of the original matrix (only applicable when names exist).\n#'\n#' - `.row_index` and `.column_index`: the row and column index of the original\n#' matrix.\n#'\n#' - `value`: the actual matrix value.\n#'\n#' Otherwise, the data input will be used for the main plot.\n#'\n#' @export\nquad_layout <- function(data = waiver(), mapping = aes(),\n xlim = waiver(), ylim = waiver(),\n ...,\n theme = NULL, active = NULL,\n width = NA, height = NA) {\n if (is.waive(xlim) && is.waive(ylim)) {\n quad_discrete(\n data = data, mapping = mapping,\n ..., active = active, theme = theme,\n width = width, height = height\n )\n } else if (!is.waive(xlim) && !is.waive(ylim)) {\n quad_continuous(\n data = data, mapping = mapping, xlim = xlim, ylim = ylim,\n ..., active = active, theme = theme,\n width = width, height = height\n )\n } else {\n data <- fortify_matrix(data = data, ...)\n new_quad_layout(\n name = \"quad_layout\",\n data = data, ylim = ylim, xlim = xlim,\n mapping = mapping, active = active, theme = theme,\n width = width, height = height\n )\n }\n}\n\n#' @export\n#' @rdname quad_layout\nquad_alignh <- function(..., ylim = waiver()) {\n quad_layout(..., xlim = NULL, ylim = ylim)\n}\n\n#' @export\n#' @rdname quad_layout\nquad_alignv <- function(..., xlim = waiver()) {\n quad_layout(..., xlim = xlim, ylim = NULL)\n}\n\n##########################################################\n#' @export\n#' @rdname quad_layout\nquad_discrete <- function(data = waiver(), mapping = aes(),\n ...,\n theme = NULL, active = NULL,\n width = NA, height = NA) {\n UseMethod(\"quad_discrete\")\n}\n\n#' @export\n#' @rdname quad_layout\n#' @usage NULL\nquad_alignb <- quad_discrete\n\n#' @export\nquad_discrete.default <- function(data = waiver(), mapping = aes(),\n ...,\n theme = NULL, active = NULL,\n width = NA, height = NA) {\n data <- fortify_matrix(data = data, ...)\n new_quad_layout(\n name = \"quad_discrete\", data = data, xlim = waiver(), ylim = waiver(),\n mapping = mapping, active = active, theme = theme,\n width = width, height = height\n )\n}\n\n#' @export\nquad_discrete.uneval <- function(data, ...) {\n cli_abort(c(\n \"{.arg data} cannot be {.obj_type_friendly {data}}\",\n \"i\" = \"Have you misspelled the {.arg data} argument in {.fn quad_discrete}\"\n ))\n}\n\n#############################################################\n#' @export\n#' @rdname quad_layout\nquad_continuous <- function(data = waiver(), mapping = aes(),\n xlim = NULL, ylim = NULL,\n ...,\n theme = NULL, active = NULL,\n width = NA, height = NA) {\n UseMethod(\"quad_continuous\")\n}\n\n#' @usage NULL\n#' @export\n#' @rdname quad_layout\nggside <- quad_continuous\n\n#' @usage NULL\n#' @export\n#' @rdname quad_layout\nquad_free <- quad_continuous\n\n#' @export\nquad_continuous.default <- function(data = waiver(), mapping = aes(),\n xlim = NULL, ylim = NULL,\n ...,\n theme = NULL, active = NULL,\n width = NA, height = NA) {\n xlim <- xlim %|w|% NULL\n ylim <- ylim %|w|% NULL\n data <- fortify_data_frame(data = data, ...)\n new_quad_layout(\n name = \"quad_continuous\",\n data = data, xlim = xlim, ylim = ylim,\n mapping = mapping, active = active, theme = theme,\n width = width, height = height\n )\n}\n\n#' @export\nquad_continuous.uneval <- function(data, ...) {\n cli_abort(c(\n \"{.arg data} cannot be {.obj_type_friendly {data}}\",\n \"i\" = \"Have you misspelled the {.arg data} argument in {.fn quad_free}\"\n ))\n}\n\n#####################################################\n#' @importFrom ggplot2 ggplot\n#' @importFrom methods new\nnew_quad_layout <- function(name, data, xlim = waiver(), ylim = waiver(),\n mapping = aes(), theme = NULL, active = NULL,\n width = NA, height = NA,\n class = \"QuadLayout\",\n call = caller_call()) {\n if (!is.waive(xlim)) assert_limits(xlim, call = call)\n if (!is.waive(ylim)) assert_limits(ylim, call = call)\n if (is.waive(xlim) || is.waive(ylim)) {\n # If we need align discrete variables, data cannot be `NULL` and\n # must be provided, here, we convert it to waiver() to indicate\n # inherit from the parent layout\n data <- data %||% waiver()\n if (!is.waive(data) && !is.function(data)) {\n nrows <- NROW(data)\n ncols <- ncol(data)\n\n # for data has dimention but one dimention is 0\n # as.matrix(data.frame(row.names = letters))\n if (nrows == 0L || ncols == 0L) {\n cli_abort(\"empty data is no allowed\")\n }\n } else {\n nrows <- NULL\n ncols <- NULL\n }\n }\n horizontal <- ylim %|w|% discrete_design(nobs = nrows)\n vertical <- xlim %|w|% discrete_design(nobs = ncols)\n\n # always remove default axis titles\n # https://stackoverflow.com/questions/72402570/why-doesnt-gplot2labs-overwrite-update-the-name-argument-of-scales-function\n # There are multiple ways to set labels in a plot, which take different\n # priorities. Here are the priorities from highest to lowest.\n # 1. The guide title.\n # 2. The scale name.\n # 3. The `labs()` function.\n # 4. The captured expression in aes().\n plot <- ggplot(mapping = mapping) +\n ggplot2::labs(x = NULL, y = NULL)\n\n if (!is.null(theme)) assert_s3_class(theme, \"theme\", call = call)\n # for `QuadLayout`, we use `NULL` to inherit data from parent layout\n # since `QuadLayout` must have data, and won't be waiver()\n # if inherit from the parent layout data, we'll inherit\n # the action data function\n schemes <- default_schemes(\n if (is.null(data)) waiver() else NULL,\n th = theme_no_strip()\n )\n\n # check arguments -----------------------------------\n width <- check_size(width, call = call)\n height <- check_size(height, call = call)\n assert_active(active, call = call)\n\n # Here we use S4 object to override the double dispatch of `+.gg` method\n new(\n class,\n # used by the layout\n data = data, theme = theme,\n schemes = schemes,\n plot_active = update_active(active, new_active(use = TRUE)),\n name = name,\n # used by the main body\n body_schemes = default_schemes(waiver()),\n # following parameters can be controlled by `quad_switch`\n width = width, height = height,\n # following parameters are used internally\n plot = plot, horizontal = horizontal, vertical = vertical\n )\n}\n\n# Used to create the QuadLayout\n#' @include layout-.R\nmethods::setClass(\n \"QuadLayout\",\n contains = \"LayoutProto\",\n list(\n data = \"ANY\", plot = \"ANY\", body_schemes = \"list\", name = \"character\",\n # parameters for main body\n width = \"ANY\", height = \"ANY\",\n # Used to align axis\n horizontal = \"ANY\", vertical = \"ANY\",\n # top, left, bottom, right must be a StackLayout object.\n top = \"ANY\", left = \"ANY\", bottom = \"ANY\", right = \"ANY\",\n # If we regard `QuadLayout` as a plot, and put it into the stack\n # layout, we need following arguments to control it's behavour\n plot_active = \"ANY\"\n ),\n prototype = list(\n # used by QuadLayout\n top = NULL, left = NULL, bottom = NULL, right = NULL\n )\n)\n\n#' @export\nis_layout_discrete.QuadLayout <- function(x, direction, ...) {\n is_discrete_design(slot(x, direction))\n}\n\n#' @export\nis_layout_continuous.QuadLayout <- function(x, direction, ...) {\n is_continuous_design(slot(x, direction))\n}\n"], ["/ggalign/R/craft-align-order.R", "#' Order observations based on weights\n#'\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' Ordering observations based on summary weights or a specified ordering\n#' character or integer index.\n#'\n#' @param weights A summary function which accepts a data and returns the\n#' weights for each observations. Alternatively, you can provide an ordering\n#' index as either an integer or a character. Since characters have been\n#' designated as character indices, if you wish to specify a function name as a\n#' string, you must enclose it with [`I()`].\n#' @param ... <[dyn-dots][rlang::dyn-dots]> Additional arguments passed to\n#' function provided in `weights` argument.\n#' @param reverse A boolean value. Should the sort order be in reverse?\n#' @param strict A boolean value indicates whether the order should be strict.\n#' If previous groups has been established, and strict is `FALSE`, this will\n#' reorder the observations in each group.\n#' @param data A `matrix`, `data frame`, or atomic vector used as the input for\n#' the `weights` function. Alternatively, you can specify a `function`\n#' (including purrr-like lambda syntax) that will be applied to the layout\n#' matrix, transforming it as necessary for weight calculations. By default, it\n#' will inherit from the layout matrix.\n#' @inheritParams align\n#' @inheritSection align Discrete Axis Alignment\n#' @examples\n#' ggheatmap(matrix(rnorm(81), nrow = 9)) +\n#' anno_left() +\n#' align_order(I(\"rowMeans\"))\n#' @importFrom ggplot2 waiver\n#' @importFrom rlang list2\n#' @export\nalign_order <- function(weights = rowMeans, ...,\n reverse = FALSE, strict = TRUE, data = NULL,\n active = NULL) {\n if (is.numeric(weights) ||\n (is.character(weights) && !inherits(weights, \"AsIs\"))) {\n # vec_duplicate_any is slight faster than `anyDuplicated`\n if (vec_any_missing(weights) || vec_duplicate_any(weights)) {\n cli_abort(paste(\n \"{.arg weights} must be an ordering numeric or character\",\n \"without missing value or ties\"\n ))\n } else if (is.numeric(weights)) {\n weights <- vec_cast(weights, integer())\n }\n if (vec_size(weights) == 0L) {\n cli_abort(\"{.arg weights} cannot be empty\")\n }\n if (!is.null(data)) {\n cli_warn(c(\n \"{.arg data} won't be used\",\n i = \"{.arg weights} is not a {.cls function}\"\n ))\n }\n } else {\n weights <- rlang::as_function(weights)\n data <- data %||% waiver()\n }\n assert_bool(strict)\n assert_bool(reverse)\n assert_active(active)\n active <- update_active(active, new_active(use = FALSE))\n align(\n align = AlignOrder,\n weights = weights,\n params = list2(...),\n reverse = reverse,\n strict = strict,\n active = active,\n data = data\n )\n}\n\n#' @importFrom ggplot2 ggproto\n#' @importFrom rlang inject is_atomic\nAlignOrder <- ggproto(\"AlignOrder\", CraftAlign,\n interact_layout = function(self, layout) {\n if (is.function(self$weights)) {\n layout <- ggproto_parent(AlignOrder2, self)$interact_layout(layout)\n } else {\n layout <- ggproto_parent(CraftAlign, self)$interact_layout(layout)\n if (is.null(layout_nobs <- .subset2(layout@design, \"nobs\"))) {\n layout@design[\"nobs\"] <- list(vec_size(self$weights))\n } else {\n assert_mismatch_nobs(\n self, layout_nobs, vec_size(self$weights),\n arg = \"weights\"\n )\n }\n self$labels <- vec_names(layout@data)\n }\n layout\n },\n compute = function(self, panel, index) {\n if (is.function(self$weights)) {\n ans <- inject(self$weights(self$data, !!!self$params))\n if (!is_atomic(ans)) {\n cli_abort(\n \"{.arg weights} must return an atomic weights\",\n call = self$call\n )\n }\n assert_mismatch_nobs(\n self, vec_size(ans), vec_size(ans),\n arg = \"weights\"\n )\n ans\n }\n },\n align = function(self, panel, index) {\n if (is.function(self$weights)) {\n index <- order(self$statistics)\n } else {\n index <- vec_as_location(\n self$weights,\n n = vec_size(self$weights),\n names = self$labels,\n missing = \"error\",\n call = self$call\n )\n }\n if (self$reverse) index <- rev(index)\n assert_reorder(self, panel, index, self$strict)\n list(panel, index)\n },\n summary_align = function(self) c(TRUE, FALSE)\n)\n"], ["/ggalign/R/layout-chain-circle-.R", "#' Arrange plots in a circular layout\n#'\n#' @description\n#' `r lifecycle::badge('experimental')`\n#'\n#' If `limits` is provided, a continuous variable will be required and aligned\n#' in the direction specified (`circle_continuous`). Otherwise, a discrete\n#' variable will be required and aligned (`circle_discrete`).\n#'\n#' @param radial A [`coord_circle()`]/[`coord_radial()`][ggplot2::coord_radial]\n#' object that defines the global parameters for coordinate across all plots\n#' in the layout. The parameters `start`, `end`, `direction`, and `expand` will\n#' be inherited and applied uniformly to all plots within the layout. The\n#' parameters `theta` and `r.axis.inside` will always be ignored and will be set\n#' to `\"x\"` and `TRUE`, respectively, for all plots.\n#' @param direction A single string of `r oxford_or(c(\"inward\", \"outward\"))`,\n#' indicating the direction in which the plot is added.\n#' - `outward`: The plot is added from the inner to the outer.\n#' - `inward`: The plot is added from the outer to the inner.\n#' @inheritParams stack_layout\n#' @return A `CircleLayout` object.\n#' @examples\n#' set.seed(123)\n#'\n#' small_mat <- matrix(rnorm(56), nrow = 7)\n#' rownames(small_mat) <- paste0(\"row\", seq_len(nrow(small_mat)))\n#' colnames(small_mat) <- paste0(\"column\", seq_len(ncol(small_mat)))\n#'\n#' # circle_layout\n#' # same for circle_discrete()\n#' circle_layout(small_mat) +\n#' ggalign() +\n#' geom_tile(aes(y = .column_index, fill = value)) +\n#' scale_fill_viridis_c() +\n#' align_dendro(aes(color = branch), k = 3L) +\n#' scale_color_brewer(palette = \"Dark2\")\n#'\n#' # same for circle_continuous()\n#' circle_layout(mpg, limits = continuous_limits(c(3, 5))) +\n#' ggalign(mapping = aes(displ, hwy, colour = class)) +\n#' geom_point(size = 2) +\n#' ggalign(mapping = aes(displ, hwy, colour = class)) +\n#' geom_point(size = 2) &\n#' scale_color_brewer(palette = \"Dark2\") &\n#' theme_bw()\n#'\n#' @export\ncircle_layout <- function(data = NULL, ..., radial = NULL,\n direction = \"outward\", sector_spacing = NULL,\n limits = waiver(), theme = NULL,\n spacing_theta = deprecated()) {\n if (is.waive(limits)) {\n circle_discrete(\n data = data, ..., radial = radial,\n direction = direction, sector_spacing = sector_spacing,\n theme = theme, spacing_theta = spacing_theta\n )\n } else {\n circle_continuous(\n data = data, ..., radial = radial,\n direction = direction, theme = theme, limits = limits,\n spacing_theta = spacing_theta\n )\n }\n}\n\n############################################################\n#' @inheritParams facet_sector\n#' @examples\n#' # circle_discrete()\n#' # direction outward\n#' circle_discrete(small_mat) +\n#' align_dendro(aes(color = branch), k = 3L) +\n#' scale_color_brewer(palette = \"Dark2\") +\n#' ggalign() +\n#' geom_tile(aes(y = .column_index, fill = value)) +\n#' scale_fill_viridis_c()\n#'\n#' # direction inward\n#' circle_discrete(small_mat, direction = \"inward\") +\n#' ggalign() +\n#' geom_tile(aes(y = .column_index, fill = value)) +\n#' scale_fill_viridis_c() +\n#' align_dendro(aes(color = branch), k = 3L) +\n#' scale_color_brewer(palette = \"Dark2\")\n#'\n#' @export\n#' @rdname circle_layout\ncircle_discrete <- function(data = NULL, ..., radial = NULL,\n direction = \"outward\", sector_spacing = NULL,\n theme = NULL, spacing_theta = deprecated()) {\n UseMethod(\"circle_discrete\", data)\n}\n\n#' @export\ncircle_discrete.default <- function(data = NULL, ..., radial = NULL,\n direction = \"outward\",\n sector_spacing = NULL,\n theme = NULL,\n spacing_theta = deprecated()) {\n # the observations are rows, we use matrix to easily\n # reshape it into a long formated data frame for ggplot,\n # and we can easily determine the number of observations\n # from matrix\n data <- data %|w|% NULL\n data <- fortify_matrix(data = data, ...)\n schemes <- default_schemes()\n if (!is.null(data) && !is.function(data)) {\n # if we have provided data, we initialize the `nobs`\n nobs <- vec_size(data)\n } else {\n nobs <- NULL\n }\n new_circle_layout(\n data = data,\n design = discrete_design(nobs = nobs),\n radial = radial, direction = direction, sector_spacing = sector_spacing,\n schemes = schemes, theme = theme, spacing_theta = spacing_theta\n )\n}\n\n#' @export\ncircle_discrete.function <- function(data = NULL, ...) {\n cli_abort(paste0(\n \"{.arg data} must be a {.cls matrix}, \",\n \"or an object coercible by {.fn fortify_matrix}, or a valid \",\n \"{.cls matrix}-like object coercible by {.fn as.matrix}\"\n ))\n}\n\n#' @export\ncircle_discrete.formula <- circle_discrete.function\n\n################################################################\n#' @examples\n#' # circle_continuous()\n#' circle_continuous(mpg, limits = continuous_limits(c(3, 5))) +\n#' ggalign(mapping = aes(displ, hwy, colour = class)) +\n#' geom_point(size = 2) +\n#' ggalign(mapping = aes(displ, hwy, colour = class)) +\n#' geom_point(size = 2) &\n#' scale_color_brewer(palette = \"Dark2\") &\n#' theme_bw()\n#' @export\n#' @rdname circle_layout\ncircle_continuous <- function(data = NULL, ..., radial = NULL,\n direction = \"outward\", sector_spacing = NULL,\n limits = NULL, theme = NULL,\n spacing_theta = deprecated()) {\n UseMethod(\"circle_continuous\", data)\n}\n\n#' @export\ncircle_continuous.default <- function(data = NULL, ..., radial = NULL,\n direction = \"outward\",\n sector_spacing = NULL,\n limits = NULL, theme = NULL,\n spacing_theta = deprecated()) {\n assert_limits(limits)\n data <- data %|w|% NULL\n data <- fortify_data_frame(data = data, ...)\n schemes <- default_schemes()\n new_circle_layout(\n data = data, design = limits,\n radial = radial, direction = direction, sector_spacing = sector_spacing,\n schemes = schemes, theme = theme, spacing_theta = spacing_theta\n )\n}\n\n#' @export\ncircle_continuous.function <- function(data = NULL, ...) {\n cli_abort(paste0(\n \"{.arg data} must be a {.cls data.frame}, \",\n \"or an object coercible by {.fn fortify_data_frame}, or a valid \",\n \"{.cls data.frame}-like object coercible by {.fn as.data.frame}\"\n ))\n}\n\n#' @export\ncircle_continuous.formula <- circle_continuous.function\n\n#' @importFrom methods new\nnew_circle_layout <- function(data, design, radial, direction,\n sector_spacing = NULL, schemes = NULL,\n theme = NULL, name = NULL,\n spacing_theta = deprecated(),\n call = caller_call()) {\n if (!is.null(theme)) assert_s3_class(theme, \"theme\", call = call)\n if (!is.null(radial) && !inherits(radial, c(\"CoordRadial\"))) {\n cli_abort(\"{.arg radial} must be created with {.fn coord_circle}\",\n call = call\n )\n }\n if (!is.null(radial) && abs(diff(radial$arc)) < pi / 2L) {\n cli_abort(\n \"Cannot create circle of acute angle < 90 in {.arg radial}\",\n call = call\n )\n }\n direction <- arg_match0(direction, c(\"inward\", \"outward\"))\n if (is.null(name)) {\n if (is_continuous_design(design)) {\n name <- \"circle_continuous\"\n } else {\n name <- \"circle_discrete\"\n }\n }\n if (lifecycle::is_present(spacing_theta)) {\n lifecycle::deprecate_warn(\n \"1.0.2\",\n \"facet_sector(spacing_theta = )\",\n \"facet_sector(sector_spacing = )\"\n )\n if (is.null(sector_spacing)) sector_spacing <- spacing_theta\n }\n new(\n \"CircleLayout\",\n name = name, data = data,\n schemes = schemes, # used by the layout\n design = design,\n sector_spacing = sector_spacing,\n theme = theme,\n radial = radial, direction = direction\n )\n}\n\n############################################################\n# Used to place multiple objects in one axis\n#' @importFrom grid unit\n#' @importFrom ggplot2 waiver\n#' @keywords internal\n#' @include layout-chain-.R\nmethods::setClass(\"CircleLayout\",\n contains = \"ChainLayout\",\n list(radial = \"ANY\", sector_spacing = \"ANY\", direction = \"character\")\n)\n"], ["/ggalign/R/alignpatch-free-align.R", "#' Free from alignment\n#'\n#' [align_plots] will try to align plot panels, and every elements of the plot,\n#' following functions romove these restrictions:\n#' - `free_align`: if we want to compose plots without alignment of some panel\n#' axes (panel won't be aligned). we can wrap the plot with `free_align`.\n#' - `free_border`: attaches borders (e.g., axis titles, tick marks) directly to\n#' the plot panel. This keeps them visually close to the panel during\n#' alignment.\n#' - `free_lab()`: Similar to `free_border()`, but only attaches axis titles\n#' and tick labels, not full borders. It’s mainly included for completeness;\n#' in most cases, combining `free_border()` and `free_space()` is sufficient.\n#' - `free_space`: Removing the ggplot element sizes when aligning.\n#' - `free_vp`: Customize the [viewport][grid::viewport] when aligning.\n#' - `free_guide`: If we want to override the behaviour of the overall guides\n#' behaviour, we can wrap the plot with `free_guide`.\n#'\n#' @param plot A [ggplot][ggplot2::ggplot] or [alignpatches][align_plots]\n#' object.\n#' @param axes Which axes shouldn't be aligned? A string containing\n#' one or more of `r oxford_and(.tlbr)`.\n#' @return\n#' - `free_align`: A modified version of `plot` with a `free_align` class.\n#' @examples\n#' # directly copied from `patchwork`\n#' # Sometimes you have a plot that defies good composition alginment, e.g. due\n#' # to long axis labels\n#' p1 <- ggplot(mtcars) +\n#' geom_bar(aes(y = factor(gear), fill = factor(gear))) +\n#' scale_y_discrete(\n#' \"\",\n#' labels = c(\n#' \"3 gears are often enough\",\n#' \"But, you know, 4 is a nice number\",\n#' \"I would def go with 5 gears in a modern car\"\n#' )\n#' )\n#'\n#' # When combined with other plots it ends up looking bad\n#' p2 <- ggplot(mtcars) +\n#' geom_point(aes(mpg, disp))\n#'\n#' align_plots(p1, p2, ncol = 1L)\n#'\n#' # We can fix this be using `free_align`\n#' align_plots(free_align(p1), p2, ncol = 1L)\n#'\n#' # If we still want the panels to be aligned to the right, we can choose to\n#' # free only the left side\n#' align_plots(free_align(p1, axes = \"l\"), p2, ncol = 1L)\n#'\n#' # We could use `free_lab` to fix the layout in a different way\n#' align_plots(p1, free_lab(p2), ncol = 1L)\n#'\n#' # `free_border` is similar with `free_lab`, they have a distinction in terms\n#' # of placement on either the top or bottom side of the panel. Specifically,\n#' # the top side contains the `title` and `subtitle`, while the bottom side\n#' # contains the `caption`. free_lab() does not attach these elements in the\n#' # panel area.\n#' p3 <- ggplot(mtcars) +\n#' geom_point(aes(hp, wt, colour = mpg)) +\n#' ggtitle(\"Plot 3\")\n#' p_axis_top <- ggplot(mtcars) +\n#' geom_point(aes(mpg, disp)) +\n#' ggtitle(\"Plot axis in top\") +\n#' scale_x_continuous(position = \"top\")\n#' align_plots(p_axis_top, free_lab(p3))\n#' align_plots(p_axis_top, free_border(p3))\n#'\n#' # Another issue is that long labels can occupy much spaces\n#' align_plots(NULL, p1, p2, p2)\n#'\n#' # This can be fixed with `free_space`\n#' align_plots(NULL, free_space(p1, \"l\"), p2, p2)\n#'\n#' @export\n#' @rdname free\nfree_align <- function(plot, axes = \"tlbr\") {\n UseMethod(\"free_align\")\n}\n\n# free_guides: set_guides\n# free_lab: collect_guides\n# free_border: collect_guides and align_border\n# free_space: get_sizes\n# free_align: get_sizes and align_border\n# free_vp: align_border\n\n#' @export\nfree_align.ggplot <- function(plot, axes = \"tlbr\") {\n assert_position(axes)\n attr(plot, \"free_axes\") <- axes\n add_class(plot, \"free_align\")\n}\n\n#' @export\nfree_align.alignpatches <- free_align.ggplot\n\n#' @importFrom rlang is_empty\n#' @export\nfree_align.free_lab <- function(plot, axes = \"tlbr\") {\n assert_position(axes)\n # if axes are free, it's not necessary to free the labs\n free_labs <- setdiff_position(attr(plot, \"free_labs\"), axes)\n if (nzchar(free_labs)) {\n attr(plot, \"free_labs\") <- free_labs\n } else {\n attr(plot, \"free_labs\") <- NULL\n plot <- remove_class(plot, \"free_lab\")\n }\n NextMethod()\n}\n\n#' @importFrom rlang is_empty\n#' @export\nfree_align.free_space <- function(plot, axes = \"tlbr\") {\n assert_position(axes)\n free_spaces <- setdiff_position(attr(plot, \"free_spaces\"), axes)\n if (nzchar(free_spaces)) {\n attr(plot, \"free_spaces\") <- free_spaces\n } else {\n attr(plot, \"free_spaces\") <- NULL\n plot <- remove_class(plot, \"free_space\")\n }\n NextMethod()\n}\n\n#' @importFrom rlang is_empty\n#' @export\nfree_align.free_border <- function(plot, axes = \"tlbr\") {\n assert_position(axes)\n free_borders <- setdiff_position(attr(plot, \"free_borders\"), axes)\n if (nzchar(free_borders)) {\n attr(plot, \"free_borders\") <- free_borders\n } else {\n attr(plot, \"free_borders\") <- NULL\n plot <- remove_class(plot, \"free_border\")\n }\n NextMethod()\n}\n\n#' @export\nfree_align.free_align <- function(plot, axes = \"tlbr\") {\n assert_position(axes)\n attr(plot, \"free_axes\") <- union_position(attr(plot, \"free_axes\"), axes)\n plot\n}\n\n#' @export\nfree_align.default <- function(plot, axes = \"tlbr\") {\n cli_abort(\"Cannot use with {.obj_type_friendly {plot}}\")\n}\n\n#' @importFrom ggplot2 ggproto ggproto_parent\n#' @export\nalignpatch.free_align <- function(x) {\n Parent <- NextMethod()\n ggproto(\n \"PatchFreeAlign\", Parent,\n free_axes = split_position(attr(x, \"free_axes\")),\n get_sizes = function(self, free = NULL, gt = self$gt) {\n ggproto_parent(Parent, self)$get_sizes(\n union(free, self$free_axes),\n gt = gt\n )\n },\n align_border = function(self, t = NULL, l = NULL, b = NULL, r = NULL,\n gt = self$gt) {\n for (axis in self$free_axes) {\n assign(x = axis, value = NULL, envir = environment())\n }\n ggproto_parent(Parent, self)$align_border(\n t = t, l = l, b = b, r = r, gt = gt\n )\n }\n )\n}\n"], ["/ggalign/R/with_quad.R", "#' Modify operated Context in `quad_layout()`\n#'\n#' @description\n#' `r lifecycle::badge('experimental')`\n#'\n#' The `with_quad()` function modifies the application context of elements in\n#' `ggheatmap()`/`quad_layout()`. It controls how objects like themes, scales,\n#' or other plot modifications apply to specific annotation stacks or the main\n#' plot without altering the currently active layout or plot.\n#'\n#' @param x An object which can be added to the ggplot, including\n#' **schemes**. See [`scheme_align()`], [`scheme_data()`], and\n#' [`scheme_theme()`]\n#' @param position A string specifying one or more positions-\n#' `r oxford_and(.tlbr)`- to indicate the annotation stack context for `x`. If\n#' `NULL`, will change the operated context to the `quad_layout()` itself. For\n#' default behaivours, see `details` section.\n#' @param main A single boolean value indicating whether `x` should apply to the\n#' main plot, used only when `position` is not `NULL`. By default, if `position`\n#' is `waiver()` and the active context of `quad_layout()` is an annotation\n#' stack or the active context of `stack_layout()` is itself, `main` will be set\n#' to `TRUE`; otherwise, it defaults to `FALSE`.\n#' @return The original object with an added attribute that sets the specified\n#' context.\n#' @details\n#' Default Behavior when adding object wrapped with `with_quad()`:\n#'\n#' For `quad_layout()` object:\n#'\n#' - When `ggheatmap()`/`quad_layout()` has no active annotation stack, objects\n#' added via `+` or `-` operate normally without `with_quad()`.\n#' - When the active annotation stack is set, `with_quad()` ensures the applied\n#' object also modifies:\n#' * The main plot (by default).\n#' * Opposite annotation stacks when using `-`.\n#'\n#' For `stack_layout()` object:\n#'\n#' - When the active layout is the `stack_layout()` itself:\n#' * `-` operator will apply changes to all plots along the\n#' `stack_layout()`, which means if the stack layout is in `horizontal`,\n#' `-` operator will also add the element to the `left` and `right`\n#' annotation, if the stack layout is in `vertical`, `-` operator will\n#' also add element to the `top` and `bottom` annotation.\n#' * `+` operator won't do anything special.\n#' - When the active layout is the nested `ggheatmap()`/`quad_layout()`, the\n#' `+`/`-` operator applies the elements to this nested layout, following the\n#' same principles as for `ggheatmap()`/`quad_layout()`.\n#'\n#' @examples\n#' set.seed(123)\n#' small_mat <- matrix(rnorm(56), nrow = 7)\n#'\n#' # By wrapping object with `with_quad()`, the `+` operator will apply the\n#' # object not only to the active plot in the annotation stack, but also to\n#' # the main plot unless specified by `main` argument otherwise.\n#' ggheatmap(small_mat) +\n#' # initialize the left annotation\n#' anno_left(size = 0.2) +\n#' align_dendro() +\n#' # apply the object not only to the active plot in the annotation stack,\n#' # but also to the main plot\n#' with_quad(theme(plot.background = element_rect(fill = \"red\")))\n#'\n#' # the `-` operator will apply changes not only to the active annotation\n#' # stack but also to the opposite one (i.e., bottom if top is active, and\n#' # vice versa). The same principle applies to the left and right annotation.\n#' ggheatmap(small_mat) +\n#' anno_left(size = 0.2) +\n#' align_dendro(aes(color = branch), k = 3L) +\n#' # Change the active layout to the left annotation\n#' anno_top(size = 0.2) +\n#' align_dendro(aes(color = branch), k = 3L) +\n#' anno_bottom(size = 0.2) +\n#' align_dendro(aes(color = branch), k = 3L) -\n#' # Modify the color scale of all plots in the bottom and the opposite\n#' # annotation, in this way, the `main` argument by default would be `TRUE`\n#' with_quad(scale_color_brewer(palette = \"Dark2\", name = \"Top and bottom\"))\n#'\n#' # When the `position` argument is manually set, the\n#' # default value of the `main` argument will be `FALSE`.\n#' ggheatmap(small_mat) +\n#' anno_left(size = 0.2) +\n#' align_dendro(aes(color = branch), k = 3L) +\n#' anno_top(size = 0.2) +\n#' align_dendro(aes(color = branch), k = 3L) +\n#' anno_bottom(size = 0.2) +\n#' align_dendro(aes(color = branch), k = 3L) -\n#' # Modify the background of all plots in the left and top annotation\n#' with_quad(theme(plot.background = element_rect(fill = \"red\")), \"tl\")\n#' @export\nwith_quad <- function(x, position = waiver(), main = NULL) {\n UseMethod(\"with_quad\")\n}\n\n#' @export\nwith_quad.default <- function(x, position = waiver(), main = NULL) {\n assert_layout_position(position)\n assert_bool(main, allow_null = TRUE)\n structure(\n list(\n object = x,\n object_name = paste(deparse(substitute(x)), collapse = \" \"),\n position = position, main = main\n ),\n class = \"ggalign_with_quad\"\n )\n}\n\n#' @export\nprint.ggalign_with_quad <- function(x, ...) {\n print(.subset2(x, \"object\"))\n invisible(x)\n}\n\n#' @export\nwith_quad.CraftBox <- function(x, position = waiver(), main = NULL) {\n cli_abort(sprintf(\"Cannot used with %s\", object_name(x)))\n}\n\n#' @export\nwith_quad.layout_title <- function(x, position = waiver(), main = NULL) {\n cli_abort(\"Cannot used with {.obj_type_friendly {x}}\")\n}\n\n#' @export\nwith_quad.layout_theme <- with_quad.layout_title\n\n#' @export\nwith_quad.layout_annotation <- with_quad.layout_title\n\n#' @export\nwith_quad.quad_active <- with_quad.layout_title\n\n#' @export\nwith_quad.quad_anno <- with_quad.layout_title\n\n#' @export\nwith_quad.stack_switch <- with_quad.layout_title\n\nquad_operated_context <- function(with, active, operator) {\n if (is.waive(ans <- .subset2(with, \"position\"))) {\n if (operator == \"-\") {\n # if wrap with `with_quad`\n # we determine the `context` from current actual active position\n if (is.null(active)) {\n ans <- NULL\n } else {\n ans <- c(active, opposite_pos(active))\n if (is.null(main <- .subset2(with, \"main\")) || main) {\n ans <- c(ans, list(NULL))\n }\n }\n } else if (operator == \"+\") {\n ans <- active\n if (!is.null(ans)) {\n if (is.null(main <- .subset2(with, \"main\")) || main) {\n ans <- c(ans, list(NULL))\n }\n }\n } else {\n cli_abort(\"Not implement for {operator}\")\n }\n } else if (!is.null(ans)) { # if set manually\n ans <- setup_pos(ans)\n if (!is.null(main <- .subset2(with, \"main\")) && main) {\n ans <- c(ans, list(NULL))\n }\n }\n ans\n}\n\n#' @importFrom ggplot2 ggplot_add\n#' @export\nggplot_add.ggalign_with_quad <- function(object, plot, object_name, ...) {\n object <- .subset2(object, \"object\")\n object_name <- .subset2(object, \"object_name\")\n ggplot_add(object, plot, object_name)\n}\n"], ["/ggalign/R/craft-align-.R", "#' Create a New `CraftBox` Object with `CraftAlign` craftsman\n#'\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' An `CraftAlign` object interacts with the `Layout` object to reorder or split\n#' observations and, in some cases, add plot components to the `Layout`.\n#'\n#' @param align An `CraftAlign` object.\n#' @param ... Additional fields passed to the `align` object.\n#' @param plot A ggplot object.\n#' @inheritParams ggalign\n#' @param schemes Options for `schemes`:\n#' - `NULL`: Used when `align` do not add a plot.\n#' - [`waiver()`][ggplot2::waiver]: Try to infer `schemes` based on `data`.\n#' @param call The `call` used to construct the `align` object, for\n#' reporting messages.\n#'\n#' @section Discrete Axis Alignment:\n#' It is important to note that we consider rows as observations, meaning\n#' `vec_size(data)`/`NROW(data)` must match the number of observations along the\n#' axis used for alignment (x-axis for a vertical stack layout, y-axis for a\n#' horizontal stack layout).\n#'\n#' @return A new `CraftBox` object.\n#' @examples\n#' align_dendro()\n#' @importFrom rlang caller_call current_call\n#' @importFrom ggplot2 ggproto\n#' @export\n#' @keywords internal\nalign <- function(align, data = NULL, ..., plot = NULL,\n size = NULL, schemes = NULL, no_axes = NULL,\n active = NULL, call = caller_call()) {\n if (override_call(call)) {\n call <- current_call()\n }\n\n # check arguments ---------------------------------------------\n data <- allow_lambda(data)\n no_axes <- no_axes %||%\n getOption(sprintf(\"%s.align_no_axes\", pkg_nm()), default = TRUE)\n schemes <- schemes %|w|% default_schemes(data)\n\n new_craftbox(\n craftsman = align,\n\n # additional field for `align` object\n no_axes = no_axes,\n ...,\n\n # Following fields will be initialzed when added into the layout\n # and will be saved and accessed across the plot rendering process\n direction = NULL,\n position = NULL,\n data = NULL, # Used to save the modified `input_data`\n statistics = NULL, # `$compute` method\n labels = NULL, # the original `vec_names()` of the `input_data`\n\n # the input data\n input_data = data,\n\n # object slots\n plot = plot,\n active = active,\n size = size,\n schemes = schemes,\n\n # call\n call = call\n )\n}\n\n#' @details\n#' Each of the `Align*` objects is just a [`ggproto()`][ggplot2::ggproto]\n#' object, descended from the top-level `CraftAlign`, and each implements\n#' various methods and fields.\n#'\n#' To create a new type of `Align*` object, you typically will want to\n#' override one or more of the following:\n#' - `setup_params`: Prepare parameter or check parameters used by this plot.\n#' - `setup_data`: Prepare data used by this plot.\n#' - `compute`: A method used to compute statistics.\n#' - `align`: A method used to group observations into panel or reorder\n#' observations.\n#' - `draw`: A method used to draw the plot. Must return a `ggplot` object.\n#' @importFrom ggplot2 ggproto\n#' @export\n#' @format NULL\n#' @usage NULL\n#' @rdname align\n#' @include craftbox-.R\nCraftAlign <- ggproto(\"CraftAlign\", Craftsman,\n interact_layout = function(self, layout) {\n # check plot is compatible with the layout\n if (is_layout_continuous(layout)) {\n layout_name <- self$layout_name\n # `CraftAlign` object is special for discrete variables\n cli_abort(c(\n sprintf(\"Cannot add %s to %s\", object_name(self), layout_name),\n i = sprintf(\"%s cannot align discrete variables\", layout_name)\n ))\n }\n layout\n },\n setup_design = function(self, design) {\n old_panel <- .subset2(design, \"panel\")\n old_index <- .subset2(design, \"index\")\n # prepare the data -------------------------------\n # compute statistics ---------------------------------\n self$statistics <- self$compute(panel = old_panel, index = old_index)\n\n # make the new layout -------------------------------\n panel_and_index <- self$align(panel = old_panel, index = old_index)\n\n # check panel\n layout_name <- self$layout_name\n nobs <- .subset2(design, \"nobs\")\n new_panel <- .subset2(panel_and_index, 1L)\n if (!is.null(new_panel)) {\n if (!is.atomic(new_panel)) {\n cli_abort(c(\n sprintf(\n \"invalid layout panels defined by %s\",\n object_name(self)\n ),\n i = \"layout panels must be an atomic vector\"\n ))\n } else if (anyNA(new_panel)) {\n cli_abort(sprintf(\n \"layout panels defined by %s contain `NA`\",\n object_name(self)\n ))\n } else if (is.null(nobs)) {\n # we have defined panel, but don't define the `nobs`\n cli_abort(sprintf(\n \"%s defined the panels but not define {.field nobs}\", object_name(self)\n ))\n } else if (length(new_panel) != nobs) {\n # we have defined panel, but don't define the `nobs`\n cli_abort(sprintf(\n \"layout panels defined by %s (nobs: %d) is not compatible with the nobs: %d\",\n object_name(self), length(new_panel), nobs\n ))\n } else if (!is.null(old_panel) && !(new_panel %nest% old_panel)) {\n cli_abort(sprintf(\n \"%s disrupt the previously established panel groups of %s\",\n object_name(self), layout_name\n ))\n }\n } else if (!is.null(old_panel)) {\n # push developer to reset the panel in the layout\n cli_abort(c(\n sprintf(\"invalid %s\", object_name(self)),\n i = sprintf(\n \"%s reset the {.field panel}, but don't change the {.field panel} of the layout\", object_name(self)\n )\n ))\n }\n panel <- new_panel\n if (!is.null(panel) && !is.factor(panel)) panel <- factor(panel)\n\n # check index\n new_index <- .subset2(panel_and_index, 2L)\n if (!is.null(new_index)) {\n if (!is.integer(new_index)) {\n cli_abort(c(\n sprintf(\n \"invalid layout ordering index defined by %s\", object_name(self)\n ),\n i = \"layout ordering index must be an integer\"\n ))\n } else if (anyNA(new_index)) {\n cli_abort(sprintf(\n \"layout ordering index defined by %s contain `NA`\",\n object_name(self)\n ))\n } else if (is.null(nobs)) {\n # we have defined panel, but don't define the `nobs`\n cli_abort(sprintf(\n \"%s defined the ordering index but not define nobs\", object_name(self)\n ))\n } else if (length(new_index) != nobs) {\n # we have defined index, but don't define the `nobs`\n cli_abort(sprintf(\n \"layout ordering index defined by %s (nobs: %d) is not compatible with the nobs (%d)\",\n object_name(self), length(new_index), nobs\n ))\n }\n } else if (!is.null(old_index)) {\n # push developer to reset the `index` in the layout\n cli_abort(c(\n sprintf(\"invalid %s\", object_name(self)),\n i = sprintf(\n \"%s reset the {.field index}, but don't change the {.field index} of the layout\",\n object_name(self)\n )\n ))\n }\n index <- new_index\n\n # we always make the index following the panel\n if (!is.null(panel) && !is.null(index)) {\n index <- reorder_index(panel, index)\n }\n\n # we always prevent from reordering twice.\n if (!is.null(old_index) && !all(old_index == index)) {\n cli_abort(sprintf(\n \"%s disrupt the previously established ordering index of %s\",\n object_name(self), layout_name\n ))\n }\n discrete_design(panel, index, nobs)\n },\n\n # Following fields should be defined for the new `CraftAlign` object.\n # argument name in these function doesn't matter.\n compute = function(self, panel, index) NULL,\n\n # Group heamap row/column and reorder, Must return a list of 2:\n # - the first one should be the groups for heatmap row/column, the factor\n # levels will determine the panel order, so it should always follow the\n # index if you don't want the panel levels break the index. See\n # `AlignDendro` for example.\n # - the second one should be the heatmap row/column order index, and will\n # determine the order in each grouped panel.\n #\n # See `$setup_design()` method for details\n # There will have following situations (the input is old index and old\n # panel):\n #\n # 1. old index is NULL and old panel is NULL, there is nothing wrong to\n # define any new index or panel\n # 2. old index is `NULL` and old panel is not `NULL`, in this way, new\n # index must follow the old panel.\n #\n # For new `CraftAlign` object, which can do clustering, we must\n # abort, if it can not do sub-clustering, if it can do sub-clustering, we\n # should know if we want to change the order between the groups (panel\n # levels).\n #\n # Please check `AlignGroup` object and `CraftAlign` object\n # For dendrogram, it can do sub-clustering within each group, it also\n # allows reordering between groups (it provide `reorder_group` argument),\n # so the new panel levels may be not the same with old panel\n #\n # For `CraftAlign` object reordering the heatmap rows/columns.\n # usually we provide a `strict` argument, to allow reorder heatmap within\n # group only. See `AlignOrder2`.\n #\n # 3. old index is not `NULL`, no matter whether old panel is `NULL` or not,\n # in this way, we should always ensure the new index won't change the old\n # index, this will be checked in `$setup_design()` method.\n align = function(self, panel, index) list(panel, index),\n\n # let Craftsman to add schemes and theme acoordingly\n finish_plot = function(self, plot, schemes, theme) {\n ggproto_parent(AlignGg, self)$finish_plot(plot, schemes, theme)\n },\n summary = function(self, plot) {\n header <- ggproto_parent(Craftsman, self)$summary(plot)\n oo <- self$summary_align()\n nms <- c(\"plot\", \"reorder\", \"split\")\n content <- c(\n if (is.null(plot)) \"no\" else \"yes\",\n if (isTRUE(oo[1L])) \"yes\" else \"no\",\n if (isTRUE(oo[2L])) \"yes\" else \"no\"\n )\n nms <- format(nms, justify = \"right\")\n content <- format(content, justify = \"left\")\n content <- paste0(\" \", nms, \": \", content)\n c(header, content)\n },\n\n # Summary the action of `Align`\n #\n # @return A logical vector of length 2, indicating:\n # - Whether the object reorders the observations.\n # - Whether the object splits the observations into groups.\n # @keywords internal\n summary_align = function(self) c(FALSE, FALSE)\n)\n"], ["/ggalign/R/craftbox-.R", "# Use S4 to override the double dispatch problem of ggplot2\n# And it's easy to convert a S4 Class to a S7 Class\nmethods::setClass(\n \"CraftBox\",\n list(\n plot = \"ANY\", # To avoid modify in place, we put plot in a slot\n active = \"ANY\",\n size = \"ANY\",\n schemes = \"ANY\",\n craftsman = \"ANY\" # `Craftsman` object\n )\n)\n\n#' Show `CraftBox` information\n#' @param object A `CraftBox` object.\n#' @return The input invisiblely.\n#' @keywords internal\nmethods::setMethod(\"show\", \"CraftBox\", function(object) {\n print(object)\n})\n\n#' @importFrom methods new\nnew_craftbox <- function(craftsman = NULL, ...,\n plot = NULL, active = NULL, size = NULL,\n schemes = NULL, call = caller_call()) {\n assert_active(active, allow_null = FALSE, call = call)\n if (is.null(size)) {\n size <- unit(NA, \"null\")\n } else {\n size <- check_size(size, call = call)\n }\n new(\n \"CraftBox\",\n # `call`: used to provide error message\n craftsman = ggproto(NULL, craftsman %||% Craftsman, ..., call = call),\n schemes = schemes %||% default_schemes(),\n plot = plot, active = active, size = size\n )\n}\n\n#' @export\nprint.CraftBox <- function(x, ...) {\n cat(x@craftsman$summary(x@plot), sep = \"\\n\")\n invisible(x)\n}\n\n#' @export\nplot.CraftBox <- function(x, ...) {\n cli_abort(sprintf(\"Cannot plot %s object directly\", object_name(x)))\n}\n\n#' @importFrom grid grid.draw\n#' @exportS3Method\ngrid.draw.CraftBox <- plot.CraftBox\n\n#' Add custom objects to ggalign plot\n#' @keywords internal\nmethods::setMethod(\"+\", c(\"CraftBox\", \"ANY\"), function(e1, e2) {\n if (missing(e2)) {\n cli_abort(c(\n \"Cannot use {.code {.Generic}} with a single argument.\",\n \"i\" = \"Did you accidentally put {.code {.Generic}} on a new line?\"\n ))\n }\n\n if (is.null(e2)) return(e1) # styler: off\n\n # Get the name of what was passed in as e2, and pass along so that it\n # can be displayed in error messages\n e2name <- paste(deparse(substitute(e2)), collapse = \" \")\n switch(.Generic, # nolint\n `+` = craftbox_add(e2, e1, e2name),\n stop_incompatible_op(.Generic, e1, e2)\n )\n})\n\n#' @importFrom methods is\nis_craftbox <- function(x) is(x, \"CraftBox\")\n\nis_cross_plot <- function(x) is_craftbox(x) && is_cross(x@craftsman)\n\nis_cross <- function(x) inherits(x, \"CraftCross\")\n\n#######################################################\n#' @importFrom ggplot2 ggproto\nCraftsman <- ggproto(\"Craftsman\",\n call = NULL,\n\n # following fields will be added when added to the layout\n in_linear = NULL,\n layout_name = NULL,\n direction = NULL,\n position = NULL, # for stack_layout() in quad_layout()\n labels = NULL,\n\n # A single boolean value indicates whether we should set facet and coord\n free_facet = FALSE,\n free_coord = FALSE,\n free_limits = FALSE,\n\n # we always prevent user from modifying the object in `$build_plot()` and\n # `$finish_plot()` methods\n locked = TRUE,\n lock = function(self) {\n assign(\"locked\", value = TRUE, envir = self)\n },\n unlock = function(self) {\n assign(\"locked\", value = FALSE, envir = self)\n },\n\n ############################################################\n # when added to the `Layout` object, will call following methods\n\n # we usually, define the `nobs` in `interact_layout`, since we can\n # act with the layout data in `interact_layout` method\n interact_layout = function(self, layout) layout,\n\n # we define the `panel` and `index` method in `setup_design` method\n setup_design = function(self, design) design,\n setup_plot = function(self, plot) plot,\n\n ##############################################################\n # Don't change the facet and coord in following methods\n build_plot = function(self, plot, design, extra_design = NULL,\n previous_design = NULL) {\n plot\n },\n finish_plot = function(self, plot, schemes, theme) {\n plot <- plot_add_schemes(plot, schemes)\n ggremove_margin(plot, self$direction) + theme_recycle()\n },\n\n # utils method to print the object, should return a character vector\n summary = function(self, plot) {\n cls <- class(self)\n cls <- cls[seq_len(which(cls == \"Craftsman\"))]\n sprintf(\"\", paste(cls, collapse = \" \"))\n }\n)\n\n# Used to lock the `Craftsman` object\n#' @export\n`$<-.Craftsman` <- function(x, name, value) {\n if (x$locked) {\n cli_abort(c(\n sprintf(\"Cannot modify %s\", object_name(x)),\n i = sprintf(\"%s is locked\", object_name(x))\n ), call = x$call)\n }\n NextMethod()\n}\n\n#################################################################\ncraftbox_add <- function(object, craftbox, object_name) {\n if (is.null(craftbox@plot)) {\n cli_abort(c(\n sprintf(\n \"Cannot add {.var {object_name}} to %s\",\n object_name(craftbox)\n ),\n i = sprintf(\"no plot found for %s\", object_name(craftbox))\n ))\n }\n UseMethod(\"craftbox_add\")\n}\n\n#' @importFrom ggplot2 ggplot_add\n#' @export\ncraftbox_add.default <- function(object, craftbox, object_name) {\n craftbox@plot <- ggplot_add(\n object,\n ggfun(\"plot_clone\")(craftbox@plot),\n object_name\n )\n craftbox\n}\n\n#' @export\ncraftbox_add.ggalign_scheme <- function(object, craftbox, object_name) {\n name <- ggalign_scheme_name(object)\n craftbox@schemes[name] <- list(update_scheme(\n object, .subset2(craftbox@schemes, name), object_name\n ))\n craftbox\n}\n\n######################################################################\nplot_build <- function(align, ..., schemes, theme) {\n plot <- align$build_plot(plot@plot, ...)\n align$finish_plot(plot, schemes, theme)\n}\n"], ["/ggalign/R/ggcross.R", "#' Connect two layout crosswise\n#'\n#' @description\n#' `ggcross` resets the layout ordering index of a [`stack_cross()`]. This\n#' allows you to add other `align_*` objects to define a new layout ordering\n#' index. Any objects added after `ggcross` will use this updated layout\n#' ordering index. This feature is particularly useful for creating `tanglegram`\n#' visualizations. `ggcross()` is an alias of `ggcross()`.\n#'\n#' @inheritParams ggalign\n#' @section ggplot2 specification:\n#' `ggcross()` initializes a ggplot `data` and `mapping`.\n#'\n#' `ggcross()` always applies a default mapping for the axis of the data index\n#' in the layout. This mapping is `aes(y = .data$.y)` for horizontal stack\n#' layout (including left and right annotation) and `aes(x = .data$.x)` for\n#' vertical stack layout (including top and bottom annotation).\n#'\n#' The data in the underlying `ggplot` object will contain following columns:\n#'\n#' - `.panel`: The panel for the aligned axis. Refers to the `x-axis` for\n#' vertical `stack_layout()` (including top and bottom annotations), and the\n#' `y-axis` for horizontal `stack_layout()` (including left and right\n#' annotations).\n#'\n#' - `.names` ([`vec_names()`][vctrs::vec_names]) and `.index`\n#' ([`vec_size()`][vctrs::vec_size()]/[`NROW()`]): Character names (if\n#' available) and the integer index of the original data.\n#'\n#' - `.hand`: a factor indicates the index groups.\n#'\n#' - `.x`/`.y` and `.discrete_x`/`.discrete_y`: Integer indices for `x`/`y`\n#' coordinates, and a factor of the data labels (only applicable when names\n#' exist).\n#'\n#' It is recommended to use `.x`/`.y`, or `.discrete_x`/`.discrete_y` as the\n#' `x`/`y` mapping.\n#'\n#' @importFrom ggplot2 ggplot aes\n#' @export\nggcross <- function(mapping = aes(), size = NULL,\n no_axes = NULL, active = NULL) {\n active <- update_active(active, new_active(use = TRUE))\n no_axes <- no_axes %||%\n getOption(sprintf(\"%s.align_no_axes\", pkg_nm()), default = TRUE)\n cross(\n CrossGg,\n plot = ggplot(mapping = mapping),\n schemes = default_schemes(th = theme_no_strip()),\n size = size, no_axes = no_axes, active = active\n )\n}\n\n#' @importFrom ggplot2 ggproto\nCrossGg <- ggproto(\"CrossGg\", \n CraftCross,\n interact_layout = function(self, layout) {\n if (!is_cross_layout(layout)) {\n cli_abort(c(\n sprintf(\n \"Cannot add %s to %s\",\n object_name(self), self$layout_name\n ),\n i = sprintf(\n \"%s can only be used in {.fn stack_cross}\",\n object_name(self)\n )\n ))\n }\n\n # udpate cross_points\n layout@cross_points <- c(layout@cross_points, length(layout@plot_list))\n\n # update old design list\n layout@odesign <- c(layout@odesign, list(layout@design))\n\n # we keep the names from the layout data for usage\n self$labels <- vec_names(layout@data)\n layout\n },\n setup_design = function(self, design) {\n design[\"index\"] <- list(NULL) # always reset the index\n design\n },\n setup_plot = function(self, plot) {\n ggadd_default(plot, mapping = switch_direction(\n self$direction, aes(y = .data$.y), aes(x = .data$.x)\n ))\n },\n #' @importFrom stats reorder\n build_plot = function(self, plot, design, extra_design = NULL,\n previous_design = NULL) {\n if (is.null(.subset2(design, \"nobs\"))) {\n cli_abort(sprintf(\n \"you must initialize %s before drawing %s\",\n self$layout_name, object_name(self)\n ), call = self$call)\n }\n direction <- self$direction\n index <- vec_c(\n .subset2(previous_design, \"index\"),\n .subset2(design, \"index\")\n )\n data <- data_frame0(\n .panel = vec_c(\n .subset2(previous_design, \"panel\"),\n .subset2(design, \"panel\")\n ),\n .index = index,\n # ggcross() only reset ordering index, labels should be the same\n .names = .subset(self$labels, index),\n .hand = if (is_horizontal(direction)) {\n factor(\n vec_rep_each(\n c(\"left\", \"right\"),\n c(\n .subset2(previous_design, \"nobs\"),\n .subset2(design, \"nobs\")\n )\n ),\n c(\"left\", \"right\")\n )\n } else {\n factor(\n vec_rep_each(\n c(\"top\", \"bottom\"),\n c(\n .subset2(previous_design, \"nobs\"),\n .subset2(design, \"nobs\")\n )\n ),\n c(\"bottom\", \"top\")\n )\n }\n )\n axis <- to_coord_axis(direction)\n coord_name <- paste0(\".\", axis)\n data[[coord_name]] <- vec_c(\n seq_len(.subset2(previous_design, \"nobs\")),\n seq_len(.subset2(design, \"nobs\"))\n )\n if (!is.null(.subset2(data, \".names\"))) {\n data[[paste0(\".discrete_\", axis)]] <- reorder(\n .subset2(data, \".names\"),\n .subset2(data, coord_name),\n order = FALSE\n )\n }\n plot <- gguse_data(plot, data)\n plot + switch_direction(\n direction,\n default_expansion(x = expansion()),\n default_expansion(y = expansion())\n )\n },\n finish_plot = function(self, plot, schemes, theme) {\n direction <- self$direction\n # remove axis titles, text, ticks used for alignment\n if (isTRUE(self$no_axes)) {\n schemes$scheme_theme <- .subset2(schemes, \"scheme_theme\") +\n theme_no_axes(switch_direction(direction, \"y\", \"x\"))\n }\n plot <- plot_add_schemes(plot, schemes)\n if (is_horizontal(direction)) {\n theme <- theme(\n panel.spacing.y = calc_element(\"panel.spacing.y\", theme)\n )\n } else {\n theme <- theme(\n panel.spacing.x = calc_element(\"panel.spacing.x\", theme)\n )\n }\n plot <- plot + theme\n ggremove_margin(plot, direction) + theme_recycle()\n },\n summary = function(self, plot) {\n header <- ggproto_parent(Craftsman, self)$summary(plot)\n c(header, \" Reset the ordering index and Add plot\")\n }\n)\n"], ["/ggalign/R/layout-chain-circle-genomic.R", "#' Create a Circular Layout for Genomic Data\n#'\n#' `circle_genomic()` constructs a circular layout specifically for genomic\n#' data. It is a specialized variant of `circle_continuous()` that applies\n#' default axis limits and coerces the first column of each plot’s data to use\n#' chromosome (`seqname`) identifiers—matching those in the layout data—as\n#' factor levels.\n#'\n#' @param data The input data, which can be:\n#' - A `character` string (\"hg19\" or \"hg38\") to load a predefined cytoband\n#' reference.\n#' - A `data.frame` with at least three columns: `chromosome`, `start`, and\n#' `end` positions.\n#' - A genomic object convertible via `fortify_data_frame()`.\n#' @param ... Additional arguments passed to specific methods or\n#' `fortify_data_frame()`.\n#' @inheritParams circle_continuous\n#' @return A `circle_layout` object representing the genomic layout.\n#' @export\ncircle_genomic <- function(data, ..., radial = NULL,\n direction = \"outward\",\n sector_spacing = NULL,\n theme = NULL) {\n UseMethod(\"circle_genomic\")\n}\n\n#' @export\ncircle_genomic.NULL <- function(data, ...) {\n cli_abort(\"{.arg data} must be provided to initialize `circle_genomic()`\")\n}\n\n#' @export\ncircle_genomic.waiver <- circle_genomic.NULL\n\n#' @export\ncircle_genomic.character <- function(data, ...) {\n data <- arg_match0(data, c(\"hg19\", \"hg38\"))\n data <- readRDS(\n pkg_extdata(\n switch(data,\n hg19 = \"ref_cytoband_hg19.rds\",\n hg38 = \"ref_cytoband_hg38.rds\"\n ),\n mustWork = TRUE\n )\n )\n circle_genomic(data, ...)\n}\n\n#' @export\n#' @keywords internal\ncircle_genomic.data.frame <- function(data, ..., radial = NULL,\n direction = \"outward\",\n sector_spacing = NULL,\n theme = NULL) {\n rlang::check_dots_empty()\n if (ncol(data) < 3L) {\n cli_abort(\"{.arg data} must have at least 3 columns: chromosome, start, and end\")\n }\n if (anyNA(data[[1L]]) || anyNA(data[[2L]]) || anyNA(data[[3L]])) {\n cli_abort(\"Columns 1, 2, and 3 of {.arg data} must not contain missing values\")\n }\n if (!is.numeric(data[[2L]]) || !is.numeric(data[[3L]])) {\n cli_abort(\"Columns 2 and 3 of {.arg data} must be numeric (start and end positions)\")\n }\n if (any(data[[2L]] > data[[3L]])) {\n cli_abort(\"Column 2 (start) must not be greater than column 3 (end) in any row of {.arg data}\")\n }\n data[[1L]] <- as.factor(data[[1L]])\n # seqnames, start, end\n # Special considerations for `data.table`, we cannot use `data[1:2]`\n groups <- vec_split(\n data.frame(start = data[[2L]], end = data[[3L]]),\n data[[1L]]\n )\n ranges <- lapply(\n .subset2(groups, \"val\"),\n function(d) genomic_range(.subset2(d, 1L), .subset2(d, 2L))\n )\n lvls <- levels(data[[1L]])\n names(ranges) <- .subset2(groups, \"key\")\n ranges <- ranges[lvls]\n limits <- continuous_limits(!!!ranges)\n ranges <- vec_rbind(!!!ranges, .names_to = \"seqnames\")\n ranges$seqnames <- factor(ranges$seqnames, levels = lvls)\n new_circle_layout(\n data = ggalign_data_set(data, seqnames = lvls, ranges = ranges),\n design = limits,\n radial = radial, direction = direction,\n sector_spacing = sector_spacing,\n schemes = default_schemes(data), theme = theme,\n name = \"circle_genomic\"\n )\n}\n\n#' @export\ncircle_genomic.default <- function(data, ..., radial = NULL,\n direction = \"outward\",\n sector_spacing = NULL,\n theme = NULL) {\n data <- fortify_data_frame(data = data, ...)\n circle_genomic(data,\n radial = radial, direction = direction,\n sector_spacing = sector_spacing, theme = theme\n )\n}\n\ngenomic_range <- function(start, end) {\n if (length(start) == 1) return(c(start = start, end = end)) # styler: off\n ordering <- order(start)\n s <- start[ordering[1L]]\n e <- end[ordering[1L]]\n for (i in ordering[-1L]) {\n if (start[ordering[i]] - e > 1) {\n cli_abort(\"Input genomic ranges cannot contain intervals\")\n }\n e <- end[ordering[i]]\n }\n c(start = s, end = e)\n}\n\n#' @export\nchain_decorate.CircleLayout <- function(layout, plot) {\n if (!identical(layout@name, \"circle_genomic\")) {\n return(plot)\n }\n if (is.data.frame(data <- plot$data)) {\n data[[1L]] <- factor(\n data[[1L]],\n levels = ggalign_attr(layout@data, \"seqnames\")\n )\n missing <- is.na(data[[1L]])\n if (any(missing)) {\n cli_warn(\"Removing {.val {sum(missing)}} rows contain missing {.field seqnames}\")\n data <- vec_slice(data, !missing)\n }\n plot$data <- data\n }\n plot\n}\n"], ["/ggalign/R/alignpatch-build.R", "#' @importFrom grid grid.draw\n#' @importFrom rlang try_fetch cnd_signal\n#' @export\nprint.alignpatches <- function(x, newpage = is.null(vp), vp = NULL, ...) {\n ggplot2::set_last_plot(x)\n if (newpage) {\n grid::grid.newpage()\n if (is.character(vp)) {\n cli_abort(c(\n \"{.arg vp} cannot be a character string when {.arg newpage} is TRUE.\",\n i = \"Please provide a viewport object or set {.arg newpage} to FALSE.\"\n ))\n }\n }\n if (!is.null(vp)) {\n if (is.character(vp)) {\n cur <- grid::current.viewport()$name\n grid::seekViewport(vp)\n if (!identical(cur, \"ROOT\")) on.exit(grid::seekViewport(cur))\n } else {\n grid::pushViewport(vp)\n on.exit(grid::upViewport())\n }\n }\n\n # render the plot\n try_fetch(\n grid.draw(x, ...),\n error = function(e) {\n if (inherits(e, \"simpleError\") &&\n deparse(conditionCall(e)[[1L]]) == \"grid.Call\") {\n error_name <- obj_type_friendly(x)\n if (Sys.getenv(\"RSTUDIO\") == \"1\") {\n cli_abort(c(paste(\n \"The RStudio {.field Plots} window may be\",\n \"too small to show\", error_name\n ), i = \"Please make the window larger.\"), parent = e)\n } else {\n cli_abort(c(\n \"The viewport may be too small to show {error_name}.\",\n i = \"Please make the window larger.\"\n ), parent = e)\n }\n }\n cnd_signal(e)\n }\n )\n invisible(x)\n}\n\n#' @importFrom grid grid.draw\n#' @exportS3Method\ngrid.draw.alignpatches <- function(x, recording = TRUE) {\n grid.draw(ggalignGrob(x), recording = recording)\n}\n\n#' @export\nggalign_build.alignpatches <- function(x) x\n\n#' @importFrom ggplot2 find_panel element_render theme theme_get\n#' @importFrom gtable gtable_add_grob gtable_add_rows gtable_add_cols\n#' @importFrom rlang arg_match0\n#' @importFrom S7 prop\n#' @export\nggalign_gtable.alignpatches <- function(x) {\n titles <- prop(x, \"titles\")\n\n # ensure theme has no missing value\n theme <- prop(x, \"theme\") %||% theme_get()\n\n # `TO-DO`: use `complete_theme()` from ggplot2 release\n theme <- complete_theme(theme)\n attr(x, \"theme\") <- theme # bypass the setter function\n table <- alignpatch(x)$patch_gtable(top_level = TRUE)\n\n fix_respect <- is.matrix(.subset2(table, \"respect\"))\n\n # Add title, subtitle, and caption -------------------\n # https://github.com/tidyverse/ggplot2/blob/2e08bba0910c11a46b6de9e375fade78b75d10dc/R/plot-build.R#L219C3-L219C9\n title <- element_render(\n theme = theme, \"plot.title\", .subset2(titles, \"title\"),\n margin_y = TRUE, margin_x = TRUE\n )\n title_height <- grobHeight(title)\n\n # Subtitle\n subtitle <- element_render(\n theme, \"plot.subtitle\", .subset2(titles, \"subtitle\"),\n margin_y = TRUE, margin_x = TRUE\n )\n subtitle_height <- grobHeight(subtitle)\n\n # caption\n caption <- element_render(\n theme, \"plot.caption\", .subset2(titles, \"caption\"),\n margin_y = TRUE, margin_x = TRUE\n )\n caption_height <- grobHeight(caption)\n\n # positioning of title and subtitle is governed by plot.title.position\n # positioning of caption is governed by plot.caption.position\n # \"panel\" means align to the panel(s)\n # \"plot\" means align to the entire plot (except margins and tag)\n panel_pos <- find_panel(table)\n title_pos <- arg_match0(\n theme$plot.title.position %||% \"panel\",\n c(\"panel\", \"plot\"),\n arg_nm = \"plot.title.position\",\n error_call = quote(theme())\n )\n\n caption_pos <- arg_match0(\n theme$plot.caption.position %||% \"panel\",\n values = c(\"panel\", \"plot\"),\n arg_nm = \"plot.caption.position\",\n error_call = quote(theme())\n )\n if (title_pos == \"panel\") {\n title_l <- panel_pos$l\n title_r <- panel_pos$r\n } else {\n title_l <- 1L\n title_r <- ncol(table)\n }\n if (caption_pos == \"panel\") {\n caption_l <- panel_pos$l\n caption_r <- panel_pos$r\n } else {\n caption_l <- 1L\n caption_r <- ncol(table)\n }\n\n table <- gtable_add_rows(table, subtitle_height, pos = 0)\n table <- gtable_add_grob(table, subtitle,\n name = \"subtitle\",\n t = 1, b = 1, l = title_l, r = title_r, clip = \"off\"\n )\n\n table <- gtable_add_rows(table, title_height, pos = 0)\n table <- gtable_add_grob(table, title,\n name = \"title\",\n t = 1, b = 1, l = title_l, r = title_r, clip = \"off\"\n )\n\n table <- gtable_add_rows(table, caption_height, pos = -1)\n table <- gtable_add_grob(table, caption,\n name = \"caption\",\n t = -1, b = -1, l = caption_l, r = caption_r, clip = \"off\"\n )\n if (fix_respect) {\n table$respect <- rbind(0L, 0L, table$respect, 0L)\n }\n\n # add margins --------------------------------------\n plot_margin <- calc_element(\"plot.margin\", theme)\n\n table <- gtable_add_rows(table, plot_margin[1L], 0L)\n table <- gtable_add_rows(table, plot_margin[3L])\n if (fix_respect) table$respect <- rbind(0L, table$respect, 0L)\n table <- gtable_add_cols(table, plot_margin[2L], 0L)\n table <- gtable_add_cols(table, plot_margin[4L])\n if (fix_respect) table$respect <- cbind(0L, table$respect, 0L)\n\n # add background -----------------------------------\n if (inherits(theme$plot.background, \"element\")) {\n table <- gtable_add_grob(table,\n element_render(theme, \"plot.background\"),\n t = 1L, l = 1L, b = -1L, r = -1L, name = \"background\", z = -Inf\n )\n table$layout <- table$layout[\n c(nrow(table$layout), 1:(nrow(table$layout) - 1L)),\n ]\n table$grobs <- table$grobs[\n c(nrow(table$layout), 1:(nrow(table$layout) - 1L))\n ]\n }\n table\n}\n"], ["/ggalign/R/ggplot-geom-draw.R", "#' Layer with Grid or Function\n#'\n#' Draw a ggplot2 layer using a grob or a function.\n#'\n#' @param draw Either a [grob][grid::grob] object or a function (can be\n#' purrr-style) that accepts at least one argument (a data frame of\n#' transformed coordinates) and returns a [grob][grid::grob].\n#'\n#' @param type A single string of `r oxford_or(c(\"group\", \"panel\"))`, `\"group\"`\n#' draws geoms with `draw_group`, which displays multiple observations as one\n#' geometric object, and `\"panel\"` draws geoms with `draw_panel`, displaying\n#' individual graphical objects for each observation (row). Default:\n#' `\"group\"`.\n#'\n#' @inheritParams ggplot2::layer\n#' @inheritParams ggplot2::geom_point\n#' @details If you want to combine the functionality of multiple geoms, it can\n#' typically be achieved by preparing the data for each geom inside the\n#' `draw_*()` call and sending it off to the different geoms, collecting the\n#' output in a [`grid::gList`] (a list of grobs) for `draw_group()` or a\n#' [`grid::gTree`] (a grob containing multiple child grobs) for\n#' `draw_panel()`.\n#' @seealso \n#' @examples\n#' text <- grid::textGrob(\n#' \"ggdraw\",\n#' x = c(0, 0, 0.5, 1, 1),\n#' y = c(0, 1, 0.5, 0, 1),\n#' hjust = c(0, 0, 0.5, 1, 1),\n#' vjust = c(0, 1, 0.5, 0, 1)\n#' )\n#' ggplot(data.frame(x = 1, y = 2)) +\n#' geom_draw(text)\n#' @importFrom rlang list2 arg_match0\n#' @importFrom ggplot2 ggproto aes\n#' @export\ngeom_draw <- function(draw, mapping = NULL, data = NULL,\n type = \"group\", stat = \"identity\",\n position = \"identity\", ...,\n na.rm = FALSE, show.legend = FALSE, inherit.aes = TRUE) {\n type <- arg_match0(type, c(\"group\", \"panel\"))\n if (!is.grob(draw) && !is.gList(draw)) draw <- rlang::as_function(draw)\n dots <- list2(...)\n ggplot2::layer(\n data = data,\n mapping = mapping,\n stat = stat,\n geom = switch(type,\n panel = ggproto(\n \"GeomDraw\",\n ggplot2::Geom,\n default_aes = GeomGshape$default_aes,\n setup_data = draw_setup_data,\n draw_panel = draw_geom_draw,\n draw_key = ggplot2::draw_key_blank\n ),\n group = ggproto(\n \"GeomDraw\",\n ggplot2::Geom,\n default_aes = GeomGshape$default_aes,\n setup_data = draw_setup_data,\n draw_group = draw_geom_draw,\n draw_key = ggplot2::draw_key_blank\n )\n ),\n position = position,\n show.legend = show.legend,\n inherit.aes = inherit.aes,\n params = c(\n list(na.rm = na.rm, draw = draw, .__draw_dots__ = dots), dots\n )\n )\n}\n\n# GeomTile will respect width and height\ndraw_setup_data <- function(self, data, params) {\n data$x <- data$x %||% 0.5\n data$y <- data$y %||% 0.5\n ggplot2::GeomTile$setup_data(data, params)\n}\n\ndraw_geom_draw <- function(data, panel_params, coord, draw, .__draw_dots__) {\n if (is.function(draw)) {\n data <- coord$transform(data, panel_params)\n # restore colour\n if (!is.null(data$colour) && is.null(data$color)) {\n data$color <- data$colour\n }\n if (!is.null(data$color) && is.null(data$colour)) {\n data$colour <- data$color\n }\n\n # restore width and height\n if (!is.null(data$xmin) && !is.null(data$xmax)) {\n data$width <- data$xmax - data$xmin\n }\n if (!is.null(data$ymin) && !is.null(data$ymax)) {\n data$height <- data$ymax - data$ymin\n }\n }\n make_draw_grob(draw, data, .__draw_dots__)\n}\n\n#' @return A [grob][grid::grob] object.\n#' @importFrom rlang inject\n#' @importFrom methods formalArgs\n#' @importFrom ggplot2 zeroGrob\n#' @keywords internal\n#' @noRd\nmake_draw_grob <- function(draw, data, dots) {\n if (is.function(draw)) {\n args <- formalArgs(draw)\n if (any(args == \"...\")) {\n draw <- inject(draw(!!!data, !!!dots))\n } else {\n draw <- inject(draw(\n !!!.subset(data, intersect(names(data), args)),\n !!!.subset(dots, intersect(\n setdiff(names(dots), names(data)), args\n ))\n ))\n }\n }\n ensure_grob(draw, zeroGrob())\n}\n"], ["/ggalign/R/ggplot-utils.R", "#' @importFrom ggplot2 .pt\nggfun <- function(fn, mode = \"any\") from_namespace(\"ggplot2\", fn, mode = mode)\n\nallow_lambda <- function(x) {\n if (rlang::is_formula(x)) rlang::as_function(x) else x\n}\n\nis.waive <- function(x) inherits(x, \"waiver\")\n\n`%|w|%` <- function(x, y) if (inherits(x, \"waiver\")) y else x\n\nsnake_class <- function(x) ggfun(\"snake_class\")(x)\n\nggadd_default <- function(plot, mapping = NULL, theme = NULL) {\n if (!is.null(mapping)) {\n plot <- plot + mapping + plot$mapping\n }\n if (!is.null(theme)) plot$theme <- theme + plot$theme\n plot\n}\n\nis_palette_unset <- function(type, aes) {\n type <- match.arg(type, c(\"discrete\", \"continuous\", \"binned\"))\n aes <- match.arg(aes, c(\"fill\", \"colour\"))\n is.null(getOption(sprintf(\"ggplot2.%s.%s\", type, aes)))\n}\n\n# A guide-box should be a `zeroGrob()` or a `gtable` object\n#' @importFrom gtable is.gtable\nmaybe_guide_box <- function(x) inherits(x, \"zeroGrob\") || is.gtable(x)\n\n######################################################\ngguse_data <- function(plot, data) {\n # ggplot use waiver() to indicate no data\n plot[\"data\"] <- list(data %||% waiver())\n plot\n}\n\nggremove_margin <- function(plot, direction) {\n if (!is.null(direction) && packageVersion(\"ggplot2\") > \"3.5.2\") {\n plot <- plot + switch_direction(\n direction,\n theme(plot.margin = margin(t = 0, r = NA, b = 0, l = NA)),\n theme(plot.margin = margin(t = NA, r = 0, b = NA, l = 0))\n )\n }\n plot\n}\n\n######################################################\ndefault_expansion <- function(x = NULL, y = NULL) {\n structure(list(x = x, y = y), class = c(\"ggalign_default_expansion\"))\n}\n\n#' @importFrom ggplot2 ggplot_add ggproto ggproto_parent\n#' @export\nggplot_add.ggalign_default_expansion <- function(object, plot, object_name,\n ...) {\n if (is.null(.subset2(object, \"x\")) && is.null(.subset2(object, \"y\"))) {\n return(plot)\n }\n ParentFacet <- plot$facet\n plot$facet <- ggproto(\n NULL,\n ParentFacet,\n init_scales = function(self, layout, x_scale = NULL, y_scale = NULL,\n params) {\n if (!is.null(x_scale) && !is.null(.subset2(object, \"x\"))) {\n x_scale$expand <- x_scale$expand %|w|% .subset2(object, \"x\")\n }\n if (!is.null(y_scale) && !is.null(.subset2(object, \"y\"))) {\n y_scale$expand <- y_scale$expand %|w|% .subset2(object, \"y\")\n }\n ggproto_parent(ParentFacet, self)$init_scales(\n layout = layout,\n x_scale = x_scale,\n y_scale = y_scale,\n params = params\n )\n }\n )\n plot\n}\n\n######################################################\nreverse_continuous_axis <- function(plot, axis) {\n if (plot$scales$has_scale(axis)) {\n # modify scale in place\n scale <- plot$scales$get_scales(axis)\n if (!scale$is_discrete()) {\n if (identical(scale$trans$name, \"identity\")) {\n scale$trans <- scales::as.transform(\"reverse\")\n } else if (identical(scale$trans$name, \"reverse\")) {\n scale$trans <- scales::as.transform(\"identity\")\n }\n }\n } else {\n plot <- plot +\n switch(axis,\n x = ggplot2::scale_x_reverse(),\n y = ggplot2::scale_y_reverse()\n )\n }\n plot\n}\n"], ["/ggalign/R/alignpatch-title.R", "#' Add patch titles to plot borders\n#'\n#' This function extends ggplot2's title functionality, allowing you to add\n#' titles to each border of the plot: top, left, bottom, and right.\n#'\n#' @details\n#'\n#' The appearance and alignment of these patch titles can be customized using\n#' [theme()][ggplot2::theme]:\n#' - `plot.patch_title`/`plot.patch_title.*`: Controls the text appearance of\n#' patch titles. By default, `plot.patch_title` inherit from `plot.title`, and\n#' settings for each border will inherit from `plot.patch_title`, with the\n#' exception of the `angle` property, which is not inherited.\n#' - `plot.patch_title.position`/`plot.patch_title.position.*`: Determines the\n#' alignment of the patch titles. By default, `plot.patch_title.position`\n#' inherit from `plot.title.position`, and settings for each border will\n#' inherit from `plot.patch_title`. The value `\"panel\"` aligns the patch\n#' titles with the plot panels. Setting this to `\"plot\"` aligns the patch\n#' title with the entire plot (excluding margins and plot tags).\n#'\n#' @param top,left,bottom,right A string specifying the title to be added to the\n#' top, left, bottom, and right border of the plot.\n#' @return A [`labels`][ggplot2::labs] object to be added to ggplot.\n#' @examples\n#' ggplot(mtcars) +\n#' geom_point(aes(mpg, disp)) +\n#' patch_titles(\n#' top = \"I'm top patch title\",\n#' left = \"I'm left patch title\",\n#' bottom = \"I'm bottom patch title\",\n#' right = \"I'm right patch title\"\n#' )\n#' @export\n#' @importFrom ggplot2 waiver\npatch_titles <- function(top = waiver(), left = waiver(), bottom = waiver(),\n right = waiver()) {\n structure(\n list(top = top, left = left, bottom = bottom, right = right),\n class = \"ggalign_patch_labels\"\n )\n}\n\n#' @importFrom ggplot2 find_panel calc_element zeroGrob element_grob merge_element\n#' @importFrom rlang arg_match0\n#' @importFrom grid grobName\nsetup_patch_titles <- function(table, patch_titles, theme) {\n # complete_theme() will ensure `plot_title` exists\n old_text <- calc_element(\"plot.title\", theme)\n # always justification by center for patch title\n old_text$hjust <- 0.5\n if (is.null(text <- .subset2(theme, \"plot.patch_title\"))) {\n text <- old_text\n } else if (inherits(text, \"element_text\")) {\n text <- merge_element(text, old_text)\n } else {\n cli_abort(paste(\n \"Theme element {.var plot.patch_title} must be a\",\n \"{.cls element_text}.\"\n ), call = quote(theme()))\n }\n # inherit from plot.title.position, default use \"panel\"\n position <- .subset2(theme, \"plot.patch_title.position\") %||%\n .subset2(theme, \"plot.title.position\") %||% \"panel\"\n for (border in .TLBR) {\n panel_pos <- find_panel(table)\n patch_title <- .subset2(patch_titles, border)\n name <- paste(\"plot.patch_title\", border, sep = \".\")\n if (is.null(patch_title)) {\n title <- zeroGrob()\n } else {\n # set the default angle\n text$angle <- switch(border,\n top = 0L,\n left = 90L,\n bottom = 0L,\n right = -90L\n )\n # we merge the element with `plot.patch_title`\n if (is.null(el <- .subset2(theme, name))) {\n el <- text\n } else if (inherits(el, \"element_text\")) {\n el <- merge_element(el, text)\n } else {\n cli_abort(paste(\n \"Theme element {.var {name}} must have\",\n \"class {.cls element_text}.\"\n ), call = quote(theme()))\n }\n # render the patch title grob\n title <- element_grob(el, patch_title,\n margin_y = TRUE, margin_x = TRUE\n )\n title$name <- grobName(title, name)\n }\n\n name <- paste(\"plot.patch_title.position\", border, sep = \".\")\n pos <- arg_match0(\n .subset2(theme, name) %||% position,\n c(\"panel\", \"plot\"),\n arg_nm = name,\n error_call = quote(theme())\n )\n if (border == \"top\") {\n height <- grobHeight(title)\n if (pos == \"panel\") {\n l <- panel_pos$l\n r <- panel_pos$r\n } else {\n l <- 1L\n r <- ncol(table)\n }\n h <- .subset2(panel_pos, \"t\") - 4L # above original xlab\n table <- gtable_add_rows(table, height, pos = h)\n table <- gtable_add_grob(table, title,\n name = \"patch-title-top\",\n t = h + 1L, b = h + 1L, l = l, r = r,\n clip = \"off\"\n )\n } else if (border == \"left\") {\n width <- grobWidth(title)\n if (pos == \"panel\") {\n t <- panel_pos$t\n b <- panel_pos$b\n } else {\n t <- 1L\n b <- nrow(table)\n }\n v <- .subset2(panel_pos, \"l\") - 4L # left of the ylab\n table <- gtable_add_cols(table, width, pos = v)\n table <- gtable_add_grob(table, title,\n name = \"patch-title-left\",\n t = t, b = b, l = v + 1L, r = v + 1L,\n clip = \"off\"\n )\n } else if (border == \"bottom\") {\n height <- grobHeight(title)\n if (pos == \"panel\") {\n l <- panel_pos$l\n r <- panel_pos$r\n } else {\n l <- 1L\n r <- ncol(table)\n }\n h <- .subset2(panel_pos, \"b\") + 3L # below original xlab\n table <- gtable_add_rows(table, height, pos = h)\n table <- gtable_add_grob(table, title,\n name = \"patch-title-bottom\",\n t = h + 1L, b = h + 1L, l = l, r = r,\n clip = \"off\"\n )\n } else if (border == \"right\") {\n width <- grobWidth(title)\n if (pos == \"panel\") {\n t <- panel_pos$t\n b <- panel_pos$b\n } else {\n t <- 1L\n b <- nrow(table)\n }\n v <- .subset2(panel_pos, \"r\") + 3L # right of the ylab\n table <- gtable_add_cols(table, width, pos = v)\n table <- gtable_add_grob(table, title,\n name = \"patch-title-right\",\n t = t, b = b, l = v + 1L, r = v + 1L,\n clip = \"off\"\n )\n }\n }\n table\n}\n\n#' @importFrom ggplot2 ggplot_add\n#' @export\nggplot_add.ggalign_patch_labels <- function(object, plot, object_name, ...) {\n plot$ggalign_patch_labels <- update_non_waive(\n plot$ggalign_patch_labels %||% list(), object\n )\n if (!inherits(plot, \"patch_ggplot\")) {\n plot <- add_class(plot, \"patch_ggplot\")\n }\n plot\n}\n"], ["/ggalign/R/attributes.R", "#' Get Data from the Attribute Attached by ggalign\n#'\n#' @description\n#' `ggalign_attr` retrieves supplementary information stored as attributes\n#' during the layout rendering process. These attributes—typically added during\n#' data transformation by functions such as [`fortify_matrix()`] or\n#' [`fortify_data_frame()`]—may contain filtered data, auxiliary metadata, or\n#' other context essential for downstream operations.\n#'\n#' Factor level information, stored as a separate attribute, can be accessed via\n#' `ggalign_lvls`.\n#'\n#' @details\n#' Attributes attached to the data are especially useful when the input data is\n#' transformed in ways that limit access to the complete dataset. For example,\n#' [`fortify_matrix.MAF()`] might filter mutation data while adding attributes\n#' that retain important context, such as the total number of observations, for\n#' detailed or aggregated analyses. Additionally, it stores the levels of\n#' `Variant_Classification` for further usage.\n#'\n#' @param x Data used, typically inherited from the layout `r rd_layout()`.\n#' @param field A string specifying the particular data to retrieve from the\n#' attached attribute. If `NULL`, the entire attached attribute list will be\n#' returned.\n#' @param check A boolean indicating whether to check if the `field` exists. If\n#' `TRUE`, an error will be raised if the specified `field` does not exist.\n#' @return\n#' - `ggalign_attr`: The specified data from the attached supplementary data or\n#' `NULL` if it is unavailable.\n#' - `ggalign_lvls`: The attached supplementary levels or `NULL` if it is\n#' unavailable.\n#'\n#' @export\nggalign_attr <- function(x, field = NULL, check = TRUE) {\n assert_string(field, allow_empty = FALSE, allow_null = TRUE)\n if (is.null(x <- ggalign_attr_get(x)) || is.null(field)) {\n return(x)\n }\n if (isTRUE(check) && !rlang::has_name(x, field)) {\n cli_abort(\"Cannot find {field} in {.arg x}\")\n }\n .subset2(x, field)\n}\n\n#' @export\n#' @rdname ggalign_attr\nggalign_lvls <- function(x) ggalign_lvls_get(x)\n\n#' Attach supplementary data and levels for ggalign\n#'\n#' @param .data Input data for the layout.\n#' @param ... <[dyn-dots][rlang::dyn-dots]> A list of data to be attached.\n#' @param .lvls A character vector representing the attached levels.\n#' @note Used by developers in [`fortify_matrix()`], [`fortify_data_frame()`],\n#' and other related methods.\n#' @seealso [`ggalign_attr()`]/[`ggalign_lvls()`]\n#' @importFrom rlang list2\n#' @export\nggalign_data_set <- function(.data, ..., .lvls = NULL) {\n if (...length() > 0L) {\n .data <- ggalign_attr_set(.data, list2(...))\n }\n if (!is.null(.lvls)) {\n .data <- ggalign_lvls_set(.data, .lvls)\n }\n # to prevent the print of attributes\n if (!is.null(ggalign_attr_get(.data)) ||\n !is.null(ggalign_lvls_get(.data))) {\n .data <- add_class(.data, \"ggalign_data\")\n }\n .data\n}\n\n#' @export\nprint.ggalign_data <- function(x, ...) {\n print(\n remove_class(\n ggalign_lvls_remove(ggalign_attr_remove(x)),\n \"ggalign_data\"\n )\n )\n invisible(x)\n}\n\nggalign_attr_set <- function(x, values) {\n attr(x, \".__ggalign_attr__\") <- values\n x\n}\n\nggalign_attr_get <- function(x) attr(x, \".__ggalign_attr__\", exact = TRUE)\n\nggalign_attr_remove <- function(x) ggalign_attr_set(x, NULL)\n\nggalign_lvls_set <- function(x, lvls) {\n attr(x, \".__ggalign_levels__\") <- lvls\n x\n}\n\nggalign_lvls_get <- function(x) attr(x, \".__ggalign_levels__\", exact = TRUE)\n\nggalign_lvls_remove <- function(x) ggalign_lvls_set(x, NULL)\n\n# we keep a special attribute across all data\n# this is used to pass additional annotation informations\nggalign_data_restore <- function(data, original) {\n if (is.null(data) || is.waive(data)) return(data) # styler: off\n if (is.null(ggalign_attr_get(data)) && # no attached attribute\n # the original has attached attribute\n !is.null(value <- ggalign_attr_get(original))) {\n data <- ggalign_attr_set(data, value)\n }\n\n if (is.null(ggalign_lvls_get(data)) && # no attached levels\n # the original has attached levels\n !is.null(value <- ggalign_lvls_get(original))) {\n data <- ggalign_lvls_set(data, value)\n }\n # to prevent the print of attributes\n if (!is.null(ggalign_attr_get(data)) ||\n !is.null(ggalign_lvls_get(data))) {\n data <- add_class(data, \"ggalign_data\")\n }\n data\n}\n"], ["/ggalign/R/ggfree.R", "#' Add ggplot to layout without alignment\n#'\n#' @description\n#' `r lifecycle::badge('experimental')`\n#'\n#' The `ggfree()` function allows you to incorporate a ggplot object into your\n#' layout. Unlike `ggalign()`, which aligns every axis value precisely,\n#' `ggfree()` focuses on integrating plots into the layout without enforcing\n#' strict axis alignment.\n#'\n#' @inheritParams ggalign\n#'\n#' @section ggplot2 specification:\n#' `ggalign` initializes a ggplot object. The underlying data is created using\n#' [`fortify_data_frame()`]. Please refer to this method for more details.\n#'\n#' When used in `quad_layout()`/`ggheatmap()`, if the data is inherited from the\n#' `quad_layout()` and the other direction aligns discrete variables, following\n#' columns will be added:\n#'\n#' - `.extra_panel`: Provides the panel information for the column (left or\n#' right annotation) or row (top or bottom annotation).\n#' - `.extra_index`: The index information for the column (left or right\n#' annotation) or row (top or bottom annotation).\n#'\n#' @examples\n#' ggheatmap(matrix(rnorm(56), nrow = 7)) +\n#' anno_top() +\n#' align_dendro() +\n#' ggfree(mtcars, aes(wt, mpg)) +\n#' geom_point()\n#' @export\nggfree <- function(data = waiver(), ..., size = NULL, active = NULL) {\n UseMethod(\"ggfree\", data)\n}\n\n#' @inheritParams ggplot2::ggplot\n#' @importFrom ggplot2 ggplot\n#' @export\n#' @rdname ggfree\nggfree.default <- function(data = waiver(), mapping = aes(), ...,\n size = NULL, active = NULL) {\n data <- fortify_data_frame(data = data, ...)\n new_free_gg(\n plot = ggplot(data = NULL, mapping = mapping),\n data = data,\n size = size,\n active = active\n )\n}\n\n#' @export\nggfree.uneval <- function(data = waiver(), ...) {\n cli_abort(c(\n \"{.arg data} cannot be {.obj_type_friendly {data}}\",\n \"i\" = \"Have you misspelled the {.arg data} argument in {.fn ggalign}\"\n ))\n}\n\n#' @export\nggfree.ggplot <- function(data = waiver(), ..., size = NULL, active = NULL) {\n rlang::check_dots_empty()\n plot <- data\n # In ggplot2, `waiver()` was regard to no data\n data <- plot$data %|w|% NULL\n plot <- gguse_data(plot, waiver())\n new_free_gg(plot, data, size = size, active = active)\n}\n\nnew_free_gg <- function(plot, data, size, active,\n call = caller_call()) {\n assert_active(active, allow_null = TRUE, call = call)\n active <- update_active(active, new_active(use = TRUE))\n new_craftbox(\n FreeGg,\n # new field for FreeGg\n input_data = data,\n # slots for the plot\n plot = plot,\n size = size,\n active = active,\n schemes = default_schemes(data),\n call = call\n )\n}\n\n#' @importFrom ggplot2 ggproto\nFreeGg <- ggproto(\"FreeGg\", Craftsman,\n free_facet = TRUE,\n free_limits = TRUE,\n interact_layout = function(self, layout) {\n layout_data <- layout@data\n if (is.waive(input_data <- self$input_data)) { # inherit from the layout\n data <- layout_data\n self$labels <- vec_names(layout_data)\n\n # for data inherit from the layout, and the design is for discrete\n # variable, we'll integrate the design into the plot data\n self$use_design <- is_stack_layout(layout)\n\n # if the layout data is from the quad-layout, we use the discrete\n # `design`\n self$use_extra_design <- is_stack_layout(layout) &&\n isTRUE(layout@heatmap$quad_matrix)\n } else if (is.function(input_data)) {\n if (is.null(layout_data)) {\n cli_abort(c(\n sprintf(\n \"{.arg data} in %s cannot be a function\",\n object_name(self)\n ),\n i = sprintf(\"no data was found in %s\", self$layout_name)\n ))\n }\n data <- input_data(layout_data)\n } else {\n data <- input_data\n }\n self$data <- ggalign_data_restore(\n fortify_data_frame(data, call = self$call), layout_data\n )\n layout\n },\n build_plot = function(self, plot, design, extra_design = NULL,\n previous_design = NULL) {\n if (is.function(data <- self$data)) {\n data <- NULL\n }\n if (is.null(data)) {\n return(gguse_data(plot, data))\n }\n if (isTRUE(self$use_extra_design) &&\n is_discrete_design(extra_design) &&\n !is.null(.subset2(extra_design, \"nobs\"))) {\n extra_plot_data <- data_frame0(\n .extra_panel = .subset2(extra_design, \"panel\"),\n .extra_index = .subset2(extra_design, \"index\")\n )\n } else {\n extra_plot_data <- NULL\n }\n\n # if inherit from the parent layout\n if (isTRUE(self$use_design) &&\n is_discrete_design(design) &&\n !is.null(.subset2(design, \"nobs\"))) {\n plot_data <- data_frame0(\n .panel = .subset2(design, \"panel\"),\n .index = .subset2(design, \"index\"),\n .names = .subset(self$labels, .subset2(design, \"index\"))\n )\n if (!is.null(extra_plot_data)) {\n plot_data <- cross_join(plot_data, extra_plot_data)\n data <- full_join(data, plot_data,\n by.x = c(\".column_index\", \".row_index\"),\n by.y = c(\".extra_index\", \".index\")\n )\n } else {\n data <- full_join(data, plot_data,\n by.x = \".row_index\", by.y = \".index\"\n )\n }\n } else if (!is.null(extra_plot_data)) {\n data <- full_join(data, extra_plot_data,\n by.x = \".column_index\", by.y = \".extra_index\"\n )\n }\n gguse_data(plot, data)\n },\n summary = function(self, plot) {\n header <- ggproto_parent(Craftsman, self)$summary(plot)\n c(header, \" Add plot without alignment\")\n }\n)\n"], ["/ggalign/R/craft-cross-link.R", "#' Add a plot to connect selected observations\n#'\n#' @param link A [`link_draw()`] object that defines how to draw the links,\n#' such as [`link_line()`].\n#' @param on_top A boolean value indicating whether to draw the link on top of\n#' the plot panel (`TRUE`) or below (`FALSE`).\n#' @inheritParams cross_none\n#' @inheritParams ggmark\n#'\n#' @section ggplot2 Specification:\n#' The `cross_link` function initializes a `ggplot` object but does not\n#' initialize any data. Using [`scheme_data()`] to change the internal data if\n#' needed.\n#'\n#' @export\ncross_link <- function(link, data = waiver(), ...,\n on_top = TRUE, obs_size = 1,\n inherit_index = NULL, inherit_panel = NULL,\n inherit_nobs = NULL,\n size = NULL, active = NULL) {\n if (!inherits(link, \"ggalign_link_draw\")) {\n cli_abort(\"{.arg link} must be a {.fn link_draw} object\")\n }\n assert_obs_size(obs_size)\n assert_active(active)\n active <- update_active(active, new_active(use = TRUE))\n cross(CrossLink,\n data = data, data_params = list2(...),\n link = link, obs_size = obs_size,\n plot = ggplot(), size = size,\n schemes = default_schemes(),\n active = active,\n on_top = on_top,\n inherit_nobs = inherit_nobs,\n inherit_panel = inherit_panel,\n inherit_index = inherit_index\n )\n}\n\n#' @importFrom ggplot2 ggproto ggproto_parent\n#' @importFrom grid gTree\n#' @include craft-cross-.R\nCrossLink <- ggproto(\"CrossLink\", CraftCross,\n interact_layout = function(self, layout) {\n if (!self$in_linear) { # only used for linear coordinate\n cli_abort(c(\n sprintf(\n \"Cannot add %s to %s\",\n object_name(self), layout_name\n ),\n i = sprintf(\n \"%s can only be used in linear layout\",\n object_name(self)\n )\n ))\n }\n ggproto_parent(CraftCross, self)$interact_layout(layout)\n },\n build_plot = function(self, plot, design, extra_design = NULL,\n previous_design = NULL) {\n if (is.null(.subset2(previous_design, \"nobs\"))) {\n cli_abort(\n sprintf(\n \"layout {.field nobs} for %s before %s is not initialized \",\n self$layout_name, object_name(self)\n )\n )\n }\n if (is.null(.subset2(design, \"nobs\"))) {\n cli_abort(\n sprintf(\n \"layout {.field nobs} for %s after %s is not initialized \",\n self$layout_name, object_name(self)\n )\n )\n }\n\n direction <- self$direction\n position <- self$position\n\n # parse links --------------------------------------------\n link <- self$link\n design1 <- previous_design\n design2 <- design\n full_data1 <- split(\n seq_len(.subset2(design1, \"nobs\")),\n .subset2(design1, \"panel\")\n )\n full_data2 <- split(\n seq_len(.subset2(design2, \"nobs\")),\n .subset2(design2, \"panel\")\n )\n links <- .subset2(link, \"links\")\n # set default links for link_line()\n if (is_empty(links) &&\n inherits(link, \"ggalign_link_line\") &&\n identical(.subset2(design1, \"nobs\"), .subset2(design2, \"nobs\"))) {\n links <- lapply(seq_len(.subset2(design1, \"nobs\")), function(i) {\n rlang::new_formula(i, i)\n })\n links <- pair_links(!!!links)\n }\n link_index <- make_links_data(\n links,\n design1 = design1, design2 = design2,\n labels1 = self$labels0, labels2 = self$labels\n )\n data_index <- lapply(link_index, function(index) {\n if (is.null(index)) {\n return(NULL)\n }\n hand1 <- .subset2(index, \"hand1\")\n hand2 <- .subset2(index, \"hand2\")\n list(\n hand1 = .subset2(design1, \"index\")[hand1],\n hand2 = .subset2(design2, \"index\")[hand2]\n )\n })\n plot$ggalign_link_data <- list(\n full_data1 = full_data1,\n full_data2 = full_data2,\n link_index = link_index,\n data_index = data_index,\n direction = direction,\n draw = .subset2(link, \"draw\"),\n obs_size = self$obs_size\n )\n plot\n },\n finish_plot = function(self, plot, schemes, theme) {\n plot <- plot_add_schemes(plot, schemes)\n\n # save spacing for usage\n spacing <- calc_element(\n switch_direction(\n self$direction,\n \"panel.spacing.y\",\n \"panel.spacing.x\"\n ),\n theme\n ) %||% unit(0, \"mm\")\n\n # setup the grob\n grob <- inject(gTree(\n !!!plot$ggalign_link_data,\n spacing1 = spacing,\n spacing2 = spacing,\n cl = \"ggalignLinkTree\"\n ))\n plot$ggalign_link_data <- NULL\n\n # insert the grob\n plot <- plot + inset(grob, on_top = self$on_top)\n ggremove_margin(plot, self$direction) + theme_recycle()\n },\n summary = function(self, plot) {\n header <- ggproto_parent(CraftCross, self)$summary(plot)\n c(header, \" Add plot to connect selected observations\")\n }\n)\n"], ["/ggalign/R/scheme-align.R", "#' Align Specifications in the Layout\n#'\n#' @description\n#' `r lifecycle::badge('experimental')`\n#'\n#' The `scheme_align()` function defines the align Specifications for plots.\n#'\n#' @param guides A string with one or more of `r oxford_and(c(.tlbr, \"i\"))`\n#' indicating which side of guide legends should be collected. Defaults to\n#' [`waiver()`][ggplot2::waiver()], which inherits from the parent layout. If no\n#' parent layout, all guides will be collected. If `NULL`, no guides will be\n#' collected.\n#'\n#' @param free_spaces A string with one or more of `r oxford_and(.tlbr)`\n#' indicating which border spaces should be removed. Defaults to\n#' [`waiver()`][ggplot2::waiver()], which inherits from the parent layout. If no\n#' parent, the default is `NULL`, meaning no spaces are removed.\n#'\n#' Usually you want to apply this with the whole layout, instead of individual\n#' plots.\n#'\n#' @param free_labs A string with one or more of `r oxford_and(.tlbr)`\n#' indicating which axis titles should be free from alignment. Defaults to\n#' [`waiver()`][ggplot2::waiver()], which inherits from the parent layout. If no\n#' parent layout, no axis titles will be aligned. If `NULL`, all axis titles\n#' will be aligned.\n#'\n#' @return A `scheme_align` object.\n#' @examples\n#' set.seed(123)\n#' mat <- matrix(rnorm(72), nrow = 8)\n#' # used in the layout, define the default action for all plots in the layout\n#' ggheatmap(mat) -\n#' scheme_align(guides = NULL) +\n#' anno_right() +\n#' align_dendro(aes(color = branch), k = 3)\n#'\n#' # You can also add it for a single plot\n#' ggheatmap(mat) -\n#' # for all plots in the layout, we default won't collect any guide legends\n#' scheme_align(guides = NULL) +\n#' # for the heatmap body, we collect guide legends in the right\n#' # note, the guide legends will be collected to the right side of the\n#' # layout which will overlap the legends in the right annotation\n#' scheme_align(guides = \"r\") +\n#' anno_right() +\n#' align_dendro(aes(color = branch), k = 3)\n#'\n#' # to avoid overlapping, we can also collect the guide legends in the\n#' # right annotation\n#' ggheatmap(mat) -\n#' scheme_align(guides = NULL) +\n#' scheme_align(guides = \"r\") +\n#' anno_right() +\n#' align_dendro(aes(color = branch), k = 3) +\n#' scheme_align(guides = \"r\")\n#' @export\nscheme_align <- function(guides = NA, free_spaces = NA, free_labs = NA) {\n if (!identical(guides, NA)) assert_layout_guides(guides)\n if (!identical(free_spaces, NA)) assert_layout_position(free_spaces)\n if (!identical(free_labs, NA)) assert_layout_position(free_labs)\n new_scheme_align(\n free_spaces = free_spaces,\n free_labs = free_labs,\n guides = guides\n )\n}\n\nnew_scheme_align <- function(guides = waiver(), free_spaces = waiver(),\n free_labs = waiver()) {\n new_scheme(\n name = \"scheme_align\",\n list(free_spaces = free_spaces, free_labs = free_labs, guides = guides),\n class = \"scheme_align\"\n )\n}\n\n#' @importFrom utils modifyList\n#' @export\nupdate_scheme.scheme_align <- function(new, old, object_name) {\n modifyList(old,\n new[!vapply(new, identical, logical(1L), y = NA, USE.NAMES = FALSE)],\n keep.null = TRUE\n )\n}\n\n#' @export\ninherit_scheme.scheme_align <- function(scheme, pscheme) {\n # `align_plots` control how to inherit `guides` from the layout\n # we don't need to inherit it here\n scheme[\"free_spaces\"] <- list(.subset2(scheme, \"free_spaces\") %|w|%\n .subset2(pscheme, \"free_spaces\"))\n scheme[\"free_labs\"] <- list(.subset2(scheme, \"free_labs\") %|w|%\n .subset2(pscheme, \"free_labs\"))\n scheme\n}\n\n#' @param theme Additional default theme elements to be added for the plot\n#' @noRd\nplot_add_scheme.scheme_align <- function(plot, scheme) {\n if (!is.waive(free_guides <- .subset2(scheme, \"guides\"))) {\n plot <- free_guide(plot, free_guides)\n }\n # by default, we'll attach all labs to the axis\n if (!is.null(free_labs <- .subset2(scheme, \"free_labs\") %|w|% \"tlbr\")) {\n plot <- free_lab(plot, free_labs)\n }\n # by default, we won't remove any spaces\n if (!is.null(free_spaces <- .subset2(scheme, \"free_spaces\") %|w|% NULL)) {\n plot <- free_space(free_border(plot, free_spaces), free_spaces)\n }\n plot\n}\n"], ["/ggalign/R/fortify-matrix-matrix.R", "#' Build a matrix\n#'\n#' @param data A matrix object.\n#' @inheritParams rlang::args_dots_empty\n#' @inheritParams fortify_matrix\n#' @section shape:\n#' - `upset`: [`fortify_matrix.matrix_upset()`]\n#' - `oncoplot`: [`fortify_matrix.matrix_oncoplot()`]\n#' @family fortify_matrix\n#' @export\nfortify_matrix.matrix <- fortify_matrix.waiver\n\n#' Convert the shape of a matrix for fortify method\n#'\n#' @param data A matrix.\n#' @param shape A string of `r oxford_or(c(\"upset\", \"oncoplot\"))`.\n#' @seealso\n#' - [`fortify_matrix.matrix()`]\n#' - [`fortify_matrix.matrix_upset()`]\n#' - [`fortify_matrix.matrix_oncoplot()`]\n#' @family tune\n#' @importFrom rlang arg_match0\n#' @export\ntune.matrix <- function(data, shape) {\n shape <- arg_match0(shape, c(\"upset\", \"oncoplot\"))\n if (identical(shape, \"oncoplot\")) {\n if (!is.character(data)) {\n cli_abort(\n \"{.arg data} must be a character matrix to use {shape} shape\"\n )\n }\n }\n new_tune(data, class = sprintf(\"matrix_%s\", shape))\n}\n\n#' @inherit fortify_matrix.list_upset title\n#' @description\n#' Converts a matrix suitable for creating an UpSet plot. [`tune.matrix()`]\n#' helps convert `matrix` object to a `matrix_upset` object.\n#' @param data A matrix where each row represents an element, and each column\n#' defines a set. The values in the matrix indicate whether the element is part\n#' of the set. Any non-missing value signifies that the element exists in the\n#' set.\n#' @inheritParams fortify_matrix.list_upset\n#' @inheritDotParams fortify_matrix.list_upset\n#' @inheritSection fortify_matrix.list_upset ggalign attributes\n#' @seealso [`tune.matrix()`]\n#' @family fortify_matrix\n#' @export\nfortify_matrix.matrix_upset <- function(data, ..., data_arg = NULL,\n call = NULL) {\n call <- call %||% current_call()\n data <- !is.na(tune_data(data))\n elements <- vec_seq_along(data)\n fortify_matrix.list_upset(\n lapply(seq_len(ncol(data)), function(i) {\n .subset(elements, data[, i, drop = TRUE])\n }),\n ...,\n data_arg = data_arg,\n call = call\n )\n}\n\n#' Build a Matrix for OncoPrint\n#'\n#' @description\n#' Converts a matrix suitable for creating an OncoPrint. [`tune.matrix()`]\n#' helps convert `matrix` object to a `matrix_oncoplot` object.\n#'\n#' @param data A matrix where each row represents an genes, and each column\n#' represents samples. The values in the matrix indicate whether the element is\n#' part of the set.\n#' @inheritParams fortify_matrix.MAF\n#' @section ggalign attributes:\n#' - `gene_summary`: An integer vector of the altered samples for each gene.\n#' - `sample_summary`: An integer vector of the altered genes for each sample.\n#' - `n_genes`: Total number of genes.\n#' - `n_samples`: Total number of samples.\n#'\n#' @seealso [`tune.matrix()`]\n#' @family fortify_matrix\n#' @export\nfortify_matrix.matrix_oncoplot <- function(data, ...,\n genes = NULL, n_top = NULL,\n remove_empty_genes = TRUE,\n remove_empty_samples = TRUE,\n missing_genes = \"error\",\n data_arg = NULL,\n call = NULL) {\n call <- call %||% current_call()\n rlang::check_dots_empty(call = call)\n\n # check arguments\n missing_genes <- arg_match0(\n missing_genes, c(\"error\", \"remove\"),\n error_call = call\n )\n\n data <- tune_data(data)\n alt <- !is.na(data)\n storage.mode(alt) <- \"integer\"\n gene_summary <- rowSums(alt)\n sample_summary <- colSums(alt)\n n_genes <- nrow(data)\n n_samples <- ncol(data)\n\n # filter by genes --------------------------------------\n if (!is.null(genes)) {\n genes <- vec_cast(genes, character())\n if (vec_any_missing(genes)) {\n cli_abort(\n \"{.arg genes} cannot contain missing values\",\n call = call\n )\n }\n if (vec_duplicate_any(genes)) {\n cli_abort(\n \"{.arg genes} cannot contain duplicated values\",\n call = call\n )\n }\n if (identical(missing_genes, \"remove\")) {\n genes <- genes[genes %in% rownames(data)]\n }\n if (is_empty(genes)) {\n cli_abort(\n \"No {.arg genes} remain after removing missing genes\",\n call = call\n )\n }\n index <- vec_as_location(\n genes,\n n = vec_size(data),\n names = rownames(data),\n missing = \"error\"\n )\n data <- vec_slice(data, index)\n alt <- vec_slice(alt, index)\n gene_summary <- vec_slice(gene_summary, index)\n }\n\n if (!is.null(n_top)) {\n n_top <- min(n_top, vec_size(alt))\n index <- vec_slice(\n order(rowSums(alt), decreasing = TRUE),\n seq_len(n_top)\n )\n data <- vec_slice(data, index)\n alt <- vec_slice(alt, index)\n gene_summary <- vec_slice(gene_summary, index)\n }\n\n # filter empty genes\n if (remove_empty_genes) {\n keep <- rowSums(alt) > 0L\n data <- vec_slice(data, keep)\n gene_summary <- vec_slice(gene_summary, keep)\n }\n\n # filter empty samples\n if (remove_empty_samples) {\n keep <- colSums(alt) > 0L\n data <- data[, keep, drop = FALSE]\n sample_summary <- vec_slice(sample_summary, keep)\n }\n\n ggalign_data_set(data,\n sample_summary = sample_summary,\n gene_summary = gene_summary,\n n_samples = n_samples,\n n_genes = n_genes\n )\n}\n"], ["/ggalign/R/scheme-theme.R", "#' Plot default theme\n#'\n#' @description\n#' `r lifecycle::badge('experimental')`\n#'\n#' `scheme_theme()` serves as the default theme and will always be overridden by\n#' any `theme()` settings applied directly to the plot. The default theme\n#' (`scheme_theme()`) is applied first, followed by any specific `theme()`\n#' settings, even if `theme()` is added before `scheme_theme()`.\n#'\n#' @inherit ggplot2::theme\n#' @param ... A [`theme()`][ggplot2::theme] object or additional element\n#' specifications not part of base ggplot2. In general, these should also be\n#' defined in the `element tree` argument. [`Splicing`][rlang::splice] a list\n#' is also supported.\n#' @examples\n#' set.seed(123)\n#' small_mat <- matrix(rnorm(56), nrow = 8)\n#' ggheatmap(small_mat) +\n#' scheme_theme(plot.background = element_rect(fill = \"red\"))\n#'\n#' # `scheme_theme()` serves as the default theme and will always be\n#' # overridden by any `theme()` settings applied directly to the plot\n#' ggheatmap(small_mat) +\n#' theme(plot.background = element_rect(fill = \"blue\")) +\n#' scheme_theme(plot.background = element_rect(fill = \"red\"))\n#'\n#' @importFrom ggplot2 theme\n#' @importFrom rlang inject\n#' @export\nscheme_theme <- rlang::new_function(\n # We utilize editor completion by listing all `theme()` arguments here.\n # By placing `...` at the beginning, we can check if the first\n # following argument is a `theme()` object rather than individual theme\n # elements.\n c(\n rlang::exprs(... = ),\n .subset(\n rlang::fn_fmls(theme),\n vec_set_difference(names(rlang::fn_fmls(theme)), \"...\")\n )\n ),\n quote({\n elements <- ggfun(\"find_args\")(..., complete = NULL, validate = NULL)\n ans <- theme(!!!elements)\n th <- NULL\n for (i in seq_len(...length())) {\n if (inherits(t <- ...elt(i), \"theme\")) {\n th <- ggfun(\"add_theme\")(th, t)\n }\n }\n new_scheme_theme(ggfun(\"add_theme\")(th, ans))\n })\n)\n\n#' @importFrom ggplot2 theme\nnew_scheme_theme <- function(th = theme()) {\n # I don't know why, if I omit the `object = th` argument, it won't work\n UseMethod(\"new_scheme_theme\", th)\n}\n\n#' @importFrom rlang inject\n#' @export\nnew_scheme_theme.theme <- function(th = theme()) {\n attrs <- attributes(th)\n attrs <- vec_slice(\n attrs, vec_set_difference(names(attrs), c(\"names\", \"class\"))\n )\n inject(new_scheme(\n name = \"scheme_theme\", th, !!!attrs,\n class = c(\"scheme_theme\", class(th))\n ))\n}\n\n#' @export\nnew_scheme_theme.scheme_theme <- function(th = theme()) th\n\n###############################################################\n#' @export\nupdate_scheme.scheme_theme <- function(new, old, object_name) {\n ggfun(\"add_theme\")(old, new, object_name)\n}\n\n#' @export\ninherit_scheme.scheme_theme <- function(scheme, pscheme) {\n pscheme + scheme\n}\n\n#' @export\nplot_add_scheme.scheme_theme <- function(plot, scheme) {\n # setup plot theme\n plot$theme <- scheme + plot$theme\n plot\n}\n"], ["/ggalign/R/craft-align-group.R", "#' Group and align observations based on a group vector\n#'\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' Splits observations into groups, with slice ordering based on group levels.\n#'\n#' @param group A character define the groups of the observations.\n#' @inheritParams align\n#' @examples\n#' set.seed(1L)\n#' small_mat <- matrix(rnorm(81), nrow = 9)\n#' ggheatmap(small_mat) +\n#' anno_top() +\n#' align_group(sample(letters[1:4], ncol(small_mat), replace = TRUE))\n#' @export\nalign_group <- function(group, active = NULL) {\n assert_active(active)\n if (vec_size(group) == 0L) {\n cli_abort(\"{.arg group} cannot be empty\")\n }\n active <- update_active(active, new_active(use = FALSE))\n align(\n align = AlignGroup,\n group = group,\n active = active,\n check.param = TRUE\n )\n}\n\n#' @importFrom ggplot2 ggproto\nAlignGroup <- ggproto(\"AlignGroup\", CraftAlign,\n interact_layout = function(self, layout) {\n layout <- ggproto_parent(CraftAlign, self)$interact_layout(layout)\n if (is.null(layout_nobs <- .subset2(layout@design, \"nobs\"))) {\n layout@design[\"nobs\"] <- list(vec_size(self$group))\n } else {\n assert_mismatch_nobs(\n self, layout_nobs, vec_size(self$group),\n arg = \"group\"\n )\n }\n layout\n },\n align = function(self, panel, index) list(self$group, index),\n summary_align = function(self) c(FALSE, TRUE)\n)\n"], ["/ggalign/R/tune.R", "#' Change the shape of the input object\n#'\n#' @param data An R object.\n#' @param shape Usually `NULL` or a string, specifying the new shape for the\n#' object. Refer to the detailed method for allowed values.\n#' @details\n#' In most cases, [`fortify_matrix()`] or [`fortify_data_frame()`] provide full\n#' support for transforming objects. However, some objects may require two\n#' completely different approaches to be fortified. The `tune` function acts as\n#' a helper to create a new class tailored for these objects.\n#' @eval rd_collect_family(\"tune\", \"`tune` method collections\")\n#' @export\ntune <- function(data, shape = NULL) UseMethod(\"tune\")\n\n#' @inherit tune title\n#' @description\n#' - `new_tune`: Creates a new object by wrapping it in a scalar list with\n#' the specified attributes and class.\n#' - `tune_data`: Retrieves the original input data.\n#'\n#' @param x An R object.\n#' @param ... Additional attributes passed to [`structure()`].\n#' @param class A character vector specifying the class name to be added.\n#' @export\nnew_tune <- function(x, ..., class = character()) {\n structure(list(x), ..., class = c(class, \"ggalign_tune\"))\n}\n\n#' @export\n#' @rdname new_tune\ntune_data <- function(x) .subset2(x, 1L)\n\n#' @export\nprint.ggalign_tune <- function(x, ...) {\n print(tune_data(x))\n invisible(x)\n}\n\n#' @export\nfortify_matrix.ggalign_tune <- function(data, ...) {\n cli_abort(\"No {.fn fortify_matrix} method for {.obj_type_friendly {data}}\")\n}\n\n#' @export\nfortify_data_frame.ggalign_tune <- function(data, ...) {\n cli_abort(\n \"No {.fn fortify_data_frame} method for {.obj_type_friendly {data}}\"\n )\n}\n"], ["/ggalign/R/alignpatch-free-vp.R", "#' @inheritParams grid::viewport\n#' @inheritDotParams grid::viewport -x -y -width -height\n#' @return\n#' - `free_vp`: A modified version of `plot` with a `free_vp` class.\n#' @importFrom grid viewport\n#' @export\n#' @rdname free\nfree_vp <- function(plot, x = 0.5, y = 0.5, width = NA, height = NA, ...) {\n UseMethod(\"free_vp\")\n}\n\n#' @export\nfree_vp.default <- function(plot, x = 0.5, y = 0.5,\n width = NA, height = NA, ...) {\n cli_abort(\"Cannot use with {.obj_type_friendly {plot}}\")\n}\n\n#' @export\nfree_vp.ggplot <- function(plot, x = 0.5, y = 0.5,\n width = NA, height = NA, ...) {\n attr(plot, \"vp\") <- viewport(\n x = x, y = y, width = width, height = height, ...,\n )\n add_class(plot, \"free_vp\")\n}\n\n#' @export\nfree_vp.alignpatches <- free_vp.ggplot\n\n####################################################\n#' @importFrom gtable gtable_width gtable_height\n#' @importFrom ggplot2 ggproto ggproto_parent\n#' @export\nalignpatch.free_vp <- function(x) {\n Parent <- NextMethod()\n ggproto(\n \"PatchFreeViewport\", Parent,\n vp = attr(x, \"vp\"),\n align_border = function(self, t = NULL, l = NULL, b = NULL, r = NULL,\n gt = self$gt) {\n ans <- ggproto_parent(Parent, self)$align_border(\n t = t, l = l, b = b, r = r, gt = gt\n )\n vp <- self$vp\n\n if (!any(is_null_unit(widths <- .subset2(ans, \"widths\")))) {\n horizontal_just <- TRUE\n vp$width <- sum(widths)\n } else if (!is.na(as.numeric(vp$width))) {\n # we guess the width from the gtable\n horizontal_just <- TRUE\n vp$width <- max(vp$width, sum(widths))\n } else {\n vp$width <- unit(1, \"npc\")\n horizontal_just <- FALSE\n }\n if (!any(is_null_unit(heights <- .subset2(ans, \"heights\")))) {\n vertical_just <- TRUE\n vp$height <- sum(heights)\n } else if (!is.na(as.numeric(vp$height))) {\n # we guess the height from the gtable\n vertical_just <- TRUE\n vp$height <- max(vp$height, sum(heights))\n } else {\n vp$height <- unit(1, \"npc\")\n vertical_just <- FALSE\n }\n if (horizontal_just || vertical_just) ans$vp <- vp\n ans\n }\n )\n}\n"], ["/ggalign/R/layout-chain-.R", "# Used by both `circle_layout()` and `stack_layout()`\n#' @keywords internal\n#' @include layout-.R\nmethods::setClass(\n \"ChainLayout\",\n contains = \"LayoutProto\",\n list(\n data = \"ANY\",\n name = \"character\", # used to provide message\n plot_list = \"list\", # save the list of plots\n design = \"ANY\" # used to align axis\n )\n)\n\n#' Finalize plot modifications from a ChainLayout object.\n#'\n#' This generic function lets a ChainLayout apply any final transformations\n#' to the composed plot before returning it. It does not extract or store\n#' the plot, but instead allows the layout to inject custom modifications\n#' (e.g., spacing guides, annotations, alignment fixes) at the last step.\n#'\n#' @param layout A ChainLayout object.\n#' @param plot The plot being finalized.\n#' @keywords internal\nchain_decorate <- function(layout, plot) UseMethod(\"chain_decorate\")\n\n#' @export\nchain_decorate.ChainLayout <- function(layout, plot) plot\n\n#' @export\nis_layout_discrete.ChainLayout <- function(x, ...) {\n is_discrete_design(x@design)\n}\n\n#' @export\nis_layout_continuous.ChainLayout <- function(x, ...) {\n is_continuous_design(x@design)\n}\n\n#############################################################\n# To-DO: Use double dispatch\n#' @keywords internal\nchain_layout_add <- function(object, layout, object_name) {\n UseMethod(\"chain_layout_add\")\n}\n\n#' @export\nchain_layout_add.layout_title <- function(object, layout, object_name) {\n layout@titles <- update_non_waive(layout@titles, object)\n layout\n}\n\n#' @export\nchain_layout_add.list <- function(object, layout, object_name) {\n for (o in object) layout <- chain_layout_add(o, layout, object_name)\n layout\n}\n\n#' @export\nchain_layout_add.NULL <- function(object, layout, object_name) {\n layout\n}\n\n#' @export\nchain_layout_add.CraftBox <- function(object, layout, object_name) {\n craftsman <- object@craftsman\n # To-Do: Use S7 and double dispatch\n if (is.null(active_index <- layout@active) ||\n is_craftbox(plot <- .subset2(layout@plot_list, active_index))) {\n # unlock the object\n craftsman$unlock()\n\n # we lock the `Craftsman` object to prevent user from modifying this\n # object in `$build_plot()` method, we shouldn't do any calculations in\n # `$build_plot()` method\n on.exit(craftsman$lock())\n\n # initialize the necessary parameters for `Craftsman` object\n if (is_stack_layout(layout)) {\n craftsman$direction <- layout@direction\n craftsman$position <- .subset2(layout@heatmap, \"position\")\n } else if (is_circle_layout(layout)) {\n # we treat circle layout as a vertical stack layout\n craftsman$direction <- \"vertical\"\n }\n craftsman$in_linear <- is_linear(layout)\n craftsman$layout_name <- object_name(layout)\n\n # firstly, we let the object do some changes in the layout\n layout <- craftsman$interact_layout(layout)\n\n # this step, the object will act with the stack layout\n # group rows into panel or reorder rows, we can also\n # initialize object data\n new_design <- craftsman$setup_design(layout@design)\n\n # initialize the plot object\n object@plot <- craftsman$setup_plot(object@plot)\n\n layout <- chain_add_plot(layout, object, object@active, object_name)\n } else { # should be a QuadLayout object\n plot <- quad_layout_add(object, plot, object_name)\n layout@plot_list[[active_index]] <- plot\n new_design <- slot(plot, layout@direction)\n }\n update_design(layout, design = new_design, object_name = object_name)\n}\n\n#' @export\nchain_layout_add.continuous_limits <- function(object, layout, object_name) {\n if (is_discrete_design(layout@design)) {\n cli_abort(c(\n sprintf(\n \"Cannot add {.var {object_name}} to %s\",\n object_name(layout)\n ),\n i = sprintf(\n \"%s cannot align continuous variables\",\n object_name(layout)\n )\n ))\n }\n update_design(layout, design = object, object_name = object_name)\n}\n\n#' @export\nchain_layout_add.ggplot <- function(object, layout, object_name) {\n chain_layout_add(ggfree(data = object), layout, object_name)\n}\n\n# Add ggplot2 elements\n#' @export\nchain_layout_add.default <- function(object, layout, object_name) {\n if (is.null(active_index <- layout@active)) {\n cli_abort(c(\n sprintf(\n \"Cannot add {.var {object_name}} to %s\",\n object_name(layout)\n ),\n i = \"No active plot component\",\n i = paste(\n \"Did you forget to initialize a {.cls ggplot} object\",\n \"with {.fn ggalign} or {.fn ggfree}?\"\n )\n ))\n }\n plot <- .subset2(layout@plot_list, active_index)\n if (is_craftbox(plot)) {\n plot <- chain_plot_add(plot, object, object_name, TRUE)\n } else {\n plot <- quad_layout_add(object, plot, object_name)\n }\n layout@plot_list[[active_index]] <- plot\n layout\n}\n\n#' @export\nchain_layout_add.layout_theme <- function(object, layout, object_name) {\n if (is.null(active_index <- layout@active) ||\n is_craftbox(plot <- .subset2(layout@plot_list, active_index))) {\n layout@theme <- update_layout_theme(layout@theme, object)\n } else {\n layout@plot_list[[active_index]] <- quad_layout_add(\n object, plot, object_name\n )\n }\n layout\n}\n\nchain_plot_add <- function(plot, object, object_name, force) {\n # if `align` has plot, we added the object\n if (force || !is.null(plot@plot)) {\n plot <- craftbox_add(object, plot, object_name)\n }\n plot\n}\n\nchain_add_plot <- function(layout, plot, active, object_name) {\n # set up context index\n plot_list <- layout@plot_list\n if (.subset2(active, \"use\")) {\n active_index <- length(plot_list) + 1L\n } else {\n active_index <- layout@active\n }\n # check the name is unique\n if (!is.na(name <- .subset2(active, \"name\"))) {\n if (any(names(plot_list) == name)) {\n cli_warn(\n \"Adding {.var {object_name}} will replace existing {.field {name}} plot\"\n )\n }\n plot_list[[name]] <- plot\n } else {\n plot_list <- c(plot_list, list(plot))\n }\n\n # add QuadLayout\n layout@plot_list <- plot_list\n layout@active <- active_index\n layout\n}\n\nswitch_chain_plot <- function(layout, what, call = caller_call()) {\n if (!is.waive(what)) {\n if (!is.null(what)) {\n what <- vec_as_location2(\n what,\n vec_size(layout@plot_list),\n vec_names(layout@plot_list),\n missing = \"error\",\n arg = \"what\", call = call\n )\n }\n layout@active <- what\n }\n layout\n}\n\n##############################################################\n# for `stack_layout()` only\n#' @export\nchain_layout_add.ggalign_with_quad <- function(object, layout, object_name) {\n if (!is_stack_layout(layout)) {\n cli_abort(sprintf(\n \"Cannot add {.var {object_name}} to %s\",\n object_name(layout)\n ))\n }\n if (is.null(active_index <- layout@active) ||\n is_craftbox(plot <- .subset2(layout@plot_list, active_index))) {\n cli_abort(c(\n sprintf(\n \"Cannot add {.var {object_name}} to %s\",\n object_name(layout)\n ),\n i = \"Did you forget to add a {.fn quad_layout}?\"\n ))\n } else {\n layout@plot_list[[active_index]] <- quad_layout_add(\n object, plot, object_name\n )\n }\n layout\n}\n\n#' @export\nchain_layout_add.quad_active <- chain_layout_add.ggalign_with_quad\n\n#' @export\nchain_layout_add.quad_anno <- chain_layout_add.quad_active\n\n#' @export\nchain_layout_add.StackLayout <- chain_layout_add.quad_active\n\n#' @export\nchain_layout_add.StackCross <- function(object, layout, object_name) {\n if (!is_stack_layout(layout)) {\n cli_abort(sprintf(\n \"Cannot add {.var {object_name}} to %s\",\n object_name(layout)\n ))\n }\n\n # preventing from adding `stack_cross` with the same direction in this way,\n # `stack_cross()` cannot be added to the heatmap annotation parallelly with\n # the `stack_layout()`\n if (identical(object@direction, layout@direction)) {\n cli_abort(c(\n sprintf(\n \"Cannot add {.var {object_name}} to %s\",\n object_name(layout)\n ),\n i = \"Cannot add {.fn stack_cross} with the same direction as {.fn stack_discrete}.\"\n ))\n }\n NextMethod() # call StackLayout method\n}\n\n#' @export\nchain_layout_add.stack_switch <- function(object, layout, object_name) {\n if (!is_stack_layout(layout)) {\n cli_abort(c(\n sprintf(\n \"Cannot add {.var {object_name}} to %s\",\n object_name(layout)\n ),\n i = \"Did you want to add a {.fn circle_switch}?\"\n ))\n }\n layout <- switch_chain_plot(\n layout, .subset2(object, \"what\"),\n quote(stack_switch())\n )\n if (!is.null(sizes <- .subset2(object, \"sizes\"))) {\n layout@sizes <- sizes\n }\n layout\n}\n\n#' @importFrom methods slot\n#' @export\nchain_layout_add.QuadLayout <- function(object, layout, object_name) {\n if (!is_stack_layout(layout)) {\n cli_abort(sprintf(\n \"Cannot add {.var {object_name}} to %s\",\n object_name(layout)\n ))\n }\n\n # preventing from adding `stack_cross` with the same direction\n # `cross_link()` cannot be added to the heatmap annotation\n # parallelly with the `stack_cross()`\n if (is_horizontal(direction <- layout@direction)) {\n if (is_cross_layout(object@left) || is_cross_layout(object@right)) {\n cli_abort(c(\n sprintf(\n \"Cannot add {.var {object_name}} to %s\",\n object_name(layout)\n ),\n i = sprintf(\n \"{.field left} or {.field right} annotation contains %s\",\n \"{.fn stack_cross}\"\n )\n ))\n }\n } else if (is_cross_layout(object@top) || is_cross_layout(object@bottom)) {\n cli_abort(c(\n sprintf(\n \"Cannot add {.var {object_name}} to %s\",\n object_name(layout)\n ),\n i = sprintf(\n \"{.field top} or {.field bottom} annotation contains %s\",\n \"{.fn stack_cross}\"\n )\n ))\n }\n\n # check quad layout is compatible with stack layout\n quad_data <- object@data\n stack_design <- layout@design\n quad_design <- slot(object, direction)\n if (is_continuous_design(quad_design)) {\n if (is_discrete_design(stack_design)) {\n cli_abort(c(\n sprintf(\n \"Cannot add %s to %s\",\n object_name(object), object_name(layout)\n ),\n i = sprintf(\n \"%s cannot align continuous variable\",\n object_name(layout)\n )\n ))\n }\n # `quad_layout()` will align continuous variables,\n # `data` can be `NULL`\n extra_design <- slot(object, vec_set_difference(\n c(\"vertical\", \"horizontal\"), direction\n ))\n allow_null <- is_continuous_design(extra_design)\n if (is.waive(quad_data) || is.function(quad_data)) {\n # check if we should initialize the `quad_layout()` data\n if (is.null(stack_data <- layout@data)) {\n if (allow_null) {\n quad_data <- NULL\n } else {\n cli_abort(c(\n sprintf(\n \"you must provide {.arg data} argument in %s\",\n object_name(object)\n ),\n i = sprintf(\n \"no data was found in %s\",\n object_name(layout)\n )\n ))\n }\n } else {\n data <- stack_data # should be a data frame\n if (is.waive(quad_data)) { # inherit from the stack layout\n if (!allow_null) { # we need a matrix\n cli_abort(c(\n sprintf(\n \"Cannot add %s to %s\",\n object_name(object), object_name(layout)\n ),\n i = sprintf(\n \"{.arg data} in %s is %s, but %s need a {.cls matrix}.\",\n object_name(layout),\n \"{.obj_type_friendly {data}}\",\n object_name(object)\n ),\n i = sprintf(\n \"Try provide {.arg data} in %s\",\n object_name(object)\n )\n ))\n }\n } else { # `quad_data` is a function\n data <- quad_data(data)\n # check the data format is correct\n if (allow_null) { # we need a data frame\n if (!is.data.frame(data)) {\n cli_abort(sprintf(\n \"{.arg data} in %s must return a {.cls data.frame}\",\n object_name(object)\n ))\n }\n } else if (!is.matrix(data)) { # we need a matrix\n cli_abort(sprintf(\n \"{.arg data} in %s must return a {.cls matrix}\",\n object_name(object)\n ))\n } else {\n if (NROW(data) == 0L || ncol(data) == 0L) {\n cli_abort(sprintf(\n \"{.arg data} in %s return an empty matrix\",\n object_name(object)\n ))\n }\n }\n }\n # we initialize the `nobs` of the extra_design for the\n # `quad_layout()`\n if (is_horizontal(direction)) {\n if (is_discrete_design(slot(object, \"vertical\"))) {\n slot(object, \"vertical\")$nobs <- ncol(data)\n }\n } else {\n if (is_discrete_design(slot(object, \"horizontal\"))) {\n slot(object, \"horizontal\")$nobs <- nrow(data)\n }\n }\n }\n # restore the ggalign attribute\n object@data <- ggalign_data_restore(data, stack_data)\n }\n layout_design <- quad_design\n } else if (is_discrete_design(stack_design)) {\n # both `quad_layout()` and `stack_layout()` will align discrete\n # variables\n if (is.waive(quad_data) || is.function(quad_data)) {\n if (is.null(stack_data <- layout@data)) {\n cli_abort(c(\n sprintf(\n \"you must provide {.arg data} argument in %s\",\n object_name(object)\n ),\n i = sprintf(\n \"no data was found in %s\",\n object_name(layout)\n )\n ))\n }\n # set `quad_layout()` data\n data <- switch_direction(direction, stack_data, t(stack_data))\n if (is.function(quad_data)) {\n data <- quad_data(data)\n if (!is.matrix(data)) {\n cli_abort(sprintf(\n \"{.arg data} in %s must return a matrix\",\n object_name(object)\n ))\n }\n if (NROW(data) == 0L || ncol(data) == 0L) {\n cli_abort(sprintf(\n \"{.arg data} in %s return an empty matrix\",\n object_name(object)\n ))\n }\n } else {\n if (NROW(data) == 0L || ncol(data) == 0L) {\n cli_abort(c(\n sprintf(\n \"Cannot use data from %s in %s\",\n object_name(layout), object_name(object)\n ),\n i = sprintf(\n \"{.arg data} in %s is an empty matrix\",\n object_name(layout)\n )\n ))\n }\n }\n # set the `nobs` for `quad_layout()`\n if (is_horizontal(direction)) {\n quad_design$nobs <- nrow(data)\n if (is_discrete_design(slot(object, \"vertical\"))) {\n slot(object, \"vertical\")$nobs <- ncol(data)\n }\n } else {\n quad_design$nobs <- ncol(data)\n if (is_discrete_design(slot(object, \"horizontal\"))) {\n slot(object, \"horizontal\")$nobs <- nrow(data)\n }\n }\n # restore the ggalign attribute\n object@data <- ggalign_data_restore(data, stack_data)\n }\n layout_design <- melt_discrete_design(\n stack_design, quad_design,\n old_name = object_name(layout),\n new_name = object_name\n )\n } else {\n cli_abort(c(\n sprintf(\n \"Cannot add %s to %s\",\n object_name(object), object_name(layout)\n ),\n i = sprintf(\n \"%s cannot align discrete variable\",\n object_name(layout)\n )\n ))\n }\n stack <- chain_add_plot(layout, object, object@plot_active, object_name)\n update_design(\n stack,\n design = layout_design,\n object_name = object_name\n )\n}\n\n##################################################\n#' @export\nchain_layout_add.circle_switch <- function(object, layout, object_name) {\n if (!is_circle_layout(layout)) {\n cli_abort(c(\n sprintf(\n \"Cannot add {.var {object_name}} to %s\",\n object_name(layout)\n ),\n i = \"Did you want to add a {.fn stack_switch}?\"\n ))\n }\n if (!is.waive(radial <- .subset2(object, \"radial\"))) {\n layout@radial <- radial\n }\n if (!is.null(direction <- .subset2(object, \"direction\"))) {\n layout@direction <- direction\n }\n layout <- switch_chain_plot(\n layout, .subset2(object, \"what\"),\n quote(circle_switch())\n )\n layout\n}\n"], ["/ggalign/R/layout-chain-stack-.R", "#' Arrange plots horizontally or vertically\n#'\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' If `limits` is provided, a continuous variable will be required and aligned\n#' in the direction specified (`stack_continuous`). Otherwise, a discrete\n#' variable will be required and aligned (`stack_discrete`).\n#'\n#' Several aliases are provided for convenience:\n#' - `stack_vertical`: A special case of `stack_layout` that sets `direction\n#' = \"v\"`.\n#' - `stack_horizontal`: A special case of `stack_layout` that sets `direction\n#' = \"h\"`.\n#' - `stack_discretev`: A special case of `stack_discrete` that sets `direction\n#' = \"v\"`.\n#' - `stack_discreteh`: A special case of `stack_discrete` that sets `direction\n#' = \"h\"`.\n#' - `stack_continuousv()`: A special case of `stack_free` that sets `direction\n#' = \"v\"`.\n#' - `stack_continuoush()`: A special case of `stack_free` that sets `direction\n#' = \"h\"`.\n#'\n#' For historical reasons, the following aliases are available:\n#' - `stack_align` is an alias for `stack_discrete`.\n#' - `stack_alignv` is an alias for `stack_discretev`.\n#' - `stack_alignh` is an alias for `stack_discreteh`.\n#' - `stack_free` is an alias for `stack_continuous`.\n#' - `stack_freev` is an alias for `stack_continuousv`.\n#' - `stack_freeh` is an alias for `stack_continuoush`.\n#'\n#' @param direction A string indicating the direction of the stack layout,\n#' either `\"h\"`(`horizontal`) or `\"v\"`(`vertical`).\n#' @param data `r rd_layout_data()`:\n#' - If `limits` is not provided, [`fortify_matrix()`] will be used to get a\n#' matrix.\n#' - If `limits` is specified, [`fortify_data_frame()`] will be used to get a\n#' data frame.\n#'\n#' @param ... Additional arguments passed to [`fortify_data_frame()`] or\n#' [`fortify_matrix()`].\n#' @param theme A [`theme()`][ggplot2::theme] object used to customize various\n#' elements of the layout, including `guides`, `title`, `subtitle`, `caption`,\n#' `margins`, `panel.border`, and `background`. By default, the theme will\n#' inherit from the parent `layout`. It also controls the panel spacing for all\n#' plots in the layout.\n#'\n#' @param sizes A numeric value or a [`unit`][grid::unit] object. When used for\n#' the [`quad_layout()`] annotation, it must be of length `1`. When used in the\n#' [`stack_layout()`] with a nested [`quad_layout()`], it should be of length\n#' `3`, specifying the relative heights (for `direction = \"h\"`) or widths (for\n#' `direction = \"v\"`) to be applied to the layout.\n#' @param limits A [`continuous_limits()`] object specifying the left/lower\n#' limit and the right/upper limit of the scale. Used to align the continuous\n#' axis.\n#' @return A `StackLayout` object.\n#' @examples\n#' set.seed(123)\n#' small_mat <- matrix(rnorm(56), nrow = 7L)\n#'\n#' stack_horizontal(small_mat) + align_dendro()\n#'\n#' # this is the same with:\n#' stack_discrete(\"h\", small_mat) + align_dendro()\n#'\n#' stack_discreteh(small_mat) + align_dendro()\n#'\n#' # For vertical layout:\n#' stack_vertical(small_mat) + align_dendro()\n#'\n#' @export\nstack_layout <- function(direction, data = NULL, ...,\n theme = NULL, sizes = NA, limits = waiver()) {\n if (is.waive(limits)) {\n stack_discrete(\n data = data, direction = direction, ...,\n theme = theme, sizes = sizes\n )\n } else {\n stack_continuous(\n data = data, direction = direction, ...,\n theme = theme, sizes = sizes, limits = limits\n )\n }\n}\n\n#' @export\n#' @rdname stack_layout\nstack_horizontal <- function(data = NULL, ..., limits = waiver()) {\n stack_layout(data = data, direction = \"h\", limits = limits, ...)\n}\n\n#' @export\n#' @rdname stack_layout\nstack_vertical <- function(data = NULL, ..., limits = waiver()) {\n stack_layout(data = data, direction = \"v\", limits = limits, ...)\n}\n\n###################################################################\n#' @export\n#' @rdname stack_layout\nstack_discrete <- function(direction, data = NULL, ...,\n theme = NULL, sizes = NA) {\n UseMethod(\"stack_discrete\", data)\n}\n\n#' @usage NULL\n#' @export\n#' @rdname stack_layout\nstack_align <- stack_discrete\n\n#' @export\n#' @rdname stack_layout\nstack_discretev <- function(data = NULL, ...) {\n stack_discrete(data = data, direction = \"v\", ...)\n}\n\n#' @usage NULL\n#' @export\n#' @rdname stack_layout\nstack_alignv <- stack_discretev\n\n#' @export\n#' @rdname stack_layout\nstack_discreteh <- function(data = NULL, ...) {\n stack_discrete(data = data, direction = \"h\", ...)\n}\n\n#' @usage NULL\n#' @export\n#' @rdname stack_layout\nstack_alignh <- stack_discreteh\n\n#' @export\nstack_discrete.default <- function(direction, data = NULL, ...,\n theme = NULL, sizes = NA) {\n direction <- check_direction(direction)\n # the observations are rows, we use matrix to easily\n # reshape it into a long formated data frame for ggplot,\n # and we can easily determine the number of observations\n # from matrix\n data <- data %|w|% NULL\n data <- fortify_matrix(data = data, ...)\n schemes <- default_schemes()\n if (!is.null(data) && !is.function(data)) {\n # if we have provided data, we initialize the `nobs`\n nobs <- vec_size(data)\n\n # for data has dimention but one dimention is 0\n # as.matrix(data.frame(row.names = letters))\n if (nobs == 0L) {\n cli_abort(\"empty data is no allowed\")\n }\n } else {\n nobs <- NULL\n }\n new_stack_layout(\n name = \"stack_discrete\",\n data = data, direction = direction,\n design = discrete_design(nobs = nobs),\n schemes = schemes, theme = theme, sizes = sizes\n )\n}\n\n#' @export\nstack_discrete.function <- function(direction, data = NULL, ...) {\n cli_abort(paste0(\n \"{.arg data} must be a {.cls matrix}, \",\n \"or an object coercible by {.fn fortify_matrix}, or a valid \",\n \"{.cls matrix}-like object coercible by {.fn as.matrix}\"\n ))\n}\n\n#' @export\nstack_discrete.formula <- stack_discrete.function\n\n################################################################\n#' @export\n#' @rdname stack_layout\nstack_continuous <- function(direction, data = NULL, ..., limits = NULL,\n theme = NULL, sizes = NA) {\n UseMethod(\"stack_continuous\", data)\n}\n\n#' @usage NULL\n#' @export\n#' @rdname stack_layout\nstack_free <- stack_continuous\n\n#' @export\n#' @rdname stack_layout\nstack_continuousv <- function(data = NULL, ...) {\n stack_continuous(data = data, direction = \"v\", ...)\n}\n\n#' @usage NULL\n#' @export\n#' @rdname stack_layout\nstack_freev <- stack_continuousv\n\n#' @export\n#' @rdname stack_layout\nstack_continuoush <- function(data = NULL, ...) {\n stack_continuous(data = data, direction = \"h\", ...)\n}\n\n#' @usage NULL\n#' @export\n#' @rdname stack_layout\nstack_freeh <- stack_continuoush\n\n#' @export\nstack_continuous.default <- function(direction, data = NULL, ...,\n limits = NULL, theme = NULL, sizes = NA) {\n assert_limits(limits)\n direction <- check_direction(direction)\n data <- data %|w|% NULL\n data <- fortify_data_frame(data = data, ...)\n schemes <- default_schemes()\n new_stack_layout(\n name = \"stack_continuous\",\n data = data, direction = direction, design = limits,\n schemes = schemes, theme = theme, sizes = sizes\n )\n}\n\n#' @export\nstack_continuous.function <- function(direction, data = NULL, ...) {\n cli_abort(paste0(\n \"{.arg data} must be a {.cls data.frame}, \",\n \"or an object coercible by {.fn fortify_data_frame}, or a valid \",\n \"{.cls data.frame}-like object coercible by {.fn as.data.frame}\"\n ))\n}\n\n#' @export\nstack_continuous.formula <- stack_continuous.function\n\n#' @importFrom methods new\nnew_stack_layout <- function(data, direction, design,\n schemes = NULL, theme = NULL, sizes = NA,\n name = NULL, call = caller_call()) {\n sizes <- check_stack_sizes(sizes, call = call)\n if (!is.null(theme)) assert_s3_class(theme, \"theme\", call = call)\n if (is.null(name)) {\n if (is_continuous_design(design)) {\n name <- \"stack_continuous\"\n } else {\n name <- \"stack_discrete\"\n }\n }\n new(\n \"StackLayout\",\n name = name, data = data,\n direction = direction,\n theme = theme, schemes = schemes, # used by the layout\n sizes = sizes, design = design\n )\n}\n\n############################################################\n# Used to place multiple objects in one axis\n#' @importFrom grid unit\n#' @importFrom ggplot2 waiver\n#' @keywords internal\n#' @include layout-chain-.R\nmethods::setClass(\n \"StackLayout\",\n contains = \"ChainLayout\",\n list(\n direction = \"character\",\n heatmap = \"list\", # used by heatmap annotation\n sizes = \"ANY\" # used by stack layout\n ),\n prototype = list(\n heatmap = list(\n position = NULL,\n free_guides = waiver(),\n # indicate whether or not the data is from the quad-layout matrix\n quad_matrix = FALSE\n )\n )\n)\n"], ["/ggalign/R/craft-cross-.R", "cross <- function(cross = NULL, data = waiver(),\n data_params = list(), ...,\n inherit_index = NULL,\n inherit_panel = NULL,\n inherit_nobs = NULL,\n plot = NULL, active = NULL, size = NULL, schemes = NULL,\n data_arg = caller_arg(data),\n call = caller_call()) {\n if (override_call(call)) {\n call <- current_call()\n }\n new_craftbox(\n craftsman = cross %||% CraftCross,\n data = allow_lambda(data), data_params = data_params,\n ...,\n inherit_nobs = inherit_nobs,\n inherit_panel = inherit_panel,\n inherit_index = inherit_index,\n plot = plot, active = active, size = size, schemes = schemes,\n data_arg = data_arg, call = call\n )\n}\n\n#' @importFrom ggplot2 ggproto ggproto_parent\n#' @include craftbox-.R\nCraftCross <- ggproto(\n \"CraftCross\", Craftsman,\n free_facet = TRUE,\n free_limits = TRUE,\n data_params = NULL,\n inherit_nobs = NULL,\n inherit_panel = NULL,\n inherit_index = NULL,\n interact_layout = function(self, layout) {\n # 1. check layout is `*_cross()`\n # 2. add `cross_points`\n # 3. add `odesign`\n # 4. define `labels`, we'll rename the `labels` to `labels0`\n layout <- ggproto_parent(CrossGg, self)$interact_layout(layout)\n\n # will define `labels0`\n self$labels0 <- self$labels\n\n # check the previous (between two `break_points`) define has been\n # initialized\n if (length(layout@break_points) &&\n is.null(.subset2(layout@design, \"nobs\"))) {\n cli_abort(sprintf(\n \"layout {.field nobs} for %s must be initialized before adding %s\",\n self$layout_name, object_name(self)\n ))\n }\n\n # setup data\n layout_data <- layout@data\n design <- layout@design\n\n if (is.waive(input_data <- self$data)) { # inherit from the layout\n data <- layout_data\n # `data` is NULL, `inherit_nobs` can be `TRUE` or `FALSE`, we by\n # default regard `inherit_nobs` as `TRUE`\n if (is.null(data) && isFALSE(self$inherit_nobs)) {\n design[\"nobs\"] <- list(NULL)\n }\n\n # `data` is not `NULL`, the `nobs` will always be the same with\n # previous design, nothing to do\n } else {\n if (is.function(input_data)) {\n if (is.null(layout_data)) {\n cli_abort(c(\n sprintf(\n \"{.arg data} in %s cannot be a function\",\n object_name(self)\n ),\n i = sprintf(\"no data was found in %s\", self$layout_name)\n ))\n }\n data <- input_data(layout_data)\n } else {\n data <- input_data\n }\n data <- inject(\n fortify_matrix(\n data, !!!self$data_params,\n data_arg = self$data_arg,\n call = self$call\n )\n ) %|w|% NULL\n if (isTRUE(self$inherit_nobs)) { # we require inherit nobs\n # we check if the data match original data dimention\n if (!is.null(data) &&\n !is.null(.subset2(design, \"nobs\")) &&\n NROW(data) != .subset2(design, \"nobs\")) {\n cli_abort(c(\n sprintf(\n \"%s (nobs: %d) is not compatible with the %s (nobs: %d)\",\n object_name(self), NROW(data), layout_name, layout_nobs\n ),\n i = \"try to set {.code inherit_nobs = FALSE}\"\n ))\n }\n } else { # for `FALSE` and `NULL`\n if (is.null(data)) {\n design[\"nobs\"] <- list(NULL)\n } else {\n if (NROW(data) == 0L) {\n cli_abort(\"{.arg data} cannot be empty\",\n call = self$call\n )\n }\n design[\"nobs\"] <- list(NROW(data))\n }\n }\n }\n\n # we keep the names from the layout data for usage\n self$labels <- vec_names(data)\n\n # determine if we should inherit panel\n # by default, `inherit_panel = FALSE`\n if (isTRUE(self$inherit_panel)) {\n if (is.null(self$labels0)) {\n cli_abort(c(\n \"Cannot inherit panel from the layout\",\n i = \"No labels found in the layout data\"\n ))\n }\n if (is.null(self$labels)) {\n cli_abort(c(\n \"Cannot inherit panel from the layout\",\n i = \"No labels found in the current {.arg data}\"\n ))\n }\n if (!all(self$labels %in% self$labels0)) {\n cli_abort(c(\n \"Cannot inherit panel from the layout\",\n i = \"Some labels in the current data are not found in the previous layout data\"\n ))\n }\n if (!is.null(panel <- .subset2(design, \"panel\"))) {\n design[\"panel\"] <- list(\n droplevels(panel[match(self$labels, self$labels0)])\n )\n }\n } else {\n design[\"panel\"] <- list(NULL)\n }\n\n # determine if we should inherit panel\n # by default, `inherit_index = FALSE`\n if (isTRUE(self$inherit_index)) {\n if (is.null(self$labels0)) {\n cli_abort(c(\n \"Cannot inherit ordering index from the layout\",\n i = \"No labels found in the previous layout data\"\n ))\n }\n\n if (is.null(self$labels)) {\n cli_abort(c(\n \"Cannot inherit ordering index from the layout\",\n i = \"No labels found in the current {.arg data}\"\n ))\n }\n\n if (!all(self$labels %in% self$labels0)) {\n cli_abort(c(\n \"Cannot inherit ordering index from the layout\",\n i = \"Some labels in the current data are not found in the previous layout data\"\n ))\n }\n\n if (!is.null(index <- .subset2(design, \"index\"))) {\n new_index <- order(match(\n self$labels,\n vec_slice(self$labels0, index)\n ))\n\n # we always make the index following the panel\n if (!is.null(panel <- .subset2(design, \"panel\"))) {\n new_index <- reorder_index(panel, new_index)\n }\n design[\"index\"] <- list(new_index)\n }\n } else {\n design[\"index\"] <- list(NULL)\n }\n\n # reset layout data\n layout@data <- data # don't restore the attribute\n\n # update the design\n layout@design <- design\n\n # udpate break_points\n layout@break_points <- c(layout@break_points, length(layout@plot_list))\n layout\n }\n)\n"], ["/ggalign/R/craft-align-kmeans.R", "#' Split observations by k-means clustering groups.\n#'\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' Aligns and groups observations based on k-means clustering, enabling\n#' observation splits by cluster groups.\n#'\n#' @inheritDotParams stats::kmeans -x -centers\n#' @param data A numeric matrix to be used by k-means. By default, it will\n#' inherit from the layout matrix.\n#' @inheritParams align\n#' @inheritSection align Discrete Axis Alignment\n#' @examples\n#' ggheatmap(matrix(rnorm(81), nrow = 9)) +\n#' anno_top() +\n#' align_kmeans(3L)\n#' @importFrom rlang list2\n#' @export\nalign_kmeans <- function(..., data = NULL, active = NULL) {\n assert_active(active)\n active <- update_active(active, new_active(use = FALSE))\n align(\n align = AlignKmeans,\n params = list2(...),\n active = active,\n data = data\n )\n}\n\n#' @importFrom ggplot2 ggproto\n#' @importFrom rlang inject\nAlignKmeans <- ggproto(\"AlignKmeans\", CraftAlign,\n interact_layout = function(self, layout) {\n ggproto_parent(AlignOrder2, self)$interact_layout(layout)\n },\n compute = function(self, panel, index) {\n inject(stats::kmeans(x = self$data, !!!self$params))\n },\n align = function(self, panel, index) {\n list(.subset2(self$statistics, \"cluster\"), index)\n },\n summary_align = function(self) c(FALSE, TRUE)\n)\n"], ["/ggalign/R/layout-chain-circle-switch.R", "#########################################################\n#' Determine the active context of circle layout\n#'\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' @inheritParams rlang::args_dots_empty\n#' @inheritParams circle_discrete\n#' @param what What should get activated for the [`circle_layout()`]?\n#' `r rd_chain_what()`.\n#' @return A `circle_switch` object which can be added to [`circle_layout()`].\n#' @examples\n#' set.seed(123)\n#' small_mat <- matrix(rnorm(56), nrow = 7)\n#' rownames(small_mat) <- paste0(\"row\", seq_len(nrow(small_mat)))\n#' colnames(small_mat) <- paste0(\"column\", seq_len(ncol(small_mat)))\n#' circle_discrete(small_mat) +\n#' ggalign() +\n#' geom_tile(aes(y = .column_index, fill = value)) +\n#' scale_fill_viridis_c() +\n#' align_dendro(aes(color = branch), k = 3L) +\n#' scale_color_brewer(palette = \"Dark2\")\n#' @export\ncircle_switch <- function(radial = waiver(), direction = NULL,\n what = waiver(), ...) {\n rlang::check_dots_empty()\n if (!is.waive(radial) && !is.null(radial)) {\n assert_s3_class(radial, \"CoordRadial\")\n if (abs(diff(radial$arc)) < pi / 2L) {\n cli_abort(\"Cannot use circle of acute angle < 90 in {.arg radial}\")\n }\n }\n if (!is.null(direction)) {\n direction <- arg_match0(direction, c(\"inward\", \"outward\"))\n }\n if (!is.waive(what)) what <- check_stack_context(what)\n structure(list(what = what, radial = radial, direction = direction),\n class = \"circle_switch\"\n )\n}\n"], ["/ggalign/R/scheme-data.R", "#' Plot data Specifications\n#'\n#' @description\n#' `r lifecycle::badge('experimental')`\n#'\n#' Transforms the plot data. Many functions in this package require a specific\n#' data format to align observations, `scheme_data()` helps reformat data frames\n#' as needed.\n#'\n#' @param data A function to transform the plot data before rendering.\n#' Acceptable values include:\n#'\n#' - `NULL`: No action taken.\n#' - [`waiver()`][ggplot2::waiver()]: Inherits from the parent layout.\n#' - A `function` or purrr-style `formula`: Used to transform the plot data,\n#' which should accept a data frame and return a data frame. You can apply\n#' this after the parent layout `scheme_data` function, using the `inherit`\n#' argument.\n#'\n#' Use this hook to modify the data for all `geoms` after the layout is created\n#' (for matrix data, it has been melted to a long format data frame) but before\n#' rendering by `ggplot2`. The returned data must be a data frame for ggplot.\n#'\n#' @param inherit A single boolean value indicates whether to apply the parent\n#' `scheme_data` first and then apply the specified `scheme_data` for the plot.\n#' Defaults to `FALSE`.\n#'\n#' @details\n#' Defaults will attempt to inherit from the parent layout if the actual data is\n#' inherited from the parent layout, with one exception: `align_dendro()`, which\n#' will not inherit the `scheme_data` by default.\n#'\n#' @export\nscheme_data <- function(data, inherit = FALSE) {\n data <- check_scheme_data(data)\n assert_bool(inherit)\n new_scheme_data(data, inherit)\n}\n\nnew_scheme_data <- function(data = NULL, inherit = FALSE) {\n new_scheme(\n name = \"scheme_data\",\n list(data = data, inherit = inherit),\n class = \"scheme_data\"\n )\n}\n\n#' @export\ninherit_scheme.scheme_data <- function(scheme, pscheme) {\n if (is.null(o <- .subset2(scheme, \"data\"))) return(scheme) # styler: off\n if (is.waive(o)) return(pscheme) # inherit from parent; styler: off\n if (!is.function(p_function <- .subset2(pscheme, \"data\"))) {\n return(scheme)\n }\n # if both are function, we check if we should call parent first then call\n # itself\n if (.subset2(scheme, \"inherit\")) {\n user_scheme_data <- o # current action data function\n scheme$data <- function(data) {\n # we always restore the attached attribute\n ans <- ggalign_data_restore(p_function(data), data)\n user_scheme_data(ans)\n }\n }\n scheme\n}\n\n#' @export\nplot_add_scheme.scheme_data <- function(plot, scheme) {\n # by default, we won't change the data\n if (!is.null(scheme_data <- .subset2(scheme, \"data\") %|w|% NULL) &&\n !is.null(raw_data <- plot$data)) {\n # To be compatible with ggplot2, it must be a data frame\n if (!is.null(data <- scheme_data(raw_data)) &&\n !is.waive(data) &&\n !is.data.frame(data)) {\n cli_abort(\"{.fn scheme_data} must return a {.cls data.frame}\")\n }\n plot <- gguse_data(plot, data)\n }\n plot\n}\n"], ["/ggalign/R/alignpatch-inset.R", "#' Create a ggplot inset\n#'\n#' @inheritParams ggwrap\n#' @return A `patch_inset` object, which can be added in ggplot.\n#' @inherit patch seealso\n#' @examples\n#' library(grid)\n#' p1 <- ggplot(mtcars) +\n#' geom_point(aes(mpg, disp))\n#' p2 <- ggplot(mtcars) +\n#' geom_boxplot(aes(gear, disp, group = gear))\n#' p1 + inset(p2, vp = viewport(0.6, 0.6,\n#' just = c(0, 0), width = 0.4, height = 0.4\n#' ))\n#' @export\ninset <- function(\n plot,\n ...,\n align = \"panel\",\n on_top = TRUE,\n clip = TRUE,\n vp = NULL) {\n make_inset(\n plot = plot,\n ...,\n align = align,\n on_top = on_top,\n clip = clip,\n vp = vp\n )\n}\n\n#' @importFrom grid editGrob\n#' @importFrom rlang arg_match0\nmake_inset <- function(\n plot,\n ...,\n align,\n on_top,\n clip,\n vp,\n call = caller_call()) {\n assert_bool(on_top, call = call)\n align <- arg_match0(align, c(\"panel\", \"plot\", \"full\"), error_call = call)\n assert_bool(clip, call = call)\n assert_s3_class(vp, \"viewport\", allow_null = TRUE, call = call)\n if (!is.grob(grob <- patch(x = plot, ...))) {\n cli_abort(\"{.fn patch} must return a {.cls grob}\", call = call)\n }\n if (!is.null(vp)) grob <- editGrob(grob, vp = vp)\n structure(\n list(\n grob = grob,\n align = align,\n clip = if (clip) \"on\" else \"off\",\n on_top = on_top\n ),\n class = \"patch_inset\"\n )\n}\n\n#' @importFrom grid grid.draw\n#' @export\ngrid.draw.patch_inset <- function(x, recording = TRUE) {\n grid.draw(.subset2(x, \"grob\"))\n}\n\n#' @importFrom ggplot2 ggplot_add\n#' @export\nggplot_add.patch_inset <- function(object, plot, object_name, ...) {\n make_wrap(plot, object)\n}\n"], ["/ggalign/R/layer-order.R", "#' Change the layer adding order\n#'\n#' @description\n#' This function allows you to change the order in which layers are added to a\n#' ggplot.\n#'\n#' @param layer A [`layer geometry`][ggplot2::layer_geoms] object to be added.\n#' @param order An integer indicating the position at which the layer should be\n#' added. If `<= 0`, the layer will be added at the beginning. If greater than\n#' the number of plot layers, it will be added at the end.\n#' @return A `layer_order` object.\n#' @examples\n#' ggplot(faithfuld, aes(waiting, eruptions)) +\n#' geom_raster(aes(fill = density)) +\n#' geom_point(color = \"red\", size = 1)\n#' ggplot(faithfuld, aes(waiting, eruptions)) +\n#' geom_raster(aes(fill = density)) +\n#' layer_order(geom_point(color = \"red\", size = 1))\n#' @export\nlayer_order <- function(layer, order = 0) {\n assert_number_decimal(order)\n UseMethod(\"layer_order\")\n}\n\n#' @export\nlayer_order.default <- function(layer, order = 0) {\n cli_abort(\"{.arg layer} must be a {.fn geom_*} object\")\n}\n\n#' @export\nlayer_order.Layer <- function(layer, order = 0) {\n if (!is.infinite(order)) order <- vec_cast(order, integer())\n structure(\n list(\n object = layer,\n order = order,\n # used for `ggplot_add`\n object_name = paste(deparse(substitute(layer)), collapse = \" \")\n ),\n class = \"ggalign_layer_order\"\n )\n}\n\n#' @export\nlayer_order.ggalign_layer_order <- function(layer, order = 0) {\n if (!is.infinite(order)) order <- vec_cast(order, integer())\n layer$order <- order\n layer\n}\n\n#' @importFrom ggplot2 ggplot_add\n#' @export\nggplot_add.ggalign_layer_order <- function(object, plot, object_name, ...) {\n # ggplot2 will do something special for the layer\n # add layer_name, we re-call the method for the layer\n ans <- ggplot_add(\n .subset2(object, \"object\"),\n plot, .subset2(object, \"object_name\")\n )\n if ((cur <- length(layers <- ans$layers)) == 1L) {\n return(ans)\n }\n order <- .subset2(object, \"order\")\n layer <- .subset2(layers, cur)\n if (order >= length(layers)) return(ans) # styler: off\n if (order <= 0L) {\n layers <- append(vec_slice(layers, -cur), layer, 0L)\n } else {\n layers <- append(vec_slice(layers, -cur), layer, order)\n }\n ans$layers <- layers\n ans\n}\n"], ["/ggalign/R/layout-quad-switch.R", "#' Determine the Active Context of Quad-Layout\n#'\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' - `quad_active`: Sets the active context to the `r rd_quad()` itself.\n#' - `quad_anno`: Sets the active context to the specified annotation stack\n#' based on the `position` argument.\n#' - `anno_top`: A special case of `quad_anno` with `position = \"top\"`.\n#' - `anno_left`: A special case of `quad_anno` with `position = \"left\"`.\n#' - `anno_bottom`: A special case of `quad_anno` with `position = \"bottom\"`.\n#' - `anno_right`: A special case of `quad_anno` with `position = \"right\"`.\n#'\n#' @inheritParams quad_layout\n#' @return An object that can be added to `r rd_quad()`.\n#' @export\n#' @rdname quad_active\nquad_active <- function(width = NULL, height = NULL) {\n if (!is.null(width)) width <- check_size(width)\n if (!is.null(height)) height <- check_size(height)\n structure(\n list(width = width, height = height),\n class = c(\"quad_active\", \"quad_switch\")\n )\n}\n\n#' @details\n#' By default, `quad_anno()` attempts to initialize the annotation stack layout\n#' using data from `r rd_quad()`. However, in situations where you want to use\n#' different data for the annotation stack, you can set `initialize = FALSE`\n#' and then provide a custom `stack_layout()`.\n#'\n#' @param position `r rd_quad_position(\"activated\")`.\n#' @param size A numeric value or an [`unit`][grid::unit] object to set the\n#' total `height`/`width` of the annotation stack.\n#' - If `position` is `\"top\"` or `\"bottom\"`, `size` sets the total height of\n#' the annotation.\n#' - If `position` is `\"left\"` or `\"right\"`, `size` sets the total width of the\n#' annotation.\n#' @param free_guides Override the `guides` collection behavior specified in the\n#' `r rd_quad()` for the annotation stack.\n#' @param initialize A boolean indicating whether the annotation stack should be\n#' initialized if it is not already. By default, the annotation stack layout\n#' will attempt to initialize when the data is compatible. If set to `TRUE`, and\n#' the data in `r rd_quad()` is incompatible with the annotation stack, no\n#' data will be used in the stack.\n#' @param what What should get activated in the annotation stack?\n#' `r rd_chain_what()`.\n#' @seealso [`quad_switch()`]\n#' @export\n#' @rdname quad_active\nquad_anno <- function(position, size = NULL, free_guides = waiver(),\n initialize = NULL, what = waiver()) {\n if (is.null(position)) {\n cli_abort(c(\n paste(\n \"{.arg position} must be a single string of\",\n \"{oxford_or(.TLBR)}, not `NULL`\"\n ),\n i = \"Do you want to set the active context to the `quad_layout()` with {.fn quad_active}?\"\n ))\n }\n position <- match.arg(position, .TLBR)\n quad_switch_anno(\n size = size, free_guides = free_guides,\n initialize = initialize, what = what,\n position = position\n )\n}\n\n#' @export\n#' @rdname quad_active\nanno_top <- function(size = NULL, free_guides = waiver(), initialize = NULL,\n what = waiver()) {\n quad_switch_anno(\n size = size, free_guides = free_guides,\n initialize = initialize, what = what,\n position = \"top\"\n )\n}\n\n#' @export\n#' @rdname quad_active\nanno_left <- function(size = NULL, free_guides = waiver(), initialize = NULL,\n what = waiver()) {\n quad_switch_anno(\n size = size, free_guides = free_guides,\n initialize = initialize, what = what,\n position = \"left\"\n )\n}\n\n#' @export\n#' @rdname quad_active\nanno_bottom <- function(size = NULL, free_guides = waiver(), initialize = NULL,\n what = waiver()) {\n quad_switch_anno(\n size = size, free_guides = free_guides,\n initialize = initialize, what = what,\n position = \"bottom\"\n )\n}\n\n#' @export\n#' @rdname quad_active\nanno_right <- function(size = NULL, free_guides = waiver(), initialize = NULL,\n what = waiver()) {\n quad_switch_anno(\n size = size, free_guides = free_guides,\n initialize = initialize, what = what,\n position = \"right\"\n )\n}\n\nquad_switch_anno <- function(position, size, free_guides, initialize, what,\n call = caller_call()) {\n if (!is.null(size)) size <- check_size(size, call = call)\n assert_layout_position(free_guides, call = call)\n if (!is.waive(what)) what <- check_stack_context(what, call = call)\n assert_bool(initialize, allow_null = TRUE)\n structure(\n list(\n position = position, size = size,\n free_guides = free_guides, what = what,\n initialize = initialize\n ),\n class = c(\"quad_anno\", \"quad_switch\")\n )\n}\n\n#' Initialize Quad-Layout Annotation\n#'\n#' @description\n#' `r lifecycle::badge(\"deprecated\")`\n#'\n#' This function was deprecated, you can add `stack_layout()` directly.\n#'\n#' @export\n#' @keywords internal\nquad_init <- function(position, data = waiver(), ...) {\n lifecycle::deprecate_stop(\"0.0.6\", \"quad_init()\", \"stack_layout()\")\n}\n\n#' @inherit quad_active title return\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' `quad_switch()` integrates [`quad_active()`] and [`quad_anno()`] into one\n#' function for ease of use. This function allows you to quickly change the\n#' active context of the [`quad_layout()`] and its annotations.\n#'\n#' `hmanno` is an alias for `quad_switch`, with additional arguments for\n#' backward compatibility\n#'\n#' @param position `r rd_quad_position(\"activated\")`. If `NULL`, it sets the\n#' active context to the `r rd_quad()` itself.\n#' @inheritParams rlang::args_dots_empty\n#' @inheritParams quad_active\n#' @examples\n#' ggheatmap(matrix(rnorm(81), nrow = 9)) +\n#' anno_top() +\n#' align_dendro()\n#' @importFrom ggplot2 waiver\n#' @seealso [`quad_active()`]/[`quad_anno()`]\n#' @export\nquad_switch <- function(position = NULL, size = NULL,\n width = NULL, height = NULL, free_guides = waiver(),\n initialize = NULL, what = waiver()) {\n if (is.null(position)) {\n quad_active(width = width, height = height)\n } else {\n position <- match.arg(position, .TLBR)\n quad_switch_anno(\n size = size,\n free_guides = free_guides, what = what,\n initialize = initialize,\n position = position\n )\n }\n}\n\n#' @inheritParams heatmap_layout\n#' @export\n#' @rdname quad_switch\nhmanno <- quad_switch\n"], ["/ggalign/R/layout-chain-operator.R", "#' @keywords internal\nchain_layout_subtract <- function(object, layout, object_name) {\n UseMethod(\"chain_layout_subtract\")\n}\n\n#' @export\nchain_layout_subtract.default <- function(object, layout, object_name) {\n if (is.null(active_index <- layout@active) ||\n is_craftbox(plot <- .subset2(layout@plot_list, active_index))) {\n layout@plot_list <- lapply(layout@plot_list, function(plot) {\n if (is_craftbox(plot)) {\n chain_plot_add(plot, object, object_name, force = FALSE)\n } else {\n plot\n }\n })\n } else {\n layout@plot_list[[active_index]] <- quad_layout_subtract(\n object, plot, object_name\n )\n }\n layout\n}\n\n# for objects can inherit from layout\n#' @export\nchain_layout_subtract.ggalign_scheme <- function(object, layout, object_name) {\n if (is.null(active_index <- layout@active) ||\n is_craftbox(plot <- .subset2(layout@plot_list, active_index))) {\n layout <- update_layout_scheme(object, layout, object_name)\n } else {\n layout@plot_list[[active_index]] <- quad_layout_subtract(\n object, plot, object_name\n )\n }\n layout\n}\n\n#' @export\nchain_layout_subtract.ggalign_with_quad <- function(object, layout,\n object_name) {\n if (!is_stack_layout(layout)) {\n cli_abort(sprintf(\n \"Cannot add {.var {object_name}} to %s\",\n object_name(layout)\n ))\n }\n if (is.null(active_index <- layout@active) ||\n is_craftbox(plot <- .subset2(layout@plot_list, active_index))) {\n inner <- .subset2(object, \"object\")\n inner_name <- .subset2(object, \"object_name\")\n\n # subtract set at layout level, if it is a plot option\n # we only apply to current active layout\n if (inherits(inner, \"ggalign_scheme\")) {\n layout <- update_layout_scheme(inner, layout, inner_name)\n return(layout)\n }\n\n # otherwise, we apply the object to all plots in the stack layout\n direction <- layout@direction\n layout@plot_list <- lapply(layout@plot_list, function(plot) {\n if (is_craftbox(plot)) {\n plot <- chain_plot_add(plot, inner, inner_name, force = FALSE)\n } else if (is.waive(.subset2(object, \"position\"))) {\n # default behaviour for object wrap with `with_quad()`\n # we add the object along the stack layout\n # if means for horizontal stack, we'll add it\n # to the left and right annotation, and the main plot\n positions <- switch_direction(\n direction,\n c(\"left\", \"right\"),\n c(\"top\", \"bottom\")\n )\n for (position in positions) {\n if (!is.null(slot(plot, position))) {\n slot(plot, position) <- chain_layout_subtract(\n inner, slot(plot, position), inner_name\n )\n }\n }\n if (is.null(main <- .subset2(object, \"main\")) || main) {\n plot <- quad_body_add(inner, plot, inner_name)\n }\n } else {\n # we respect the context setting\n plot <- quad_layout_subtract(object, plot, object_name)\n }\n plot\n })\n } else {\n layout@plot_list[[active_index]] <- quad_layout_subtract(\n object, plot, object_name\n )\n }\n layout\n}\n\n##################################################################\n#' @keywords internal\nchain_layout_and_add <- function(object, layout, object_name) {\n UseMethod(\"chain_layout_and_add\")\n}\n\n#' @export\nchain_layout_and_add.ggalign_with_quad <- function(object, layout, object_name) {\n if (!is_stack_layout(layout)) {\n cli_abort(sprintf(\n \"Cannot add {.var {object_name}} to %s\",\n object_name(layout)\n ))\n }\n object <- .subset2(object, \"object\")\n object_name <- .subset2(object, \"object_name\")\n NextMethod()\n}\n\n#' @export\nchain_layout_and_add.default <- function(object, layout, object_name) {\n layout@plot_list <- lapply(layout@plot_list, function(plot) {\n if (is_craftbox(plot)) {\n plot <- chain_plot_add(plot, object, object_name, force = FALSE)\n } else {\n plot <- quad_layout_and_add(object, plot, object_name)\n }\n plot\n })\n layout\n}\n\n#' @export\nchain_layout_and_add.theme <- function(object, layout, object_name) {\n ans <- NextMethod()\n # to align with `patchwork`, we also modify the layout theme\n # when using `&` to add the theme object.\n ans@theme <- ggfun(\"add_theme\")(ans@theme, object)\n ans\n}\n"], ["/ggalign/R/layout-quad-add.R", "#' @keywords internal\nquad_layout_add <- function(object, quad, object_name) {\n UseMethod(\"quad_layout_add\")\n}\n\n#############################################################\n#' @export\nquad_layout_add.layout_title <- function(object, quad, object_name) {\n quad@titles <- update_non_waive(quad@titles, object)\n quad\n}\n\n##############################################################\n# Preventing from adding following elements\n#' @export\nquad_layout_add.matrix <- function(object, quad, object_name) {\n cli_abort(sprintf(\"Can't change data of %s\", object_name(quad)))\n}\n\n#' @export\nquad_layout_add.data.frame <- quad_layout_add.matrix\n\n#############################################################\n# Add elements for the main body or the annotation\n#' @importFrom methods slot slot<-\n#' @export\nquad_layout_add.default <- function(object, quad, object_name) {\n if (is.null(position <- quad@active)) {\n quad <- quad_body_add(object, quad, object_name)\n } else if (is.null(stack <- slot(quad, position))) {\n cli_abort(c(\n sprintf(\"Cannot add {.var {object_name}} to %s\", object_name(quad)),\n i = \"the {.field {position}} annotation stack is not initialized\",\n i = \"Try to use {.code quad_anno(initialize = TRUE)} or you can add a {.code stack_layout()} manually\"\n ))\n } else {\n slot(quad, position) <- chain_layout_add(object, stack, object_name)\n }\n quad\n}\n\n#' @export\nquad_layout_add.list <- function(object, quad, object_name) {\n for (o in object) quad <- quad_layout_add(o, quad, object_name)\n quad\n}\n\n#' @export\nquad_layout_add.NULL <- function(object, quad, object_name) {\n quad\n}\n\n#' @export\nquad_layout_add.ggalign_with_quad <- function(object, quad, object_name) {\n old <- quad@active\n contexts <- quad_operated_context(object, old, \"+\") %||%\n list(NULL) # we wrap `NULL` to a list for `for loop`.\n object <- .subset2(object, \"object\")\n object_name <- .subset2(object, \"object_name\")\n for (active in contexts) {\n quad@active <- active\n quad <- quad_layout_add(object, quad, object_name)\n }\n quad@active <- old\n quad\n}\n\n##################################################################\n#' @export\nquad_layout_add.quad_active <- function(object, quad, object_name) {\n if (!is.null(width <- .subset2(object, \"width\"))) {\n quad@width <- width\n }\n if (!is.null(height <- .subset2(object, \"height\"))) {\n quad@height <- height\n }\n quad@active <- NULL\n quad\n}\n\n#' @importFrom methods slot\n#' @export\nquad_layout_add.quad_anno <- function(object, quad, object_name) {\n position <- .subset2(object, \"position\")\n initialize <- .subset2(object, \"initialize\")\n stack <- slot(quad, position)\n if (is.null(stack) && !isFALSE(initialize)) {\n # try to initialize the annotation stack with the layout data\n direction <- to_direction(position)\n layout_design <- slot(quad, direction)\n # for the annotation stack, we try to take the data from the\n # quad layout\n quad_data <- quad@data\n data <- waiver() # use waiver() to indicate data is not initialized\n quad_matrix <- FALSE # the default value for `quad_matrix` in the stack\n if (is_continuous_design(layout_design)) { # the stack need a data frame\n if (!is.data.frame(quad_data)) {\n if (is.null(initialize)) {\n cli_warn(paste(\n \"`data` in {.fn {quad@name}} is\",\n \"{.obj_type_friendly {quad_data}}, but the\",\n \"{.field {position}} annotation stack need a\",\n \"{.cls data.frame}, won't initialize\",\n \"the {.field {position}} annotation stack\"\n ))\n } else {\n data <- NULL\n }\n } else {\n data <- quad_data\n }\n } else if (is.matrix(quad_data)) { # the stack need a matrix\n if (is_horizontal(direction)) {\n data <- quad_data\n } else {\n data <- ggalign_data_restore(t(quad_data), quad_data)\n }\n quad_matrix <- TRUE\n } else {\n if (is.null(initialize)) {\n cli_warn(paste(\n \"`data` in {.fn {quad@name}} is\",\n \"{.obj_type_friendly {quad_data}}, but the\",\n \"{.field {position}} annotation stack need a\",\n \"{.cls data.frame}, won't initialize\",\n \"the {.field {position}} annotation stack\"\n ))\n } else {\n data <- NULL\n }\n }\n if (!is.waive(data)) { # initialize the annotation stack\n stack <- new_stack_layout(\n data = data,\n direction = direction,\n # the layout parameters should be the same with `quad_layout()`\n design = layout_design,\n # we'll inherit the action data function when\n schemes = default_schemes(if (is.null(data)) NULL else waiver())\n )\n stack@heatmap$position <- position\n stack@heatmap$quad_matrix <- quad_matrix\n }\n } else if (!is.null(stack) && isTRUE(initialize)) {\n cli_abort(c(\n \"Cannot initialize the {position} annotation stack\",\n i = \"{position} annotation stack has already been initialized\"\n ))\n }\n\n if (!is.null(stack)) {\n # update parameters\n if (!is.null(size <- .subset2(object, \"size\"))) {\n stack@sizes <- size\n }\n if (!is.waive(free_guides <- .subset2(object, \"free_guides\"))) {\n stack@heatmap[\"free_guides\"] <- list(free_guides)\n }\n stack <- switch_chain_plot(\n stack, .subset2(object, \"what\"), quote(quad_anno())\n )\n slot(quad, position) <- stack\n }\n quad@active <- position\n quad\n}\n\n#' @export\nquad_layout_add.QuadLayout <- function(object, quad, object_name) {\n cli_abort(c(\n sprintf(\"Cannot add {.var {object_name}} to %s\", object_name(quad)),\n i = \"Did you mean to place multiple {.fn quad_layout} elements inside a {.fn stack_layout}?\"\n ))\n}\n\n#' @export\nquad_layout_add.StackLayout <- function(object, quad, object_name) {\n # we check if there is an active annotation\n if (is.null(position <- quad@active)) {\n cli_abort(c(\n sprintf(\"Cannot add {.var {object_name}} to %s\", object_name(quad)),\n i = \"no active annotation stack\",\n i = \"try to activate an annotation stack with {.fn anno_*}\"\n ))\n }\n # check the annotation stack is not initialized\n if (!is.null(slot(quad, position))) {\n cli_abort(c(\n sprintf(\"Cannot add {.var {object_name}} to %s\", object_name(quad)),\n i = \"{position} annotation stack already exists\"\n ))\n }\n # cannot contain nested layout\n if (!all(vapply(object@plot_list, is_craftbox, logical(1L),\n USE.NAMES = FALSE))) { # styler: off\n cli_abort(c(\n sprintf(\"Cannot add {.var {object_name}} to %s\", object_name(quad)),\n i = \"annotation stack cannot contain nested layout\"\n ))\n }\n # check quad layout is compatible with stack layout\n if (!identical(direction <- to_direction(position), object@direction)) {\n cli_abort(c(\n sprintf(\"Cannot add {.var {object_name}} to %s\", object_name(quad)),\n i = \"only {.field {direction}} stack is allowed in {position} annotation\"\n ))\n }\n if (length(object@sizes) > 1L) {\n cli_abort(c(\n sprintf(\"Cannot add {.var {object_name}} to %s\", object_name(quad)),\n i = \"{.arg sizes} must be of length one to use the stack as an annotation\"\n ))\n }\n quad_design <- slot(quad, direction)\n if (is_cross_layout(object) &&\n any(position == c(\"bottom\", \"right\")) &&\n !is_empty(object@cross_points)) {\n # if there are cross points in bottom or right annotation,\n # use the first design\n stack_design <- .subset2(object@odesign, 1L)\n } else {\n stack_design <- object@design\n }\n # check if we can align in this direction\n # `stack_layout()` is free from aligning obervations in this axis\n if (is_continuous_design(stack_design)) {\n if (!is_continuous_design(quad_design)) {\n cli_abort(c(\n sprintf(\n \"Cannot add {.var {object_name}} to %s\",\n object_name(quad)\n ),\n i = sprintf(\n \"%s cannot align continuous variable in {.field {direction}} direction\",\n object_name(quad)\n )\n ))\n }\n layout_design <- stack_design\n } else if (is_discrete_design(quad_design)) {\n layout_design <- melt_discrete_design(\n quad_design, stack_design,\n old_name = object_name(quad),\n new_name = object_name\n )\n } else {\n cli_abort(c(\n sprintf(\"Cannot add {.var {object_name}} to %s\", object_name(quad)),\n i = sprintf(\n \"%s cannot align discrete variable in {.field {direction}} direction\",\n object_name(quad)\n )\n ))\n }\n object@heatmap$position <- position\n slot(quad, position) <- object\n update_design(quad,\n direction = direction,\n design = layout_design,\n object_name = object_name\n )\n}\n\n#' @importFrom methods slot slot<-\n#' @export\nquad_layout_add.CraftBox <- function(object, quad, object_name) {\n if (is.null(position <- quad@active)) {\n cli_abort(c(\n sprintf(\"Cannot add {.var {object_name}} to %s\", object_name(quad)),\n i = \"no active annotation stack\",\n i = \"try to activate an annotation stack with {.fn anno_*}\"\n ))\n }\n if (is.null(stack <- slot(quad, position))) {\n cli_abort(c(\n sprintf(\"Cannot add {.var {object_name}} to %s\", object_name(quad)),\n i = \"the {.field {position}} annotation stack is not initialized\",\n i = \"Try to use {.code quad_anno(initialize = TRUE)} or you can add a {.code stack_layout()} manually\"\n ))\n }\n\n # add annotation -----------------------------\n stack <- chain_layout_add(object, stack, object_name)\n slot(quad, position) <- stack\n\n # if there are cross points in bottom or right annotation, we use\n # the first design\n if (is_cross_layout(stack) &&\n any(position == c(\"bottom\", \"right\")) &&\n !is_empty(stack@cross_points)) {\n new_design <- .subset2(stack@odesign, 1L)\n } else {\n new_design <- stack@design\n }\n\n update_design(\n quad,\n direction = to_direction(position),\n design = new_design,\n object_name = object_name\n )\n}\n\n#######################################################\n# used to add elements for main body\n#' @keywords internal\nquad_body_add <- function(object, quad, object_name) {\n UseMethod(\"quad_body_add\")\n}\n\n#' @importFrom ggplot2 ggplot_add\n#' @export\nquad_body_add.default <- function(object, quad, object_name) {\n quad@plot <- ggplot_add(object, ggfun(\"plot_clone\")(quad@plot), object_name)\n quad\n}\n\n#' @export\nquad_body_add.Coord <- function(object, quad, object_name) {\n if (!inherits(object, \"CoordCartesian\")) {\n cli_warn(c(\n \"only {.field cartesian coordinate} is supported\",\n i = \"will discard {.var {object_name}} directly\"\n ))\n return(quad)\n }\n NextMethod() # call default method\n}\n\n#' @export\nquad_body_add.layout_theme <- function(object, quad, object_name) {\n quad@theme <- update_layout_theme(quad@theme, object)\n quad\n}\n\n#' @export\nquad_body_add.ggalign_scheme <- function(object, quad, object_name) {\n name <- ggalign_scheme_name(object)\n quad@body_schemes[name] <- list(update_scheme(\n object, .subset2(quad@body_schemes, name), object_name\n ))\n quad\n}\n"], ["/ggalign/R/active.R", "#' Plot Adding Context Settings\n#'\n#' @description\n#' `r lifecycle::badge('experimental')`\n#'\n#' These settings control the behavior of the plot when added to a layout, as\n#' well as the arrangement of individual plot areas within the layout.\n#'\n#' @details\n#' By default, the active context is set only for functions that add plot areas.\n#' This allows other `ggplot2` elements-such as `geoms`, `stats`, `scales`, or\n#' `themes`- to be seamlessly added to the current plot area.\n#'\n#' The default ordering of the plot areas is from top to bottom or from left to\n#' right, depending on the layout orientation. However, users can customize this\n#' order using the `order` argument.\n#'\n#' @param order An integer specifying the order of the plot area within the\n#' layout.\n#' @param use A logical (`TRUE`/`FALSE`) indicating whether to set the\n#' active context to the current plot when added to a layout. If `TRUE`,\n#' any subsequent `ggplot` elements will be applied to this plot.\n#' @param name A string specifying the plot's name, useful for switching active\n#' contexts through the `what` argument in functions like\n#' [`quad_anno()`]/[`stack_switch()`].\n#' @export\nactive <- function(order = waiver(), use = waiver(), name = waiver()) {\n if (!is.waive(order)) order <- check_order(order)\n if (!is.waive(use)) assert_bool(use)\n if (!is.waive(name)) {\n assert_string(name,\n empty_ok = FALSE, allow_na = TRUE,\n allow_null = FALSE\n )\n }\n new_active(order = order, use = use, name = name)\n}\n\n# for internal function, we only adjust to the `use` argument\n# here, we put it in the first\nnew_active <- function(use, order = NA_integer_, name = NA_character_) {\n structure(\n list(order = order, use = use, name = name),\n class = \"ggalign_active\"\n )\n}\n\n#' @importFrom utils modifyList\nupdate_active <- function(active, default) {\n if (is.null(active)) return(default) # styler: off\n modifyList(default,\n active[!vapply(active, is.waive, logical(1L), USE.NAMES = FALSE)],\n keep.null = TRUE\n )\n}\n"], ["/ggalign/R/rasterise.R", "rasterise.QuadLayout <- function(input, ...) {\n input@plot <- ggrastr::rasterise(input = input@plot, ...)\n for (position in .TLBR) {\n stack <- slot(input, position)\n if (is.null(stack)) next\n slot(input, position) <- ggrastr::rasterise(input = stack, ...)\n }\n input\n}\n\nrasterise.ChainLayout <- function(input, ...) {\n input@plot_list <- lapply(input@plot_list, ggrastr::rasterise, ...)\n input\n}\n\nrasterise.CraftBox <- function(input, ...) {\n if (!is.null(plot <- input@plot)) {\n input@plot <- ggrastr::rasterise(input = plot, ...)\n }\n input\n}\n\n##########################################################\n#' @export\nraster_magick0.QuadLayout <- function(x, ...) {\n x@plot <- raster_magick0(x = x@plot, ...)\n for (position in .TLBR) {\n stack <- slot(x, position)\n if (is.null(stack)) next\n slot(x, position) <- raster_magick0(x = stack, ...)\n }\n x\n}\n\n#' @export\nraster_magick0.ChainLayout <- function(x, ...) {\n x@plot_list <- lapply(x@plot_list, raster_magick0, ...)\n x\n}\n\n\n#' @export\nraster_magick0.CraftBox <- function(x, ...) {\n if (!is.null(plot <- input@plot)) {\n input@plot <- raster_magick0(x = plot, ...)\n }\n input\n}\n"], ["/ggalign/R/layout-chain-stack-switch.R", "#########################################################\n#' Determine the active context of stack layout\n#'\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' `stack_active` is an alias for `stack_switch()`, which sets `what = NULL` by\n#' default.\n#'\n#' @inheritParams rlang::args_dots_empty\n#' @inheritParams quad_switch\n#' @inheritParams stack_discrete\n#' @param what What should get activated for the stack layout?\n#' `r rd_chain_what()`, this is useful when the active context is a\n#' [`quad_layout()`] object, where any `align_*()` will be added to the\n#' [`quad_layout()`]. By removing the active context, we can add `align_*()`\n#' into the [`stack_layout()`].\n#' @return A `stack_switch` object which can be added to [stack_layout()].\n#' @examples\n#' stack_discrete(\"h\", matrix(1:9, nrow = 3L)) +\n#' ggheatmap() +\n#' # ggheamtap will set the active context, directing following addition\n#' # into the heatmap plot area. To remove the heatmap active context,\n#' # we can use `stack_active()` which will direct subsequent addition into\n#' # the stack\n#' stack_active() +\n#' # here we add a dendrogram to the stack.\n#' align_dendro()\n#' @export\nstack_switch <- function(sizes = NULL, what = waiver(), ...) {\n rlang::check_dots_empty()\n if (!is.waive(what)) what <- check_stack_context(what)\n if (!is.null(sizes)) sizes <- check_stack_sizes(sizes)\n structure(list(what = what, sizes = sizes), class = \"stack_switch\")\n}\n\n#' @export\n#' @rdname stack_switch\nstack_active <- function(sizes = NULL, ...) {\n rlang::check_dots_empty()\n stack_switch(sizes, what = NULL)\n}\n"], ["/ggalign/R/layout-quad-operator.R", "# `subtract` operates at layout-level\n#' @keywords internal\nquad_layout_subtract <- function(object, quad, object_name) {\n UseMethod(\"quad_layout_subtract\")\n}\n\n#' @export\nquad_layout_subtract.default <- function(object, quad, object_name) {\n if (is.null(context <- quad@active)) context <- c(.TLBR, list(NULL))\n for (active in context) {\n if (is.null(active)) {\n quad <- quad_body_add(object, quad, object_name)\n } else if (!is.null(slot(quad, active))) {\n slot(quad, active) <- chain_layout_subtract(\n object, slot(quad, active), object_name\n )\n }\n }\n quad\n}\n\n# for object can set at layout level\n#' @export\nquad_layout_subtract.ggalign_scheme <- function(object, quad, object_name) {\n if (is.null(context <- quad@active)) {\n quad <- update_layout_scheme(object, quad, object_name)\n } else {\n slot(quad, context) <- update_layout_scheme(\n object, slot(quad, context), object_name\n )\n }\n quad\n}\n\n#' @export\nquad_layout_subtract.ggalign_with_quad <- function(object, quad, object_name) {\n old <- quad@active\n context <- quad_operated_context(object, old, \"-\")\n object <- .subset2(object, \"object\")\n object_name <- .subset2(object, \"object_name\")\n # `subtract` operates at layout-level\n if (is.null(context)) {\n quad@active <- context\n quad <- quad_layout_subtract(object, quad, object_name)\n } else {\n for (active in context) {\n if (is.null(active)) {\n quad <- quad_body_add(object, quad, object_name)\n } else if (!is.null(slot(quad, active))) {\n slot(quad, active) <- chain_layout_subtract(\n object, slot(quad, active), object_name\n )\n }\n }\n }\n quad@active <- old\n quad\n}\n\n###############################################################\n#' @keywords internal\nquad_layout_and_add <- function(object, quad, object_name) {\n UseMethod(\"quad_layout_and_add\")\n}\n\n#' @export\nquad_layout_and_add.default <- function(object, quad, object_name) {\n quad <- quad_body_add(object, quad, object_name)\n for (position in .TLBR) {\n stack <- slot(quad, position)\n if (is.null(stack)) next\n slot(quad, position) <- chain_layout_and_add(\n object, stack, object_name\n )\n }\n quad\n}\n\n#' @export\nquad_layout_and_add.ggalign_with_quad <- function(object, quad, object_name) {\n object <- .subset2(object, \"object\")\n object_name <- .subset2(object, \"object_name\")\n NextMethod()\n}\n\n#' @export\nquad_layout_and_add.theme <- function(object, quad, object_name) {\n ans <- NextMethod()\n # to align with `patchwork`, we also modify the layout theme\n # when using `&` to add the theme object.\n ans@theme <- ggfun(\"add_theme\")(ans@theme, object)\n ans\n}\n"], ["/ggalign/R/alignpatch-free-lab.R", "#' @param labs Which axis labs to be free? A string containing one or more of\n#' `r oxford_and(.tlbr)`.\n#' @return\n#' - `free_lab`: A modified version of `plot` with a `free_lab` class.\n#' @export\n#' @rdname free\nfree_lab <- function(plot, labs = \"tlbr\") {\n UseMethod(\"free_lab\")\n}\n\n#' @export\nfree_lab.ggplot <- function(plot, labs = \"tlbr\") {\n assert_position(labs)\n attr(plot, \"free_labs\") <- labs\n add_class(plot, \"free_lab\")\n}\n\n#' @export\nfree_lab.alignpatches <- free_lab.ggplot\n\n#' @export\nfree_lab.free_align <- function(plot, labs = \"tlbr\") {\n assert_position(labs)\n labs <- setdiff_position(labs, attr(plot, \"free_axes\"))\n if (!nzchar(labs)) return(plot) # styler: off\n NextMethod()\n}\n\n#' @export\nfree_lab.free_borders <- function(plot, labs = \"tlbr\") {\n assert_position(labs)\n labs <- setdiff_position(labs, attr(plot, \"free_borders\"))\n if (!nzchar(labs)) return(plot) # styler: off\n NextMethod()\n}\n\n#' @export\nfree_lab.free_lab <- function(plot, labs = \"tlbr\") {\n assert_position(labs)\n attr(plot, \"free_labs\") <- union_position(attr(plot, \"free_labs\"), labs)\n plot\n}\n\n#' @export\nfree_lab.default <- function(plot, labs = \"tlbr\") {\n cli_abort(\"Cannot use with {.obj_type_friendly {plot}}\")\n}\n\n####################################################\n#' @importFrom ggplot2 ggproto ggproto_parent\n#' @export\nalignpatch.free_lab <- function(x) {\n Parent <- NextMethod()\n ggproto(\n \"PatchFreeLab\", Parent,\n free_labs = setup_pos(attr(x, \"free_labs\")),\n collect_guides = function(self, guides, gt = self$gt) {\n ans <- ggproto_parent(Parent, self)$collect_guides(\n guides = guides, gt = gt\n )\n self$gt <- ggproto_parent(Parent, self)$free_lab(\n labs = self$free_labs, gt = self$gt\n )\n ans\n },\n free_lab = function(self, labs, gt = self$gt) {\n if (length(labs <- vec_set_difference(labs, self$free_labs))) {\n gt <- ggproto_parent(Parent, self)$free_lab(\n labs = labs, gt = gt\n )\n }\n gt\n }\n )\n}\n"], ["/ggalign/R/alignpatch-free-border.R", "#' @param borders Which border shouldn't be aligned? A string containing one or\n#' more of `r oxford_and(.tlbr)`.\n#' @return\n#' - `free_border`: A modified version of `plot` with a `free_border` class.\n#' @export\n#' @rdname free\nfree_border <- function(plot, borders = \"tlbr\") {\n UseMethod(\"free_border\")\n}\n\n#' @export\nfree_border.ggplot <- function(plot, borders = \"tlbr\") {\n assert_position(borders)\n attr(plot, \"free_borders\") <- borders\n add_class(plot, \"free_border\")\n}\n\n#' @export\nfree_border.alignpatches <- free_border.ggplot\n\n#' @export\nfree_border.free_align <- function(plot, borders = \"tlbr\") {\n assert_position(borders)\n borders <- setdiff_position(borders, attr(plot, \"free_axes\"))\n if (!nzchar(borders)) {\n return(plot)\n }\n NextMethod()\n}\n\n#' @export\nfree_border.free_lab <- function(plot, borders = \"tlbr\") {\n assert_position(borders)\n free_labs <- setdiff_position(attr(plot, \"free_labs\"), borders)\n if (nzchar(free_labs)) {\n attr(plot, \"free_labs\") <- free_labs\n } else {\n attr(plot, \"free_labs\") <- NULL\n plot <- remove_class(plot, \"free_lab\")\n }\n NextMethod()\n}\n\n#' @export\nfree_border.free_border <- function(plot, borders = \"tlbr\") {\n assert_position(borders)\n attr(plot, \"free_borders\") <- union_position(\n attr(plot, \"free_borders\"), borders\n )\n plot\n}\n\n#' @export\nfree_border.default <- function(plot, borders = \"tlbr\") {\n cli_abort(\"Cannot use with {.obj_type_friendly {plot}}\")\n}\n\n################################################################\n#' @importFrom ggplot2 ggproto ggproto_parent\n#' @export\nalignpatch.free_border <- function(x) {\n Parent <- NextMethod()\n ggproto(\n \"PatchFreeBorder\", Parent,\n free_borders = setup_pos(attr(x, \"free_borders\")),\n collect_guides = function(self, guides, gt = self$gt) {\n ans <- ggproto_parent(Parent, self)$collect_guides(\n guides = guides, gt = gt\n )\n self$gt <- ggproto_parent(Parent, self)$free_border(\n borders = self$free_borders, gt = self$gt\n )\n ans\n },\n align_border = function(self, t = NULL, l = NULL, b = NULL, r = NULL,\n gt = self$gt) {\n gt <- ggproto_parent(Parent, self)$align_border(\n t = t, l = l, b = b, r = r, gt = gt\n )\n ggproto_parent(Parent, self)$align_free_border(\n borders = self$free_borders,\n t = t, l = l, b = b, r = r, gt = gt\n )\n },\n free_border = function(self, borders, gt = self$gt) {\n borders <- vec_set_difference(borders, self$free_borders)\n if (length(borders)) {\n gt <- ggproto_parent(Parent, self)$free_border(\n borders = borders, gt = gt\n )\n }\n gt\n },\n align_free_border = function(self, borders,\n t = NULL, l = NULL, b = NULL, r = NULL,\n gt = self$gt) {\n borders <- vec_set_difference(borders, self$free_borders)\n if (length(borders)) {\n gt <- ggproto_parent(Parent, self)$align_free_border(\n borders = borders,\n t = t, l = l, b = b, r = r, gt = gt\n )\n }\n gt\n }\n )\n}\n"], ["/ggalign/R/ggalign-package.R", "#' @keywords internal\n\"_PACKAGE\"\n\n## usethis namespace: start\n#' @import vctrs\n#' @importFrom lifecycle deprecated\n#' @importFrom rlang .data .env\n#' @importFrom cli cli_abort cli_warn cli_inform\n## usethis namespace: end\nNULL\n\n# enable usage of @name in package code\n#' @rawNamespace if (getRversion() < \"4.3.0\") importFrom(\"S7\", \"@\")\nNULL\n"], ["/ggalign/R/fortify-matrix-.R", "#' Build a Matrix\n#'\n#' @description\n#' `r lifecycle::badge('stable')`\n#'\n#' This function converts various objects into a matrix format. By default, it\n#' calls [`as.matrix()`] to build a matrix.\n#'\n#' @param data An object to be converted into a matrix.\n#' @param ... Additional arguments passed to methods.\n#' @param data_arg The argument name for `data`. Developers can use it to\n#' improve messages. Not used by the user.\n#' @param call The execution environment where `data` and other arguments for\n#' the method are collected. Developers can use it to improve messages. Not\n#' used by the user.\n#' @return A matrix.\n#' @eval\n#' rd_collect_family(\"fortify_matrix\", \"`fortify_matrix` method collections\")\n#' @export\nfortify_matrix <- function(data, ..., data_arg = NULL,\n call = NULL) {\n UseMethod(\"fortify_matrix\")\n}\n\n#' @inheritParams rlang::args_dots_empty\n#' @inherit fortify_matrix title return\n#' @description\n#' By default, it calls [`as.matrix()`] to build a matrix.\n#' @inheritParams fortify_matrix\n#' @family fortify_matrix\n#' @importFrom rlang try_fetch\n#' @export\nfortify_matrix.default <- function(data, ..., data_arg = NULL,\n call = NULL) {\n call <- call %||% current_call()\n data_arg <- data_arg %||% \"data\"\n rlang::check_dots_empty(call = call)\n try_fetch(\n as.matrix(data),\n error = function(cnd) {\n cli_abort(\n paste0(\n \"{.arg {data_arg}} must be a {.cls matrix}, \",\n \"or an object coercible by {.fn fortify_matrix}, or a valid \",\n \"{.cls matrix}-like object coercible by {.fn as.matrix}\"\n ),\n call = call\n )\n }\n )\n}\n\n#' @export\nfortify_matrix.waiver <- function(data, ..., data_arg = NULL,\n call = NULL) {\n call <- call %||% current_call()\n rlang::check_dots_empty(call = call)\n data\n}\n\n#' @export\nfortify_matrix.NULL <- fortify_matrix.waiver\n\n#' @export\nfortify_matrix.function <- fortify_matrix.waiver\n\n#' @export\nfortify_matrix.formula <- function(data, ..., data_arg = NULL,\n call = NULL) {\n call <- call %||% current_call()\n rlang::check_dots_empty(call = call)\n rlang::as_function(data)\n}\n"], ["/ggalign/R/utils-rd.R", "rd_layout <- function() {\n sprintf(\"%s or [`stack_layout()`] object\", rd_quad())\n}\n\nrd_quad <- function() \"[`quad_layout()`]/[`ggheatmap()`]\"\n\nrd_chain_what <- function() {\n paste(\n \"A single number or string of the plot elements in the layout.\",\n \"If `NULL`, will remove any active context\"\n )\n}\n\nrd_quad_position <- function(action) {\n sprintf(\n \"A string of %s indicates which annotation stack should be %s\",\n oxford_or(.TLBR),\n action\n )\n}\n\nrd_layout_data <- function() {\n paste(\n \"Default dataset to use for the layout. If not specified, it must be\",\n \"supplied in each plot added to the layout\"\n )\n}\n\nrd_gg_aesthetics <- function(...) {\n ans <- ggfun(\"rd_aesthetics\")(...)\n ans <- sub(\"link[=\", \"link[ggplot2:\", ans, fixed = TRUE)\n sub(\"(vignette\\\\([^)]+)\\\\)\", \"\\\\1, package = \\\"ggplot2\\\")\", ans)\n}\n"], ["/ggalign/R/alignpatch-free-guide.R", "#' @param guides A string containing one or more of\n#' `r oxford_and(c(.tlbr, \"i\"))` indicates which side of guide legends should be\n#' collected for the plot. If `NULL`, no guide legends will be collected.\n#' @return\n#' - `free_guide`: A modified version of `plot` with a `free_guide` class.\n#' @export\n#' @rdname free\nfree_guide <- function(plot, guides = \"tlbr\") {\n UseMethod(\"free_guide\")\n}\n\n#' @export\nfree_guide.ggplot <- function(plot, guides = \"tlbr\") {\n if (!is.null(guides)) assert_guides(guides)\n attr(plot, \"free_guides\") <- guides\n add_class(plot, \"free_guide\")\n}\n\n#' @export\nfree_guide.alignpatches <- free_guide.ggplot\n\n#' @export\nfree_guide.free_guide <- function(plot, guides = \"tlbr\") {\n if (is.null(guides)) {\n attr(plot, \"free_guides\") <- NULL\n } else {\n assert_guides(guides)\n if (is.null(old <- attr(plot, \"free_guides\", exact = TRUE))) {\n attr(plot, \"free_guides\") <- guides\n } else {\n attr(plot, \"free_guides\") <- union_position(old, guides)\n }\n }\n plot\n}\n\n################################################################\n#' @importFrom ggplot2 ggproto ggproto_parent\n#' @export\nalignpatch.free_guide <- function(x) {\n Parent <- NextMethod()\n if (!is.null(free_guides <- attr(x, \"free_guides\", exact = TRUE))) {\n free_guides <- setup_guides(free_guides)\n }\n ggproto(\"PatchFreeGuide\", Parent,\n set_guides = function(self, guides) free_guides\n )\n}\n"], ["/ggalign/R/alignpatch-free-space.R", "#' @param spaces Which border spaces should be removed? A string containing one\n#' or more of `r oxford_and(.tlbr)`.\n#' @return\n#' - `free_space`: A modified version of `plot` with a `free_space` class.\n#' @export\n#' @rdname free\nfree_space <- function(plot, spaces = \"tlbr\") {\n UseMethod(\"free_space\")\n}\n\n#' @export\nfree_space.default <- function(plot, spaces = \"tlbr\") {\n cli_abort(\"Cannot use with {.obj_type_friendly {plot}}\")\n}\n\n#' @export\nfree_space.ggplot <- function(plot, spaces = \"tlbr\") {\n assert_position(spaces)\n attr(plot, \"free_spaces\") <- spaces\n add_class(plot, \"free_space\")\n}\n\n#' @export\nfree_space.alignpatches <- free_space.ggplot\n\n#' @export\nfree_space.free_align <- function(plot, spaces = \"tlbr\") {\n assert_position(spaces)\n spaces <- setdiff_position(spaces, attr(plot, \"free_axes\"))\n if (!nzchar(spaces)) {\n return(plot)\n }\n NextMethod()\n}\n\n#' @export\nfree_space.free_space <- function(plot, spaces = \"tlbr\") {\n assert_position(spaces)\n attr(plot, \"free_spaces\") <- union_position(\n attr(plot, \"free_spaces\"), spaces\n )\n plot\n}\n\n##########################################################\n#' @importFrom ggplot2 ggproto ggproto_parent\n#' @importFrom grid unit\n#' @export\nalignpatch.free_space <- function(x) {\n Parent <- NextMethod()\n ggproto(\n \"PatchFreeSpace\", Parent,\n free_spaces = split_position(attr(x, \"free_spaces\")),\n get_sizes = function(self, free = NULL, gt = self$gt) {\n ggproto_parent(Parent, self)$get_sizes(\n union(free, self$free_spaces),\n gt = gt\n )\n }\n )\n}\n"], ["/ggalign/R/craft-cross-none.R", "#' Reset layout ordering and panel group\n#'\n#' @param data The dataset to use for the layout. By default,\n#' [`fortify_matrix()`] will convert the data to a matrix. This argument\n#' allows you to change the layout data. If not specified, the original data\n#' will be used.\n#' @param ... <[dyn-dots][rlang::dyn-dots]> Additional arguments passed to\n#' [`fortify_matrix()`].\n#' @param inherit_index A boolean value indicating whether to inherit the\n#' ordering index. If `TRUE`, will match the layout ordering index with the\n#' data names.\n#' @param inherit_panel A boolean value indicating whether to inherit the\n#' panel group. If `TRUE`, will match the layout panel with the data names.\n#' @param inherit_nobs A boolean value indicating whether to inherit the\n#' number of observations (nobs). If `TRUE`, the `data` input must be\n#' compatible with the layout data.\n#' @export\ncross_none <- function(data = waiver(), ...,\n inherit_index = NULL,\n inherit_panel = NULL,\n inherit_nobs = NULL) {\n cross(CrossNone,\n data = data, data_params = list2(...), plot = NULL,\n active = new_active(use = FALSE),\n schemes = default_schemes(),\n inherit_index = inherit_index,\n inherit_panel = inherit_panel,\n inherit_nobs = inherit_nobs\n )\n}\n\n#' @importFrom ggplot2 ggproto ggproto_parent\n#' @include craft-cross-.R\nCrossNone <- ggproto(\"CrossNone\", CraftCross)\n"], ["/ggalign/R/object-name.R", "format_object_name <- function(name, format = NULL) {\n if (is.null(format)) {\n name\n } else {\n sprintf(\"{.%s %s}\", format, name)\n }\n}\n\nobject_name <- function(object, format) UseMethod(\"object_name\")\n\n#' @export\nobject_name.StackLayout <- function(object, format = \"fn\") {\n ans <- format_object_name(object@name, format)\n if (!is.null(position <- .subset2(object@heatmap, \"position\"))) {\n ans <- sprintf(\"the %s annotation %s\", position, ans)\n } else {\n ans <- sprintf(\"the %s %s\", object@direction, ans)\n }\n ans\n}\n\n#' @export\nobject_name.CircleLayout <- function(object, format = \"fn\") {\n format_object_name(object@name, format)\n}\n\n#' @export\nobject_name.QuadLayout <- function(object, format = \"fn\") {\n format_object_name(object@name, format)\n}\n\n#' @export\nobject_name.CraftBox <- function(object, format = \"fn\") {\n object_name(object@craftsman, format)\n}\n\n#' @export\nobject_name.Craftsman <- function(object, format = \"fn\") {\n format_object_name(snake_class(object), format)\n}\n\n#' @export\nobject_name.AlignGg <- function(object, format = \"fn\") {\n format_object_name(\"ggalign\", format)\n}\n\n#' @export\nobject_name.CrossGg <- function(object, format = \"fn\") {\n format_object_name(\"ggcross\", format)\n}\n\n#' @export\nobject_name.FreeGg <- function(object, format = \"fn\") {\n format_object_name(\"ggfree\", format)\n}\n\n#' @export\nobject_name.MarkGg <- function(object, format = \"fn\") {\n format_object_name(\"ggmark\", format)\n}\n"], ["/ggalign/R/zzz.R", "#' @importFrom S7 methods_register\n.onLoad <- function(libname, pkgname) {\n # register ggplot2 theme elements\n theme_elements()\n\n # register method for\n s3_register(\"ggrastr::rasterise\", \"CraftBox\")\n s3_register(\"ggrastr::rasterise\", \"QuadLayout\")\n s3_register(\"ggrastr::rasterise\", \"ChainLayout\")\n\n methods_register()\n invisible()\n}\n"]], "task_instance_info": {"created_time": "2025-08-21 01:13:41", "created_task_model": "DeepSeek-R1", "function_skeleton": "function(.l) {}", "code_description": "This code segment functions to: Restructure a nested list collection by reorganizing elements such that inner list positions or names become the outer grouping mechanism, ensuring consistent element alignment across hierarchical levels."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```r\n[TASK_BEGIN]\nlist_transpose <- function(.l) {\n if (length(.l) == 0) return(list())\n inner_names <- names(.l[[1]])\n max_length <- max(lengths(.l))\n out <- lapply(seq_len(max_length), function(i) {\n lapply(.l, function(x) if (i <= length(x)) x[[i]] else NULL)\n })\n if (!is.null(inner_names)) names(out) <- inner_names\n out\n}\n[TASK_END]\n```", "inference_time": "2025-08-21 01-15-51"}, "editdistance_info": {"edit_distance": 20.5674, "calculate_time": "2025-08-21 01:15:51", "true_code_clean": "function(.l) {\n if (!length(.l)) return(.l) \n inner_names <- names(.subset2(.l, 1L))\n if (is.null(inner_names)) {\n fields <- seq_along(.subset2(.l, 1L))\n } else {\n fields <- inner_names\n names(fields) <- fields\n .l <- lapply(.l, function(x) {\n if (is.null(names(x))) names(x) <- inner_names \n x\n })\n }\n .l <- lapply(.l, as.list)\n lapply(fields, function(i) lapply(.l, .subset2, i))\n}", "predict_code_clean": "list_transpose <- function(.l) {\n if (length(.l) == 0) return(list())\n inner_names <- names(.l[[1]])\n max_length <- max(lengths(.l))\n out <- lapply(seq_len(max_length), function(i) {\n lapply(.l, function(x) if (i <= length(x)) x[[i]] else NULL)\n })\n if (!is.null(inner_names)) names(out) <- inner_names\n out\n}"}}