Skip to content

Commit

Permalink
Fix for position_dodge(preserve = "single") with location based data (
Browse files Browse the repository at this point in the history
#6000)

* fallback for location based data

* Warn when x/xmin are absent
  • Loading branch information
teunbrand authored Sep 13, 2024
1 parent 6d48584 commit c3dd767
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
11 changes: 9 additions & 2 deletions R/position-dodge.R
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,11 @@ PositionDodge <- ggproto("PositionDodge", Position,
reverse = NULL,
setup_params = function(self, data) {
flipped_aes <- has_flipped_aes(data, default = self$orientation == "y")
check_required_aesthetics(
if (flipped_aes) "y|ymin" else "x|xmin",
names(data), snake_class(self)
)

data <- flip_data(data, flipped_aes)
if (is.null(data$xmin) && is.null(data$xmax) && is.null(self$width)) {
cli::cli_warn(c(
Expand All @@ -117,8 +122,10 @@ PositionDodge <- ggproto("PositionDodge", Position,
if (identical(self$preserve, "total")) {
n <- NULL
} else {
n <- vec_unique(data[c("group", "PANEL", "xmin")])
n <- vec_group_id(n[c("PANEL", "xmin")])
data$xmin <- data$xmin %||% data$x
cols <- intersect(colnames(data), c("group", "PANEL", "xmin"))
n <- vec_unique(data[cols])
n <- vec_group_id(n[setdiff(cols, "group")])
n <- max(tabulate(n, attr(n, "n")))
}

Expand Down
16 changes: 16 additions & 0 deletions tests/testthat/test-position_dodge.R
Original file line number Diff line number Diff line change
Expand Up @@ -37,3 +37,19 @@ test_that("position_dodge() can reverse the dodge order", {
ld <- get_layer_data(p + geom_col(position = position_dodge(reverse = FALSE)))
expect_equal(ld$label[order(ld$x)], c("A", "A", "B", "B", "C"))
})

test_that("position_dodge warns about missing required aesthetics", {

# Bit of a contrived geom to not have a required 'x' aesthetic
GeomDummy <- ggproto(NULL, GeomPoint, required_aes = NULL, optional_aes = "x")

p <- ggplot(mtcars, aes(cyl, disp, colour = factor(vs))) +
layer(
geom = GeomDummy,
stat = "identity",
position = position_dodge(width = 0.5),
mapping = aes(x = NULL)
)

expect_error(ggplot_build(p), "requires the following missing aesthetics")
})

0 comments on commit c3dd767

Please sign in to comment.