diff --git a/NEWS.md b/NEWS.md index 3b4926b206..3db3d030ea 100644 --- a/NEWS.md +++ b/NEWS.md @@ -197,6 +197,7 @@ `labs()` and several guides (@teunbrand, #3196). * `stat_summary_bin()` no longer ignores `width` parameter (@teunbrand, #4647). * Added `keep.zeroes` argument to `stat_bin()` (@teunbrand, #3449) +* `coord_sf()` no longer errors when dealing with empty graticules (@teunbrand, #6052) # ggplot2 3.5.1 diff --git a/R/coord-sf.R b/R/coord-sf.R index c31af6d393..c563ded9c2 100644 --- a/R/coord-sf.R +++ b/R/coord-sf.R @@ -657,6 +657,9 @@ sf_breaks <- function(scale_x, scale_y, bbox, crs) { #' @keywords internal view_scales_from_graticule <- function(graticule, scale, aesthetic, label, label_graticule, bbox) { + if (empty(graticule)) { + return(ggproto(NULL, ViewScale)) + } # Setup position specific parameters # Note that top/bottom doesn't necessarily mean to label the meridians and diff --git a/tests/testthat/test-coord_sf.R b/tests/testthat/test-coord_sf.R index 12a667be5b..a25d470e3b 100644 --- a/tests/testthat/test-coord_sf.R +++ b/tests/testthat/test-coord_sf.R @@ -371,3 +371,27 @@ test_that("coord_sf() throws error when limits are badly specified", { # throws error when limit's length is different than two expect_snapshot_error(ggplot() + coord_sf(ylim=1:3)) }) + +test_that("coord_sf() can render with empty graticules", { + + skip_if_not_installed("sf") + # Skipping this test on CRAN as changes upstream in {sf} might affect + # this test, i.e. when suddenly graticules *do* work + skip_on_cran() + + df <- sf::st_sf( + g = sf::st_sfc(sf::st_point( + # Out of bounds values for lon/lat + c(-600, 1200) + )), + crs = 4326 + ) + + # Double-check graticule is empty, suppressing warnings about oob longlat values + grat <- suppressWarnings(sf::st_graticule(df)) + expect_equal(nrow(grat), 0) + + # Plot should render + p <- suppressWarnings(layer_grob(ggplot(df) + geom_sf())[[1]]) + expect_length(p$x, 1) +})