Skip to content

Commit d79623a

Browse files
committed
isolate bandwidth logic
1 parent 7712c8d commit d79623a

File tree

1 file changed

+25
-18
lines changed

1 file changed

+25
-18
lines changed

R/stat-density-2d.R

Lines changed: 25 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -182,24 +182,7 @@ StatDensity2d <- ggproto("StatDensity2d", Stat,
182182
compute_group = function(data, scales, na.rm = FALSE, h = NULL, adjust = c(1, 1),
183183
n = 100, ...) {
184184

185-
if (is.null(h)) {
186-
# Note: MASS::bandwidth.nrd is equivalent to stats::bw.nrd * 4
187-
h <- c(MASS::bandwidth.nrd(data$x), MASS::bandwidth.nrd(data$y))
188-
# Handle case when when IQR == 0 and thus regular nrd bandwidth fails
189-
if (h[1] == 0) {
190-
h[1] <- bw.nrd0(data$x) * 4
191-
}
192-
if (h[2] == 0) {
193-
h[2] <- bw.nrd0(data$y) * 4
194-
}
195-
h <- h * adjust
196-
}
197-
if (any(is.na(h) | h <= 0)) {
198-
cli::cli_abort(c(
199-
"The bandwidth argument {.arg h} must contain numbers larger than 0.",
200-
i = "Please set the {.arg h} argument to stricly positive numbers manually."
201-
))
202-
}
185+
h <- precompute_2d_bw(data$x, data$y, h = h, adjust = adjust)
203186

204187
# calculate density
205188
dens <- MASS::kde2d(
@@ -232,3 +215,27 @@ StatDensity2dFilled <- ggproto("StatDensity2dFilled", StatDensity2d,
232215
contour_type = "bands"
233216
)
234217

218+
precompute_2d_bw <- function(x, y, h = NULL, adjust = 1) {
219+
220+
if (is.null(h)) {
221+
# Note: MASS::bandwidth.nrd is equivalent to stats::bw.nrd * 4
222+
h <- c(MASS::bandwidth.nrd(x), MASS::bandwidth.nrd(y))
223+
# Handle case when when IQR == 0 and thus regular nrd bandwidth fails
224+
if (h[1] == 0 && length(x) > 1) h[1] <- bw.nrd0(x) * 4
225+
if (h[2] == 0 && length(y) > 1) h[2] <- bw.nrd0(y) * 4
226+
h <- h * adjust
227+
}
228+
229+
check_numeric(h)
230+
check_length(h, 2L)
231+
232+
if (any(is.na(h) | h <= 0)) {
233+
cli::cli_abort(c(
234+
"The bandwidth argument {.arg h} must contain numbers larger than 0.",
235+
i = "Please set the {.arg h} argument to stricly positive numbers manually."
236+
))
237+
}
238+
239+
h
240+
}
241+

0 commit comments

Comments
 (0)