diff --git a/R/plot-construction.R b/R/plot-construction.R index 188e5cc574..10cebca7eb 100644 --- a/R/plot-construction.R +++ b/R/plot-construction.R @@ -200,6 +200,12 @@ S7::method(update_ggplot, list(class_theme, class_ggplot)) <- S7::method(update_ggplot, list(class_coord, class_ggplot)) <- function(object, plot, ...) { if (!isTRUE(plot@coordinates$default)) { + + if (isTRUE(object$default)) { + # We don't let default coords override non-default coords (#6572) + return(plot) + } + cli::cli_inform(c( "Coordinate system already present.", i = "Adding new coordinate system, which will replace the existing one." diff --git a/tests/testthat/_snaps/coord-.md b/tests/testthat/_snaps/coord-.md index 563c7f475d..d4c6991988 100644 --- a/tests/testthat/_snaps/coord-.md +++ b/tests/testthat/_snaps/coord-.md @@ -34,3 +34,11 @@ Error: ! `1:3` must be a vector of length 2, not length 3. +# adding default coords works correctly + + Code + test <- test + coord_cartesian(xlim = c(-2, 2)) + Message + Coordinate system already present. + i Adding new coordinate system, which will replace the existing one. + diff --git a/tests/testthat/test-coord-.R b/tests/testthat/test-coord-.R index ea80cb5ce1..02ed6675ed 100644 --- a/tests/testthat/test-coord-.R +++ b/tests/testthat/test-coord-.R @@ -108,3 +108,31 @@ test_that("coord expand takes a vector", { }) +test_that("adding default coords works correctly", { + + base <- ggplot() + coord_cartesian(default = TRUE, xlim = c(0, 1)) + + # default + user = user + expect_no_message( + test <- base + coord_cartesian(xlim = c(-1, 1)) + ) + expect_equal(test@coordinates$limits$x, c(-1, 1)) + + # user1 + user2 = user2 + message + expect_snapshot( + test <- test + coord_cartesian(xlim = c(-2, 2)) + ) + expect_equal(test@coordinates$limits$x, c(-2, 2)) + + # user + default = user + expect_no_message( + test <- test + coord_cartesian(xlim = c(-3, 3), default = TRUE) + ) + expect_equal(test@coordinates$limits$x, c(-2, 2)) + + # default1 + default2 = default2 (silent) + expect_no_message( + test <- base + coord_cartesian(xlim = c(-4, 4), default = TRUE) + ) + expect_equal(test@coordinates$limits$x, c(-4, 4)) +})