R/lim.R

Defines functions sanitize_lim_rev is_partial_lim resolve_lim cat_pad widen_degenerate expand_lim lim_args

# calculate limits of each plot

lim_args = function(settings) {
  env2env(
    settings,
    environment(),
    c(
      "xaxb", "xlabs", "xlim", "null_xlim", "rev_x",
      "yaxb", "ylabs", "ylim", "null_ylim", "rev_y",
      "datapoints", "type", "type_hints", "xpad", "ypad", "xaxs", "yaxs",
      "log"
    )
  )

  # For cases where x/yaxb is provided and corresponding x/ylabs is not null...
  # We can subset these here to provide breaks
  if (!is.null(xaxb) && !is.null(xlabs)) {
    xlabs = xlabs[names(xlabs) %in% xaxb]
    xaxb = NULL # don't need this any more
  }
  if (!is.null(yaxb) && !is.null(ylabs)) {
    ylabs = ylabs[names(ylabs) %in% yaxb]
    yaxb = NULL # don't need this any more
  }

  if (is.null(xlim)) {
    xlim = range(as.numeric(c(
      datapoints[["x"]], datapoints[["xmin"]],
      datapoints[["xmax"]])), finite = TRUE)
  } else if (length(xlim) != 2L || anyNA(xlim)) {
    xdrng = range(as.numeric(c(
      datapoints[["x"]], datapoints[["xmin"]],
      datapoints[["xmax"]])), finite = TRUE)
    xlim = resolve_lim(xlim, xdrng, "xlim")
  }
  if (is.null(ylim)) {
    ylim = range(as.numeric(c(
      datapoints[["y"]], datapoints[["ymin"]],
      datapoints[["ymax"]])), finite = TRUE)
  } else if (length(ylim) != 2L || anyNA(ylim)) {
    ydrng = range(as.numeric(c(
      datapoints[["y"]], datapoints[["ymin"]],
      datapoints[["ymax"]])), finite = TRUE)
    ylim = resolve_lim(ylim, ydrng, "ylim")
  }

  if (identical(type, "boxplot")) {
    xlim = xlim + c(-0.5, 0.5)
  }

  prop_lim = isTRUE(type_hints[["has_proportional_lim"]])
  if (null_xlim && !is.null(xaxb) && !prop_lim) xlim = range(c(xlim, xaxb))
  if (null_ylim && !is.null(yaxb) && !prop_lim) ylim = range(c(ylim, yaxb))

  # A categorical axis asks for its buffer in category widths; xpad speaks in
  # fractions of the range. Convert and let the existing machinery apply it.
  # An explicit x/ylim or x/yaxs = "i" is the user's call; leave those to base.
  if (isTRUE(type_hints[["pads_cat_axis"]])) {
    if (is.null(xpad) && !is.null(xlabs) && null_xlim && !identical(xaxs, "i")) {
      xpad = cat_pad(xlim)
    }
    if (is.null(ypad) && !is.null(ylabs) && null_ylim && !identical(yaxs, "i")) {
      ypad = cat_pad(ylim)
    }
  }

  if (!is.null(xpad)) {
    xlim = expand_lim(widen_degenerate(xlim), xpad,
                      log = grepl("x", log, fixed = TRUE))
  }
  if (!is.null(ypad)) {
    ylim = expand_lim(widen_degenerate(ylim), ypad,
                      log = grepl("y", log, fixed = TRUE))
  }

  # reverse axis direction last, once the range is otherwise finalized
  if (isTRUE(rev_x)) xlim = rev(xlim)
  if (isTRUE(rev_y)) ylim = rev(ylim)

  # update settings
  env2env(
    environment(),
    settings,
    c("xlim", "ylim", "xpad", "ypad", "xlabs", "ylabs", "xaxb", "yaxb")
  )
}


#
# x/ylim helpers ----
#

# Widen a data range by `pad` at each end, as a fraction of the range.
#
# A logged axis is expanded in log space, which is where base applies it too --
# expanding the raw values would put the padding in the wrong place entirely
# once the range spans decades.
expand_lim = function(lim, pad, log = FALSE) {
  if (length(lim) != 2L || !all(is.finite(lim))) return(lim)
  if (!is.finite(pad) || pad == 0) return(lim)
  logged = isTRUE(log) && all(lim > 0)
  if (logged) lim = log10(lim)
  out = lim + c(-1, 1) * pad * diff(lim)
  if (logged) out = 10^out
  out
}

# Widen a zero-width range the way base R does before any style expansion is
# applied: out to 0.4 of the value either side, or to +/-1 when the value is
# zero. Kept separate from expand_lim() because the three places tinyplot
# expands a range do not currently agree on this rule (base's here, 0.04 of the
# value in free facets, half a unit in the dynmar predictor). Reconciling them
# is a behaviour change and deliberately not part of this one.
widen_degenerate = function(lim) {
  if (length(lim) != 2L || !all(is.finite(lim)) || diff(lim) != 0) return(lim)
  lim + c(-1, 1) * (if (lim[1L] == 0) 1 else 0.4 * abs(lim[1L]))
}


# The categorical buffer as the fraction of the range that `xpad` wants, one
# category being one unit. Takes `lim` rather than a category count because
# dodging widens the span past n-1, and the gutter should clear what is drawn.
# Past a span of reach/0.04 (eight categories at the default) base's own 4%
# already reaches further, so NULL hands those plots back to it untouched. A
# quarter of a category, not the half box-like types take: a box is most of a
# category wide and needs the room; a point is not.
cat_pad = function(lim, reach = 0.25) {
  span = abs(diff(lim))
  if (!is.finite(span) || span == 0 || span > reach / 0.04) return(NULL)
  reach / span
}


# Resolve a user-supplied x/ylim that may be a scalar or contains a single NA.
# `lim`  : raw user value (already known to be non-NULL)
# `drng` : data range, 2-element numeric, i.e. range(..., finite = TRUE)
# Returns a 2-element numeric vector (raw; window padding applied downstream).
resolve_lim = function(lim, drng, arg = "xlim") {
  if (!is.numeric(lim)) {
    stop(sprintf("`%s` must be numeric (a scalar or length-2 vector).", arg), call. = FALSE)
  }
  n = length(lim)
  if (n == 1L) {
    if (is.na(lim)) stop(sprintf("`%s` cannot be a single `NA`.", arg), call. = FALSE)
    # scalar: ensure the value is covered alongside the data
    return(range(c(drng, lim)))
  }
  if (n == 2L) {
    nas = is.na(lim)
    if (all(nas)) {
      stop(sprintf("`%s` cannot be `c(NA, NA)`; supply at least one finite limit.", arg), call. = FALSE)
    }
    if (!any(nas)) return(lim) # full override: unchanged (reversed axis OK)
    # exactly one NA: fill that side from the data range, pin the other verbatim
    if (nas[1L]) lim[1L] = drng[1L] else lim[2L] = drng[2L]
    return(lim)
  }
  stop(sprintf("`%s` must be length 1 or 2, not length %d.", arg, n), call. = FALSE)
}

# Does a user-supplied x/ylim lean on the data range for at least one side, i.e.
# the scalar (xlim = 0) or single-NA (xlim = c(0, NA)) form? Free facets have to
# re-resolve those per panel; see facet_free_lim().
is_partial_lim = function(lim) {
  is.numeric(lim) &&
    (length(lim) == 1L || (length(lim) == 2L && sum(is.na(lim)) == 1L))
}

# Resolve an axis-reversal keyword passed to x/ylim, e.g. xlim = "reverse" (or
# the "rev" abbreviation). Returns a list with the (possibly NULL-ified) limit
# and a logical flag. When a keyword is detected we strip the limit back to NULL
# so that all the usual auto-range machinery (data range, breaks, free facets,
# type-specific limits) runs untouched; the flag is consumed later to rev() the
# finalized range.
sanitize_lim_rev = function(lim, arg = "xlim") {
  if (is.character(lim)) {
    rev_ok = length(lim) == 1L && !is.na(lim) &&
      nchar(lim) >= 3L && pmatch(tolower(lim), "reverse", nomatch = 0L) == 1L
    if (!rev_ok) {
      stop(sprintf('If `%s` is a character string it must be "reverse" (or "rev").', arg), call. = FALSE)
    }
    return(list(lim = NULL, rev = TRUE))
  }
  list(lim = lim, rev = FALSE)
}

Try the tinyplot package in your browser

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

tinyplot documentation built on Nov. 29, 2026, 9:07 a.m.