Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Only use finite breaks for computing fuzz #5668

Merged
merged 7 commits into from
Feb 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading