diff --git a/NEWS.md b/NEWS.md index b297a93bad..3818fe385a 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,5 +1,8 @@ # ggplot2 (development version) +* Fix a bug in `position_dodge2()` where `NA` values in thee data would cause an + error (@thomasp85, #2905) + * Fix a bug in `position_jitter()` where different jitters would be applied to different position aesthetics of the same axis (@thomasp85, #2941) diff --git a/R/position-dodge2.r b/R/position-dodge2.r index 2423bb396b..4f27cb7676 100644 --- a/R/position-dodge2.r +++ b/R/position-dodge2.r @@ -138,7 +138,7 @@ find_x_overlaps <- function(df) { overlaps[1] <- counter <- 1 for (i in seq_asc(2, nrow(df))) { - if (df$xmin[i] >= df$xmax[i - 1]) { + 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 diff --git a/tests/testthat/test-position-dodge2.R b/tests/testthat/test-position-dodge2.R index 7c7d748022..08aa70082f 100644 --- a/tests/testthat/test-position-dodge2.R +++ b/tests/testthat/test-position-dodge2.R @@ -107,3 +107,11 @@ test_that("width of groups is computed per facet", { expect_true(all(width == (0.9 / 3) * 0.9)) }) + +test_that("NA values are given their own group", { + df <- data.frame( + xmin = c(1, 2, NA, NA), + xmax = c(1, 2, NA, NA) + ) + expect_equal(find_x_overlaps(df), seq_len(4)) +})