diff --git a/R/stat-density.r b/R/stat-density.r index 6d18b8bb12..f9f865af76 100644 --- a/R/stat-density.r +++ b/R/stat-density.r @@ -66,6 +66,13 @@ StatDensity <- ggproto("StatDensity", Stat, required_aes = "x", default_aes = aes(y = stat(density), fill = NA, weight = NULL), + setup_params = function(data, params) { + if (!is.null(data$y)) { + stop("stat_density() must not be used with a y aesthetic.", call. = FALSE) + } + params + }, + compute_group = function(data, scales, bw = "nrd0", adjust = 1, kernel = "gaussian", n = 512, trim = FALSE, na.rm = FALSE) { if (trim) { diff --git a/tests/testthat/test-stat-density.R b/tests/testthat/test-stat-density.R index 9c4791e337..ff3996bf44 100644 --- a/tests/testthat/test-stat-density.R +++ b/tests/testthat/test-stat-density.R @@ -12,3 +12,10 @@ test_that("compute_density returns useful df and throws warning when <2 values", expect_equal(names(dens), c("x", "density", "scaled", "ndensity", "count", "n")) expect_type(dens$x, "double") }) + +test_that("stat_density throws error when y aesthetic is present", { + dat <- data_frame(x = 1:3, y = 1:3) + + expect_error(ggplot_build(ggplot(dat, aes(x, y)) + stat_density()), + "must not be used with a y aesthetic.") +})