R/limits.R

Defines functions vec_expand_limits vec_expand_limits.numeric

Documented in vec_expand_limits vec_expand_limits.numeric

#' Expand a range
#'
#' Expand a range with multiplicative or additive constant. This function has
#' two tasks. First it needs to integrate the limits given to the coordinate
#' system with the limits from the scale system.
#'
#' @param limits A vector indicating limits from the scale system.
#' @param expand The result of calling \code{\link[ggplot2]{expansion}}.
#' @param coord_limits A vector indicating limits from the coord system.
#'
#' @return A vector with expanded limits
#' @export
#'
#' @examples
#' vec_expand_limits(c(0, 1), expansion(1), NULL)
vec_expand_limits <- function(limits, expand = expansion(0, 0),
                              coord_limits = NULL) {
  UseMethod("vec_expand_limits")
}

#' @export
#' @rdname vec_expand_limits
#' @method vec_expand_limits numeric
vec_expand_limits.numeric <- function(limits, expand = expansion(0, 0),
                                      coord_limits = NULL) {
  if (all(!is.finite(limits))) {
    return(c(-Inf, Inf))
  }
  if (!is.null(coord_limits)) {
    if (length(coord_limits) != 2) {
      coord_limits <- c(NA_real_, NA_real_)
    }
    limits <- coord_limits %|% limits
  }

  lower <- scales::expand_range(limits, expand[1], expand[2])[1]
  upper <- scales::expand_range(limits, expand[3], expand[4])[2]
  c(lower, upper)
}
teunbrand/ggvctrcoords documentation built on Jan. 12, 2020, 6:25 p.m.