Skip to content
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

Apply jitter in position_jitterdodge() once #5819

Merged
merged 4 commits into from
May 20, 2024
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 2 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,8 @@
returns input unaltered (@teunbrand, #5800).
* `width` is implemented as aesthetic instead of parameter in `geom_col()` and
`geom_bar()` (#3142).
* Fix a bug in `position_jitterdodge()` where different jitters would be applied
to different position aesthetics of the same axis (@teunbrand, #5818).

# ggplot2 3.5.1

Expand Down
13 changes: 12 additions & 1 deletion R/position-jitterdodge.R
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,18 @@ PositionJitterdodge <- ggproto("PositionJitterdodge", Position,
trans_x <- if (params$jitter.width > 0) function(x) jitter(x, amount = params$jitter.width)
trans_y <- if (params$jitter.height > 0) function(x) jitter(x, amount = params$jitter.height)

data <- with_seed_null(params$seed, transform_position(data, trans_x, trans_y))
x_aes <- intersect(ggplot_global$x_aes, names(data))
y_aes <- intersect(ggplot_global$y_aes, names(data))

x <- if (length(x_aes) == 0) 0 else data[[x_aes[1]]]
y <- if (length(y_aes) == 0) 0 else data[[y_aes[1]]]
dummy_data <- data_frame0(x = x, y = y, .size = nrow(data))

fixed_jitter <- with_seed_null(params$seed, transform_position(dummy_data, trans_x, trans_y))
x_jit <- fixed_jitter$x - x
y_jit <- fixed_jitter$y - y

data <- transform_position(data, function(x) x + x_jit, function(x) x + y_jit)
flip_data(data, params$flipped_aes)
}
)
12 changes: 12 additions & 0 deletions tests/testthat/test-position-jitterdodge.R
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,15 @@ test_that("position_jitterdodge() fails with meaningful error", {
p <- ggplot(mtcars) + geom_point(aes(disp, mpg), position = 'jitterdodge')
expect_snapshot_error(ggplot_build(p))
})

test_that("position_jitterdodge preserves widths", {
ld <- layer_data(
ggplot(mtcars, aes(factor(cyl), fill = factor(am))) +
geom_bar(position = position_jitterdodge())
)

expect_equal(
as.numeric(ld$xmax - ld$xmin),
rep(0.45, nrow(ld))
)
})