1

I'm trying to plot a map shapefile on top of a map downloaded using the ggmap package. However, I get a cryptic error message and a not very useful traceback:

Code:

map <- get_stamenmap( bbox = c(left = 3, bottom = 48, right = 3.5, top = 49), zoom = 12, maptype = "terrain")

transformed_sample = st_transform(rpg_sf %>% filter(commune %in% smallcomslist), crs=4326)

ggmap(map) + geom_sf(data=transformed_sample, mapping=aes(fill=commune),lwd=0) 

#Here transformed_sample is an object of class "sf" containing some outlines of villages in the area given by bbox.

#This returns:

ggmap(map) + 
   geom_sf(data=transformed_sample, mapping=aes(fill=commune),lwd=0) 

Coordinate system already present. Adding new coordinate system, which will replace the existing one.

Error in FUN(X[[i]], ...) : object 'lon' not found traceback()
10: FUN(X[[i]], ...)
9: lapply(aesthetics, eval_tidy, data = data, env = env)
8: f(..., self = self)
7: l$compute_aesthetics(d, plot)
6: f(l = layers[[i]], d = data[[i]])
5: by_layer(function(l, d) l$compute_aesthetics(d, plot))
4: ggplot_build.ggplot(x)
3: ggplot_build(x)
2: print.ggplot(x)
1: (function (x, ...)
UseMethod("print"))(x)

I have no idea why a "lon" is expected. Any ideas?

Peter
  • 11,500
  • 5
  • 21
  • 31
Holt Dwyer
  • 51
  • 5
  • This entry advises to use package `sf`s `plot`method for your `sf` object (= transformed_sample) and use its `bgMap` argument to set the stamen map in the background: https://stackoverflow.com/questions/47749078/how-to-put-a-geom-sf-produced-map-on-top-of-a-ggmap-produced-raster However, this approach repeatedly crashed my R session, so take care ;-) –  Mar 25 '22 at 08:44

1 Answers1

0

Very late to this party, but after going down a rabbit hole of Coordinate Reference System changes, I solved a similar error by simply adding inherit.aes = FALSE in the geom_sf() layer. So your code would become

ggmap(map) + 
      geom_sf(data = transformed_sample, mapping = aes(fill=commune), lwd=0, inherit.aes = FALSE) 

As an FYI, if you use tidyverse quite a bit, I would advise against naming an object map. The package purrr, which gets loaded when you run library(tidyverse) also has a function map().

Geraldine
  • 771
  • 3
  • 9
  • 23