Skip to content

Fix overlap identification in position_dodge2() #5939

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

Merged
merged 7 commits into from
Jul 11, 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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,8 @@
* `geom_hline()` and `geom_vline()` now have `position` argument
(@yutannihilation, #4285).
* New function `get_strip_labels()` to retrieve facet labels (@teunbrand, #4979)
* Fixed bug in `position_dodge2()`'s identification of range overlaps
(@teunbrand, #5938, #4327).

# ggplot2 3.5.1

Expand Down
23 changes: 14 additions & 9 deletions R/position-dodge2.R
Original file line number Diff line number Diff line change
Expand Up @@ -132,14 +132,19 @@ pos_dodge2 <- function(df, width, n = NULL, padding = 0.1) {

# Find groups of overlapping elements that need to be dodged from one another
find_x_overlaps <- function(df) {
overlaps <- numeric(nrow(df))
overlaps[1] <- counter <- 1

for (i in seq_asc(2, nrow(df))) {
if (is.na(df$xmin[i]) || is.na(df$xmax[i - 1]) || df$xmin[i] >= df$xmax[i - 1]) {
counter <- counter + 1
}
overlaps[i] <- counter
}
overlaps
start <- df$xmin
nonzero <- df$xmax != df$xmin
missing <- is.na(df$xmin) | is.na(df$xmax)
start <- vec_fill_missing(start, "downup")
end <- vec_fill_missing(df$xmax, "downup")

# For end we take largest end seen so far of previous observation
end <- cummax(c(end[1], end[-nrow(df)]))
# Start new group when 'start >= end' for non zero-width ranges
# For zero-width ranges, start must be strictly larger than end
overlaps <- cumsum(start > end | (start == end & nonzero))
# Missing ranges always get separate group
overlaps[missing] <- seq_len(sum(missing)) + max(overlaps, na.rm = TRUE)
match(overlaps, unique0(overlaps))
}
8 changes: 8 additions & 0 deletions tests/testthat/test-position-dodge2.R
Original file line number Diff line number Diff line change
Expand Up @@ -118,3 +118,11 @@ test_that("groups are different when two blocks have externall touching point",{
)
expect_equal(find_x_overlaps(df1), seq_len(2))
})

test_that("overlaps are identified correctly", {
df <- data.frame(
xmin = c(1, 2, 3, 5),
xmax = c(4, 3, 4, 6)
)
expect_equal(find_x_overlaps(df), c(1, 1, 1, 2))
})
Loading