diff --git a/NEWS.md b/NEWS.md index bbe72af33f..97c111e8a0 100644 --- a/NEWS.md +++ b/NEWS.md @@ -12,6 +12,7 @@ * Patterns and gradients are now also enabled in `geom_sf()` (@teunbrand, #5716). * `stat_bin()` deals with non-finite breaks better (@teunbrand, #5665). +* Theme elements that do not exist now throw warnings instead of errors (#5719). * Fixed bug in `coord_radial()` where full circles were not treated as such (@teunbrand, #5750). * When legends detect the presence of values in a layer, `NA` is now detected diff --git a/R/theme-elements.R b/R/theme-elements.R index 7ac53ddffb..b8e83c75e4 100644 --- a/R/theme-elements.R +++ b/R/theme-elements.R @@ -620,7 +620,8 @@ validate_element <- function(el, elname, element_tree, call = caller_env()) { eldef <- element_tree[[elname]] if (is.null(eldef)) { - cli::cli_abort("The {.var {elname}} theme element is not defined in the element hierarchy.", call = call) + cli::cli_warn("The {.var {elname}} theme element is not defined in the element hierarchy.", call = call) + return() } # NULL values for elements are OK diff --git a/R/theme.R b/R/theme.R index ecade9aa62..62ac55f3c6 100644 --- a/R/theme.R +++ b/R/theme.R @@ -575,7 +575,8 @@ plot_theme <- function(x, default = theme_get()) { # Check that all elements have the correct class (element_text, unit, etc) validate_theme(theme) - theme + + theme[intersect(names(theme), names(get_element_tree()))] } #' Modify properties of an element in a theme object diff --git a/tests/testthat/test-theme.R b/tests/testthat/test-theme.R index 146ad29fc8..895d4cf9fc 100644 --- a/tests/testthat/test-theme.R +++ b/tests/testthat/test-theme.R @@ -293,7 +293,7 @@ test_that("incorrect theme specifications throw meaningful errors", { test_that("element tree can be modified", { # we cannot add a new theme element without modifying the element tree p <- ggplot() + theme(blablabla = element_text(colour = "red")) - expect_snapshot_error(print(p)) + expect_snapshot_warning(print(p)) register_theme_elements( element_tree = list(blablabla = el_def("character", "text"))