From e69687a407addd2c29510153de52a128bde4701e Mon Sep 17 00:00:00 2001 From: Teun van den Brand <49372158+teunbrand@users.noreply.github.com> Date: Mon, 26 Aug 2024 16:10:19 +0200 Subject: [PATCH] Ignore empty non-mapped aesthetics (#6011) * drop empty aesthetics with warning * add test * add news bullet --- NEWS.md | 2 ++ R/layer.R | 9 +++++++++ tests/testthat/test-layer.R | 7 +++++++ 3 files changed, 18 insertions(+) diff --git a/NEWS.md b/NEWS.md index b4636c5166..4cab4f4c79 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,5 +1,7 @@ # ggplot2 (development version) +* Passing empty unmapped aesthetics to layers raises a warning instead of + throwing an error (@teunbrand, #6009). * Moved {mgcv} from Imports to Suggests (@teunbrand, #5986) * New `reset_geom_defaults()` and `reset_stat_defaults()` to restore all geom or stat default aesthetics at once (@teunbrand, #5975). diff --git a/R/layer.R b/R/layer.R index 59a9dba096..eba8666de4 100644 --- a/R/layer.R +++ b/R/layer.R @@ -146,6 +146,15 @@ layer <- function(geom = NULL, stat = NULL, if (any(pattern)) { aes_params[pattern] <- lapply(aes_params[pattern], list) } + # Drop empty aesthetics + empty_aes <- names(aes_params)[lengths(aes_params) == 0] + if (length(empty_aes) > 0) { + cli::cli_warn( + "Ignoring empty aesthetic{?s}: {.arg {empty_aes}}.", + call = call_env + ) + aes_params <- aes_params[setdiff(names(aes_params), empty_aes)] + } # Warn about extra params and aesthetics extra_param <- setdiff(names(params), all) diff --git a/tests/testthat/test-layer.R b/tests/testthat/test-layer.R index 8be6c8555f..51f0cd9eee 100644 --- a/tests/testthat/test-layer.R +++ b/tests/testthat/test-layer.R @@ -25,6 +25,13 @@ test_that("unknown aesthetics create warning", { expect_warning(geom_point(aes(blah = "red")), "unknown aesthetics") }) +test_that("empty aesthetics create warning", { + expect_warning( + geom_point(fill = NULL, shape = character()), + "Ignoring empty aesthetics" + ) +}) + test_that("invalid aesthetics throws errors", { # We want to test error and ignore the scale search message suppressMessages({