Skip to content

Avoid bounded density discontinuity #5642

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

Merged
merged 5 commits into from
May 20, 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
2 changes: 2 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# ggplot2 (development version)

* The bounded density option in `stat_density()` uses a wider range to
prevent discontinuities (#5641).
* `geom_raster()` now falls back to rendering as `geom_rect()` when coordinates
are not Cartesian (#5503).
* `stat_ecdf()` now has an optional `weight` aesthetic (@teunbrand, #5058).
Expand Down
19 changes: 16 additions & 3 deletions R/stat-density.R
Original file line number Diff line number Diff line change
Expand Up @@ -148,10 +148,23 @@ compute_density <- function(x, w, from, to, bw = "nrd0", adjust = 1,
bw <- precompute_bw(x, bw)
# Decide whether to use boundary correction
if (any(is.finite(bounds))) {
dens <- stats::density(x, weights = w, bw = bw, adjust = adjust,
kernel = kernel, n = n)
# To prevent discontinuities, we widen the range before calling the
# unbounded estimator (#5641).
bounds <- sort(bounds)
range <- range(from, to)
width <- diff(range)
range[1] <- range[1] - width * as.numeric(is.finite(bounds[1]))
range[2] <- range[2] + width * as.numeric(is.finite(bounds[2]))
n <- n * (sum(is.finite(bounds)) + 1)

dens <- reflect_density(dens = dens, bounds = bounds, from = from, to = to)
dens <- stats::density(
x, weights = w, bw = bw, adjust = adjust,
kernel = kernel, n = n, from = range[1], to = range[2]
)
dens <- reflect_density(
dens = dens, bounds = bounds,
from = range[1], to = range[2]
)
} else {
dens <- stats::density(x, weights = w, bw = bw, adjust = adjust,
kernel = kernel, n = n, from = from, to = to)
Expand Down
4 changes: 2 additions & 2 deletions tests/testthat/test-stat-density.R
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ test_that("stat_density uses `bounds`", {
expect_equal(
orig_density(test_sample) + left_reflection + right_reflection,
plot_density(test_sample),
tolerance = 1e-4
tolerance = 1e-3
)
}

Expand Down Expand Up @@ -94,7 +94,7 @@ test_that("stat_density handles data outside of `bounds`", {
stat_density(bounds = c(cutoff, Inf))
)

expect_equal(data_actual, data_expected)
expect_equal(data_actual, data_expected, tolerance = 1e-4)
})

test_that("compute_density succeeds when variance is zero", {
Expand Down
Loading