Skip to content

Commit

Permalink
Violin resolution (#5402)
Browse files Browse the repository at this point in the history
* Preserve mapped_discrete class

* Add test

* Add news bullet
  • Loading branch information
teunbrand authored Sep 12, 2023
1 parent f6269b0 commit 0d2023d
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 1 deletion.
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)

* `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)

Expand Down
5 changes: 4 additions & 1 deletion R/stat-ydensity.R
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
16 changes: 16 additions & 0 deletions tests/testthat/test-stat-ydensity.R
Original file line number Diff line number Diff line change
Expand Up @@ -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))
})

0 comments on commit 0d2023d

Please sign in to comment.