Skip to content

Commit

Permalink
Remove scale limit clamping for binning
Browse files Browse the repository at this point in the history
  • Loading branch information
arcresu committed Jan 10, 2025
1 parent e2f2c01 commit 8b3baad
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 6 deletions.
6 changes: 0 additions & 6 deletions R/helpers_ggplot.R
Original file line number Diff line number Diff line change
Expand Up @@ -200,12 +200,6 @@ breaks_from_scale <- function(breaks, scale) {
major_breaks <- scale$get_breaks()
minor_breaks <- scale$get_breaks_minor()

# clamp to limits
# FIXME this might be too aggressive for bins at the limits
limits <- scale$get_limits()
major_breaks <- major_breaks[(major_breaks >= limits[[1]]) & (major_breaks <= limits[[2]])]
minor_breaks <- minor_breaks[(minor_breaks >= limits[[1]]) & (minor_breaks <= limits[[2]])]

breaks <- switch(breaks,
minor = minor_breaks,
major = major_breaks,
Expand Down
67 changes: 67 additions & 0 deletions tests/testthat/test-stat_bin_location.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
run_stat_bin_location <- function(data, ..., .x.scale = list()) {
plot <-
ggplot2::ggplot(data, aes(x, y)) +
rlang::inject(ggplot2::scale_x_date(!!!.x.scale)) +
stat_bin_location(...)

layer_data(plot)
}

s2d <- function(x) as.numeric(as.Date(x))

test_that("overflow bins work", {
computed <-
run_stat_bin_location(
data.frame(
x = as.Date(c(
"2020-02-01", "2020-12-31", # inside
"2000-01-01", "2021-02-01", # oob
"2020-01-01", "2020-07-01", "2021-01-01" # boundaries
)),
y = 1
),
overflow = list(x = TRUE, y = FALSE),
breaks = list(x = as.Date(c("2020-01-01", "2020-07-01", "2021-01-01")), y = 1:5),
closed = list(x = "right", y = "right"),
)

expect_equal(computed$xmin, c(
s2d("2020-01-01"), s2d("2020-07-01"),
-Inf, s2d("2021-01-01"),
s2d("2020-01-01"), s2d("2020-01-01"), s2d("2020-07-01")
))
expect_equal(computed$xmax, c(
s2d("2020-07-01"), s2d("2021-01-01"),
s2d("2020-01-01"), Inf,
s2d("2020-07-01"), s2d("2020-07-01"), s2d("2021-01-01")
))
})

test_that("overflow bins work with left-closed bins", {
computed <-
run_stat_bin_location(
data.frame(
x = as.Date(c(
"2020-02-01", "2020-12-31", # inside
"2000-01-01", "2021-02-01", # oob
"2020-01-01", "2020-07-01", "2021-01-01" # boundaries
)),
y = 1
),
overflow = list(x = TRUE, y = FALSE),
breaks = list(x = as.Date(c("2020-01-01", "2020-07-01", "2021-01-01")), y = 1:5),
closed = list(x = "left", y = "right"),
.x.scale = list(oob = scales::oob_censor)
)

expect_equal(computed$xmin, c(
s2d("2020-01-01"), s2d("2020-07-01"),
-Inf, s2d("2021-01-01"),
s2d("2020-01-01"), s2d("2020-07-01"), s2d("2020-07-01")
))
expect_equal(computed$xmax, c(
s2d("2020-07-01"), s2d("2021-01-01"),
s2d("2020-01-01"), Inf,
s2d("2020-07-01"), s2d("2021-01-01"), s2d("2021-01-01")
))
})

0 comments on commit 8b3baad

Please sign in to comment.