Skip to content

Commit

Permalink
Only use finite breaks for computing fuzz (#5668)
Browse files Browse the repository at this point in the history
* Only use finite breaks for computing fuzz

* compute fuzz after sorting

* protect against NA fuzzes

* add news bullet

* add test
  • Loading branch information
teunbrand authored Feb 27, 2024
1 parent 9b4d4fe commit bc3e401
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 2 deletions.
1 change: 1 addition & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
* Fixed spurious warnings from `sec_axis()` with `breaks = NULL` (#5713).
* Patterns and gradients are now also enabled in `geom_sf()`
(@teunbrand, #5716).
* `stat_bin()` deals with non-finite breaks better (@teunbrand, #5665).

# ggplot2 3.5.0

Expand Down
8 changes: 6 additions & 2 deletions R/bin.R
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
bins <- function(breaks, closed = "right",
fuzz = 1e-08 * stats::median(diff(breaks))) {
fuzz = NULL) {
check_numeric(breaks)
closed <- arg_match0(closed, c("right", "left"))

breaks <- sort(breaks)

# Adapted base::hist - this protects from floating point rounding errors
fuzz <- fuzz %||% 1e-08 * stats::median(diff(breaks[is.finite(breaks)]))
if (!is.finite(fuzz)) { # happens when 0 or 1 finite breaks are given
fuzz <- .Machine$double.eps * 1e3
}
if (closed == "right") {
fuzzes <- c(-fuzz, rep.int(fuzz, length(breaks) - 1))
} else {
Expand Down
7 changes: 7 additions & 0 deletions tests/testthat/test-stat-bin.R
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,13 @@ test_that("stat_bin() provides width (#3522)", {

# Underlying binning algorithm --------------------------------------------

test_that("bins() computes fuzz with non-finite breaks", {
test <- bins(breaks = c(-Inf, 1, Inf))
expect_equal(test$fuzzy, test$breaks, tolerance = 1e-10)
difference <- test$fuzzy - test$breaks
expect_equal(difference[2], 1000 * .Machine$double.eps, tolerance = 0)
})

comp_bin <- function(df, ...) {
plot <- ggplot(df, aes(x = x)) + stat_bin(...)
layer_data(plot)
Expand Down

0 comments on commit bc3e401

Please sign in to comment.