diff --git a/NEWS.md b/NEWS.md index 70050e2ee2..d10c128d4e 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,5 +1,7 @@ # ggplot2 (development version) +* Binned scales with zero-width data expand the default limits by 0.1 + (@teunbrand, #5066) * New default `geom_qq_line(geom = "abline")` for better clipping in the vertical direction. In addition, `slope` and `intercept` are new computed variables in `stat_qq_line()` (@teunbrand, #6087). diff --git a/R/scale-.R b/R/scale-.R index 5ae52f65ab..1ab3381099 100644 --- a/R/scale-.R +++ b/R/scale-.R @@ -1292,9 +1292,17 @@ ScaleBinned <- ggproto("ScaleBinned", Scale, new_limits[1] <- breaks[1] breaks <- breaks[-1] } - } else { + } else if (nbreaks == 1) { bin_size <- max(breaks[1] - limits[1], limits[2] - breaks[1]) new_limits <- c(breaks[1] - bin_size, breaks[1] + bin_size) + } else { + new_limits <- limits + if (zero_range(new_limits)) { + # 0.1 is the same width as the expansion `default_expansion()` + # gives for 0-width data + new_limits <- new_limits + c(-0.05, 0.05) + } + breaks <- new_limits } new_limits_trans <- suppressWarnings(transformation$transform(new_limits)) limits[is.finite(new_limits_trans)] <- new_limits[is.finite(new_limits_trans)] diff --git a/tests/testthat/test-scale-binned.R b/tests/testthat/test-scale-binned.R index 527d862339..22ce6ef12a 100644 --- a/tests/testthat/test-scale-binned.R +++ b/tests/testthat/test-scale-binned.R @@ -104,3 +104,9 @@ test_that('binned scales can calculate breaks on date-times', { ))) ) }) + +test_that("binned scales can calculate breaks for zero-width data", { + scale <- scale_x_binned() + scale$train(c(1, 1)) + expect_equal(scale$get_breaks(), c(0.95, 1.05)) +})