From b733fba67d9de123498dd9d0f22d99e8e33d725b Mon Sep 17 00:00:00 2001 From: Teun van den Brand Date: Tue, 27 Aug 2024 09:24:53 +0200 Subject: [PATCH 1/3] skip viewscales for empty graticules --- R/coord-sf.R | 3 +++ 1 file changed, 3 insertions(+) diff --git a/R/coord-sf.R b/R/coord-sf.R index a14b3c718c..d8ff3c9e10 100644 --- a/R/coord-sf.R +++ b/R/coord-sf.R @@ -658,6 +658,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 From 07cbf37d9f68b509df690dd300a96ed25df5ef5e Mon Sep 17 00:00:00 2001 From: Teun van den Brand Date: Tue, 27 Aug 2024 09:25:09 +0200 Subject: [PATCH 2/3] add test --- tests/testthat/test-coord_sf.R | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) 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) +}) From 424967d2ef257374367fdca26e4f938664cd3998 Mon Sep 17 00:00:00 2001 From: Teun van den Brand Date: Tue, 27 Aug 2024 09:27:35 +0200 Subject: [PATCH 3/3] add news bullet --- NEWS.md | 1 + 1 file changed, 1 insertion(+) diff --git a/NEWS.md b/NEWS.md index 4cab4f4c79..54940a4a5f 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,5 +1,6 @@ # ggplot2 (development version) +* `coord_sf()` no longer errors when dealing with empty graticules (@teunbrand, #6052) * Passing empty unmapped aesthetics to layers raises a warning instead of throwing an error (@teunbrand, #6009). * Moved {mgcv} from Imports to Suggests (@teunbrand, #5986)