Skip to content

Fix warning in geom_violin with draw_quantiles #4654

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
Mar 20, 2022
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
3 changes: 3 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
# ggplot2 (development version)

* `geom_violin()` no longer issues "collapsing to unique 'x' values" warning
(@bersbersbers, #4455)

* `annotate()` now documents unsupported geoms (`geom_abline()`, `geom_hline()`
and `geom_vline()`), and warns when they are requested (@mikmart, #4719)

Expand Down
2 changes: 1 addition & 1 deletion R/geom-violin.r
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,7 @@ GeomViolin <- ggproto("GeomViolin", Geom,
# Returns a data.frame with info needed to draw quantile segments.
create_quantile_segment_frame <- function(data, draw_quantiles) {
dens <- cumsum(data$density) / sum(data$density)
ecdf <- stats::approxfun(dens, data$y)
ecdf <- stats::approxfun(dens, data$y, ties = "ordered")
ys <- ecdf(draw_quantiles) # these are all the y-values for quantiles

# Get the violin bounds for the requested quantiles.
Expand Down
20 changes: 20 additions & 0 deletions tests/testthat/test-geom-violin.R
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,26 @@ test_that("quantiles do not fail on zero-range data", {
expect_equal(length(layer_grob(p)), 1)
})

test_that("quantiles are at expected positions at zero width", {
# Symmetric density with n components and zero middle:
# 50% quantile can be drawn anywhere as long as there is density 0
n <- 256
density <- c(rep(2, n / 4), rep(0, n / 2), rep(2, n / 4)) / n
density.data <- data_frame(y = (1:n) / n, density = density)
line <- create_quantile_segment_frame(density.data, 0.5)
y_idx <- which.min(abs(density.data$y - line$y[1]))
expect_equal(density[y_idx], 0)
})

test_that("quantiles do not issue warning", {
data <- data_frame(x = 1, y = c(0, 0.25, 0.5, 0.75, 5))

p <- ggplot(data, aes(x = x, y = y)) +
geom_violin(draw_quantiles = 0.5)

expect_warning(plot(p), regexp = NA)
})


# Visual tests ------------------------------------------------------------

Expand Down