scales icon indicating copy to clipboard operation
scales copied to clipboard

Feature request: integer breaks

Open mjskay opened this issue 1 year ago • 1 comments
trafficstars

I've been using breaks_width(1) to label count data, where we don't really want breaks that aren't whole numbers (or, more generally, integers). It works well except when the number of breaks can be very large. In those cases it would be very useful to have something that dynamically picks breaks but guarantees they are integers.

Something like breaks_extended(Q = c(1, 5, 2, 4, 3)), which is breaks_extended with the value 2.5 omitted from its default value of Q, works pretty well, except it will still generate non-integer values if the range of data is small.

I prototyped a variant based on breaks_extended() that uses this Q value but also filters out non-integer values, and as a final last-ditch effort just uses the rounded range of the data:

breaks_integer = function(n, ...) {
  n_default <- n
  function(x, n = n_default) {
    x <- x[is.finite(x)]
    if (length(x) == 0) {
      return(numeric())
    }

    rng <- range(x)
    breaks <- labeling::extended(rng[1], rng[2], n, Q = c(1, 5, 2, 4, 3), ...)
    breaks <- breaks[rlang::is_integerish(breaks)]
    if (length(breaks) == 0) {
      breaks <- unique(round(rng))
    }
    breaks
  }
}

Happy to open a PR if this would be useful.

mjskay avatar Jan 15 '24 00:01 mjskay

Happy to review a PR. Maybe breaks_whole() is a better name?

thomasp85 avatar Oct 22 '24 08:10 thomasp85

@mjskay is this something you are still interested in? I'll be prepping a release soonish...

thomasp85 avatar Apr 22 '25 13:04 thomasp85

Not the original poster but +1 to adding this somehow!

monicathieu avatar Nov 21 '25 20:11 monicathieu