ScienceNoob
ScienceNoob

Reputation: 231

Geojson on ggmap: Error occurred in the 4th layer

I want to display a geojson file from URL on a map via ggmap. It works when I just plot the geometry via plot():

intensity_url <- "https://earthquake.usgs.gov/realtime/product/shakemap/us6000jllz/us/1675733020783/download/cont_mmi.json"
intensity <- geojson_read(data_url, what = "sp")
intensity <- sf::read_sf(intensity_url)

plot(intensity$geometry)

Output: enter image description here

But when I add this geometry on ggmap, it shows an error:

bbox <- c(28.841667, 29.866555, 48.266738, 44.65)

myMap <- get_stamenmap(bbox=bbox)

ggmap(myMap) +
  geom_sf(aes(long, lat, group = group), data = intensity$geometry)

Error message:

ℹ Map tiles by Stamen Design, under CC BY 3.0. Data by OpenStreetMap, under ODbL.
ℹ 3024 tiles needed, this may take a while (try a smaller zoom?)
Warning: Ignoring unknown aesthetics: x and yCoordinate system already present. Adding new coordinate system, which will replace the existing one.Error in `geom_sf()`:
! Problem while computing aesthetics.
ℹ Error occurred in the 4th layer.
Caused by error in `FUN()`:
! object 'group' not found
Backtrace:
  1. base (local) `<fn>`(x)
  2. ggplot2:::print.ggplot(x)
  4. ggplot2:::ggplot_build.ggplot(x)
  5. ggplot2:::by_layer(...)
 12. ggplot2 (local) f(l = layers[[i]], d = data[[i]])
 13. l$compute_aesthetics(d, plot)
 14. ggplot2 (local) compute_aesthetics(..., self = self)
 15. ggplot2:::scales_add_defaults(...)
 16. base::lapply(aesthetics[new_aesthetics], eval_tidy, data = data)
 17. rlang (local) FUN(X[[i]], ...)
Error in geom_sf(aes(long, lat, group = group), data = intensity$geometry) :

ℹ Error occurred in the 4th layer.
Caused by error in `FUN()`:
! object 'group' not found

Note: When I remove the group from aes, then it will show the same error with long.

Do you have any idea why this error is shown?

Upvotes: 1

Views: 762

Answers (1)

margusl
margusl

Reputation: 17584

Try with inherit.aes = FALSE
Also, for geom_sf() data shouldn't be the geometry column but the sf object itself (data = intensity) and variables in aes() should also exist in the data (i.e. something from names(intensity), so long / lat / group will not do).

library(sf)
#> Linking to GEOS 3.9.3, GDAL 3.5.2, PROJ 8.2.1; sf_use_s2() is TRUE
library(ggmap)
intensity_url <- "https://earthquake.usgs.gov/realtime/product/shakemap/us6000jllz/us/1675733020783/download/cont_mmi.json"

intensity <- read_sf(intensity_url)
bbox <- st_bbox(intensity) |> unname()

get_stamenmap(bbox, zoom = 6, maptype = "toner-lite") %>% 
  ggmap() +
  geom_sf(aes(color = color), data = intensity, inherit.aes = FALSE) +
  scale_color_identity()
#> ℹ Map tiles by Stamen Design, under CC BY 3.0. Data by OpenStreetMap, under ODbL.
#> Coordinate system already present. Adding new coordinate system, which will
#> replace the existing one.

Created on 2023-02-08 with reprex v2.0.2

Upvotes: 1

Related Questions