rif-statementggplot2ggmap

Switch between ggplot and ggmap but retain the rest of the code?


I'm building a function which automates the map plotting for users' data, with various options, one of which is to allow different map backgrounds, either Google satellite from ggmap::get_map, or a global coastline processed by gbm.auto::gbm.basemap (my own package). The problem is, the plot starting function needs to be different, either ggmap or ggplot respectively, but the rest of the plot block is the same. I tried putting this as an option in braces:

if (mapsource == "gbm.basemap") {
      ggplot() +
        ggspatial::layer_spatial(shape, col = "black")
    } else {
      ggmap::ggmap(myMap)
    } +
    stars::geom_stars(data = predabundstars |> sf::st_transform(3857), inherit.aes = FALSE) +
    [more code, fill, theme, etc]

This works for the second option (else; ggmap):

ggmap google

But if mapsource == "gbm.basemap", it runs the initial code in braces but nothing after:

basemap fail

If I run the ggplot code outside of braces it works fine, so there's nothing wrong with the data, therefore it must be the 'braces to start a plot' bit:

basemap

I tried switching it around (ggmap then basemap), and doing them independently (if ggmap, if basemap) but still no dice. Is this a peculiarity of ggplot? Does anyone know a way around it? I suppose the 'nuclear' option would be duplicating the whole plot code block, one with ggmap, one with ggplot, and ifelse-ing them. I presume that would work but it also kinda sucks that it's that clunky.

Thanks in advance for any intel!


Solution

  • I would recommend assigning to an object within the if statement and then using this after the if statement:

    if (mapsource == "gbm.basemap") {
          p <- ggplot() +
            ggspatial::layer_spatial(shape, col = "black")
        } else {
          p <- ggmap::ggmap(myMap)
        }
    p <- p + stars::geom_stars(data = predabundstars |> sf::st_transform(3857), inherit.aes = FALSE)