Search code examples
ggplot2r-sffacet-grid

Using facet_grid to plot multiple spatial polygons with common polygon as overlay


I want to plot spatial data from a SpatialPolygonDataframe. More specifically I want to plot single spatial features in single subplots using facet_grid() of ggplot2. In addition I'd like to plot a common spatial polygon as overlay in each of the facets.

Here an example using a spatial dataset of the USA and its single states. Each state (of the subset) should be displayed in a single facet) while the outline of the USA (provided in another spatial dataset) should be plotted as overlay in each facet. With my current attempt, also the USA outline is split (based on ID) and spread across the facets:

library(sf)
library(ggplot2)

usa <- as(st_as_sf(maps::map(database="usa",fill=T, plot =FALSE)),"Spatial")
usa_states <- as(st_as_sf(maps::map(database="state",fill=T, plot =FALSE)),"Spatial")
usa_states <- usa_states[c(1:5),]

ggplot(data=usa_states)+
  geom_polygon(data=usa, aes(x = long, y = lat,group=id), 
               size = 1, colour = "red",fill=NA)+
  geom_polygon(data=usa_states, aes(x = long, y = lat,group=id), 
               size = 0.3, fill = "green",color="black",alpha=0.2)+
  facet_grid(facets= id ~.)

How can I specify that fact_grid only considers 'id' of the usa_states dataset and does not split up the usa outline?

enter image description here


Solution

  • Here is the solution. There's no need to transform sf to sp. You can use geom_sf function. The problem was because your id values are have the same names in both datasets.

    library(sf)
    library(ggplot2)
    library(dplyr)
    
    usa <- st_as_sf(maps::map(database="usa",fill=T, plot =FALSE))
    usa_states <- st_as_sf(maps::map(database="state",fill=T, plot =FALSE))
    usa_states <- usa_states[c(1:5),]
    
    usa_states <- usa_states %>% 
      rename(id = ID)
    
    ggplot(data = usa_states)+
      geom_sf(size = 0.3, fill = "green",color="black",alpha=0.2)+
      geom_sf(data = usa ,
                   size = 1, colour = "red",fill=NA) +
      facet_wrap(~ id)
    

    enter image description here