Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plotting geom_sf over ggmap shape

Tags:

r

ggplot2

ggmap

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?

like image 726
Holt Dwyer Avatar asked Feb 24 '26 22:02

Holt Dwyer


1 Answers

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().

like image 136
Geraldine Avatar answered Feb 26 '26 13:02

Geraldine



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!