Skip to content

Commit bc3e401

Browse files
authored
Only use finite breaks for computing fuzz (#5668)
* Only use finite breaks for computing fuzz * compute fuzz after sorting * protect against NA fuzzes * add news bullet * add test
1 parent 9b4d4fe commit bc3e401

File tree

3 files changed

+14
-2
lines changed

3 files changed

+14
-2
lines changed

NEWS.md

+1
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
* Fixed spurious warnings from `sec_axis()` with `breaks = NULL` (#5713).
99
* Patterns and gradients are now also enabled in `geom_sf()`
1010
(@teunbrand, #5716).
11+
* `stat_bin()` deals with non-finite breaks better (@teunbrand, #5665).
1112

1213
# ggplot2 3.5.0
1314

R/bin.R

+6-2
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,14 @@
11
bins <- function(breaks, closed = "right",
2-
fuzz = 1e-08 * stats::median(diff(breaks))) {
2+
fuzz = NULL) {
33
check_numeric(breaks)
44
closed <- arg_match0(closed, c("right", "left"))
5-
65
breaks <- sort(breaks)
6+
77
# Adapted base::hist - this protects from floating point rounding errors
8+
fuzz <- fuzz %||% 1e-08 * stats::median(diff(breaks[is.finite(breaks)]))
9+
if (!is.finite(fuzz)) { # happens when 0 or 1 finite breaks are given
10+
fuzz <- .Machine$double.eps * 1e3
11+
}
812
if (closed == "right") {
913
fuzzes <- c(-fuzz, rep.int(fuzz, length(breaks) - 1))
1014
} else {

tests/testthat/test-stat-bin.R

+7
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,13 @@ test_that("stat_bin() provides width (#3522)", {
112112

113113
# Underlying binning algorithm --------------------------------------------
114114

115+
test_that("bins() computes fuzz with non-finite breaks", {
116+
test <- bins(breaks = c(-Inf, 1, Inf))
117+
expect_equal(test$fuzzy, test$breaks, tolerance = 1e-10)
118+
difference <- test$fuzzy - test$breaks
119+
expect_equal(difference[2], 1000 * .Machine$double.eps, tolerance = 0)
120+
})
121+
115122
comp_bin <- function(df, ...) {
116123
plot <- ggplot(df, aes(x = x)) + stat_bin(...)
117124
layer_data(plot)

0 commit comments

Comments
 (0)