diff --git a/DESCRIPTION b/DESCRIPTION index f3b9ee7208..dcaf992c7f 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -67,7 +67,7 @@ Suggests: rpart, sf (>= 0.7-3), svglite (>= 2.1.2), - testthat (>= 3.1.2), + testthat (>= 3.1.5), vdiffr (>= 1.0.6), xml2 Enhances: diff --git a/NEWS.md b/NEWS.md index 583017fc33..67c07b0b05 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,5 +1,6 @@ # ggplot2 (development version) +* `geom_rug()` prints a warning when `na.rm = FALSE`, as per documentation (@pn317, #5905) * `position_dodge(preserve = "single")` now handles multi-row geoms better, such as `geom_violin()` (@teunbrand based on @clauswilke's work, #2801). * `position_jitterdodge()` now dodges by `group` (@teunbrand, #3656) diff --git a/R/geom-rug.R b/R/geom-rug.R index f41ea44fa8..a1273e3e08 100644 --- a/R/geom-rug.R +++ b/R/geom-rug.R @@ -157,5 +157,44 @@ GeomRug <- ggproto("GeomRug", Geom, draw_key = draw_key_path, - rename_size = TRUE + rename_size = TRUE, + + handle_na = function(self, data, params) { + sides_aes <- character() + + if (grepl("b|t", params$sides)) { + sides_aes <- c(sides_aes, "x") + } + + if (grepl("l|r", params$sides)) { + sides_aes <- c(sides_aes, "y") + } + + if (length(sides_aes) > 0) { + df_list <- lapply( + sides_aes, + function(axis) { + remove_missing( + data, params$na.rm, + c(axis, self$required_aes, self$non_missing_aes), + snake_class(self) + ) + } + ) + data <- switch( + paste0(sides_aes, collapse = ""), + "x" = , + "y" = df_list[[1]], + "xy" = vctrs::vec_set_union(df_list[[1]], df_list[[2]]) + ) + } else { + data <- remove_missing( + data, params$na.rm, + c(self$required_aes, self$non_missing_aes), + snake_class(self) + ) + } + + data + } ) diff --git a/tests/testthat/test-geom-rug.R b/tests/testthat/test-geom-rug.R index a613e58f0d..28aa17efcb 100644 --- a/tests/testthat/test-geom-rug.R +++ b/tests/testthat/test-geom-rug.R @@ -40,3 +40,21 @@ test_that("Rug lengths are correct", { }) +test_that( + "geom_rug() warns about missing values when na.rm = FALSE", + { + df2 <- df + n_missing <- 2 + df2$x[sample(nrow(df2), size = n_missing)] <- NA + + p1 <- ggplot(df2, aes(x = x)) + geom_rug() + p2 <- ggplot(df2, aes(x = x)) + geom_rug(na.rm = TRUE) + + expect_warning( + ggplotGrob(p1), + paste0("Removed ", n_missing, " rows containing missing values or values outside the scale range") + ) + + expect_no_warning(ggplotGrob(p2)) + } +)