From 0d2023d53ccbc88fc998b9c37b75f398d9671edf Mon Sep 17 00:00:00 2001 From: Teun van den Brand <49372158+teunbrand@users.noreply.github.com> Date: Tue, 12 Sep 2023 08:55:23 +0200 Subject: [PATCH] Violin resolution (#5402) * Preserve mapped_discrete class * Add test * Add news bullet --- NEWS.md | 3 +++ R/stat-ydensity.R | 5 ++++- tests/testthat/test-stat-ydensity.R | 16 ++++++++++++++++ 3 files changed, 23 insertions(+), 1 deletion(-) diff --git a/NEWS.md b/NEWS.md index ea136bae78..28cb0695a5 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,5 +1,8 @@ # ggplot2 (development version) +* `stat_ydensity()` with incomplete groups calculates the default `width` + parameter more stably (@teunbrand, #5396) + * `geom_boxplot()` gains a new argument, `staplewidth` that can draw staples at the ends of whiskers (@teunbrand, #5126) diff --git a/R/stat-ydensity.R b/R/stat-ydensity.R index a090898dea..c7f034bbd5 100644 --- a/R/stat-ydensity.R +++ b/R/stat-ydensity.R @@ -102,11 +102,14 @@ StatYdensity <- ggproto("StatYdensity", Stat, ) dens$y <- dens$x - dens$x <- mean(range(data$x)) # Compute width if x has multiple values if (vec_unique_count(data$x) > 1) { + dens$x <- mean(range(data$x)) width <- diff(range(data$x)) * 0.9 + } else { + # Explicitly repeat to preserve data$x's mapped_discrete class + dens$x <- vec_rep(data$x[1], nrow(dens)) } dens$width <- width diff --git a/tests/testthat/test-stat-ydensity.R b/tests/testthat/test-stat-ydensity.R index ecda132e04..98138d2d21 100644 --- a/tests/testthat/test-stat-ydensity.R +++ b/tests/testthat/test-stat-ydensity.R @@ -25,3 +25,19 @@ test_that("`drop = FALSE` preserves groups with 1 observations", { ) expect_equal(length(unique(ld$x)), 4) }) + +test_that("mapped_discrete class is preserved", { + + df <- data_frame0( + x = factor(rep(c("A", "C"), each = 3), c("A", "B", "C")), + y = 1:6 + ) + + ld <- layer_data( + ggplot(df, aes(x, y)) + geom_violin() + + scale_x_discrete(drop = FALSE) + ) + + expect_s3_class(ld$x, "mapped_discrete") + expect_equal(unique(ld$x), c(1, 3)) +})