Skip to content

Commit b5cab7e

Browse files
committed
Add adjust param to stat_density2d() (fix tidyverse#2860)
1 parent 7f317d4 commit b5cab7e

File tree

3 files changed

+17
-2
lines changed

3 files changed

+17
-2
lines changed

NEWS

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@ ggplot2 1.0.1
66
* Improvements to order of colours and legend display for continuous colour
77
scales extracted from colorbrewer palettes by `scale_*_distiller()` (@jiho, 1076)
88

9+
* `stat_density2d()` can now take an `adjust` parameter to scale the default bandwidth. (#2860, @haleyjeppson)
10+
911
ggplot2 1.0.0
1012
----------------------------------------------------------------
1113

R/stat-density-2d.r

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,10 @@
55
#' @param n number of grid points in each direction
66
#' @param h Bandwidth (vector of length two). If `NULL`, estimated
77
#' using [MASS::bandwidth.nrd()].
8+
#' @param adjust A multiplicate bandwidth adjustment to be used if 'h' is
9+
#' 'NULL'. This makes it possible to adjust the bandwidth while still
10+
#' using the a bandwidth estimator. For example, `adjust = 1/2` means
11+
#' use half of the default bandwidth.
812
#' @section Computed variables:
913
#' Same as [stat_contour()]
1014
#'
@@ -19,6 +23,7 @@ stat_density_2d <- function(mapping = NULL, data = NULL,
1923
contour = TRUE,
2024
n = 100,
2125
h = NULL,
26+
adjust = c(1, 1),
2227
na.rm = FALSE,
2328
show.legend = NA,
2429
inherit.aes = TRUE) {
@@ -35,6 +40,7 @@ stat_density_2d <- function(mapping = NULL, data = NULL,
3540
contour = contour,
3641
n = n,
3742
h = h,
43+
adjust = adjust,
3844
...
3945
)
4046
)
@@ -54,11 +60,12 @@ StatDensity2d <- ggproto("StatDensity2d", Stat,
5460

5561
required_aes = c("x", "y"),
5662

57-
compute_group = function(data, scales, na.rm = FALSE, h = NULL,
63+
compute_group = function(data, scales, na.rm = FALSE, h = NULL, adjust = c(1, 1),
5864
contour = TRUE, n = 100, bins = NULL,
5965
binwidth = NULL) {
6066
if (is.null(h)) {
6167
h <- c(MASS::bandwidth.nrd(data$x), MASS::bandwidth.nrd(data$y))
68+
h <- h * adjust
6269
}
6370

6471
dens <- MASS::kde2d(

man/geom_density_2d.Rd

Lines changed: 7 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)