Skip to content
Open
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
1 change: 1 addition & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
* `theme(strip.placement.x)` and `theme(strip.placement.y)` can be used for more
granular control of strip placement when facetting. These have existed for some
time but were not previously documented (@arcresu, #6827).
* Added support for weighted quantiles in `geom_density` (@hughjonesd)

# ggplot2 4.0.2

Expand Down
8 changes: 4 additions & 4 deletions R/stat-ydensity.R
Original file line number Diff line number Diff line change
Expand Up @@ -75,11 +75,11 @@ StatYdensity <- ggproto(
cli::cli_abort("{.arg quantiles} must be between 0 and 1.")
}
if (!is.null(data[["weight"]]) || !all(data[["weight"]] == 1)) {
cli::cli_warn(
"{.arg quantiles} for weighted data is not implemented."
)
check_installed("Hmisc")
quants <- Hmisc::wtd.quantile(data$y, weights = data$weight, probs = quantiles)
} else {
quants <- stats::quantile(data$y, probs = quantiles)
}
quants <- stats::quantile(data$y, probs = quantiles)
quants <- data_frame0(
y = unname(quants),
quantile = quantiles
Expand Down
12 changes: 12 additions & 0 deletions tests/testthat/test-stat-ydensity.R
Original file line number Diff line number Diff line change
Expand Up @@ -51,3 +51,15 @@ test_that("quantiles are based on actual data (#4120)", {

expect_equal(ld$y[!is.na(ld$quantile)], 1:9)
})

test_that("weighted quantiles are correct", {

df <- data.frame(y = c(0:10, 20), weight = c(rep(1, 11), 0))
q <- seq(0.1, 0.9, by = 0.1)

p <- ggplot(df, aes("X", y, weight = weight)) +
stat_ydensity(quantiles = q)
ld <- get_layer_data(p)

expect_equal(ld$y[!is.na(ld$quantile)], 1:9)
})
Loading