Skip to content

Fix density calculations for groups with one or two elements #2142

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 4 commits into from
Jun 1, 2017
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
4 changes: 4 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# ggplot2 2.2.1.9000

* `geom_density` drops groups with fewer than two data points and throws a
warning. For groups with two data points, the density values are now
calculated with `stats::density` (@karawoo, #2127).

* `geom_smooth` now orders by the `x` aesthetic, making it easier to pass
pre-computed values without manual ordering (@izahn, #2028).

Expand Down
15 changes: 8 additions & 7 deletions R/stat-density.r
Original file line number Diff line number Diff line change
Expand Up @@ -85,14 +85,15 @@ compute_density <- function(x, w, from, to, bw = "nrd0", adjust = 1,
w <- rep(1 / nx, nx)
}

# if less than 3 points, spread density evenly over points
if (nx < 3) {
# if less than 2 points return data frame of NAs and a warning
if (nx < 2) {
warning("Groups with fewer than two data points have been dropped.", call. = FALSE)
return(data.frame(
x = x,
density = w / sum(w),
scaled = w / max(w),
count = 1,
n = nx
x = NA,
density = NA,
scaled = NA,
count = NA,
n = NA
))
}

Expand Down
6 changes: 3 additions & 3 deletions tests/testthat/test-stat-density.R
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@ test_that("compute_density succeeds when variance is zero", {
expect_equal(dens$n, rep(10, 512))
})

test_that("compute_density returns useful df when <3 values", {
dens <- compute_density(c(1, 2), NULL, from = 0, to = 0)
test_that("compute_density returns useful df and throws warning when <2 values", {
expect_warning(dens <- compute_density(1, NULL, from = 0, to = 0))

expect_equal(nrow(dens), 2)
expect_equal(nrow(dens), 1)
expect_equal(names(dens), c("x", "density", "scaled", "count", "n"))
})