Search code examples
rggplot2geospatialspatial

Substitute to fortify to plot a map with sf package


I want to plot a map. In the early times, everything was OK, but with the absence of rgdal and maptools, some functions don't seem to have substitutes. For me it is the case of fortify; I try tidy and others functions without success.

In my example:

#----------------------------------------------------
# Map representation
library(sf)
library(ggplot2)

url <- "https://gist.githubusercontent.com/hrbrmstr/91ea5cc9474286c72838/raw/f3fde312c9b816dff3994f39f2bcda03209eff8f/continents.json"
stop_for_status(GET(url, write_disk("continents.json")))
continents <- geojson_sf("continents.json")
continents.f <- continents[continents$CONTINENT %in% c("North America", "Central America", "South America"),]
continents_map <- fortify(continents.f, region="CONTINENT")


gg <- ggplot() # the base map
gg <- gg + geom_map(data=continents_map, map=continents_map,
                    aes(x=long, y=lat, map_id=id, group=group),
                    fill="#ffffff", color="black", size=0.15) +
                    lims(x = c(-110, -20), y = c(-60, 20))
gg 
#---------------------------------------------------- 

Error in `geom_map()`:
! `map` must have the columns `x`, `y`, and `id`
Run `rlang::last_trace()` to see where the error occurred.

Please, any help with it?


Solution

  • Just load data with read_sf() from sf package and the fortify() is not necessary. It is recommended to use geom_sf() to plot map when the geojson data is loaded.

    library(sf)
    library(ggplot2)
    
    continents <- read_sf("https://gist.githubusercontent.com/hrbrmstr/91ea5cc9474286c72838/raw/f3fde312c9b816dff3994f39f2bcda03209eff8f/continents.json")
    continents.f <- continents[continents$CONTINENT %in% c("North America", "Central America", "South America"),]
    
    ggplot(data = continents.f) +
      geom_sf(fill="#ffffff", color="black", size=0.15) +
      lims(x = c(-110, -20), y = c(-60, 20))
    
    
    # add some values to fill
    continents.f$test <- 1:nrow(continents.f)
    ggplot(data = continents.f) +
      geom_sf(aes(fill = test)) +
      lims(x = c(-110, -20), y = c(-60, 20))