Skip to content

Commit 15d38fb

Browse files
authored
Make sure jitter is only calculated once (#4403)
1 parent a9cc097 commit 15d38fb

File tree

2 files changed

+15
-1
lines changed

2 files changed

+15
-1
lines changed

NEWS.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
# ggplot2 (development version)
22

3+
* Fix a bug in `position_jitter()` where different jitters would be applied to
4+
different position aesthetics of the same axis (@thomasp85, #2941)
5+
36
* `ggsave()` now uses ragg to render raster output if ragg is available
47
(@thomasp85, #4388)
58

R/position-jitter.r

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,17 @@ PositionJitter <- ggproto("PositionJitter", Position,
7676
trans_x <- if (params$width > 0) function(x) jitter(x, amount = params$width)
7777
trans_y <- if (params$height > 0) function(x) jitter(x, amount = params$height)
7878

79-
with_seed_null(params$seed, transform_position(data, trans_x, trans_y))
79+
# Make sure x and y jitter is only calculated once for all position aesthetics
80+
x_aes <- intersect(ggplot_global$x_aes, names(data))
81+
x <- if (length(x_aes) == 0) 0 else data[[x_aes[1]]]
82+
y_aes <- intersect(ggplot_global$y_aes, names(data))
83+
y <- if (length(y_aes) == 0) 0 else data[[y_aes[1]]]
84+
dummy_data <- new_data_frame(list(x = x, y = y), nrow(data))
85+
fixed_jitter <- with_seed_null(params$seed, transform_position(dummy_data, trans_x, trans_y))
86+
x_jit <- fixed_jitter$x - x
87+
y_jit <- fixed_jitter$y - y
88+
89+
# Apply jitter
90+
transform_position(data, function(x) x + x_jit, function(x) x + y_jit)
8091
}
8192
)

0 commit comments

Comments
 (0)