Search code examples
rggplot2mapsfacet-wrapgeom-sf

r facet wrap maps ggplot


I have an issue with using geom_sf and facet_wrap.

Below is a reproducible example. When I use 'ct_sf1` I dont see a boundary of my first geom_sf.

library(dplyr)
library(ggplot2)
library(sf)
library(tigris)

ct_sf <- tigris::county_subdivisions(state = "09", cb = T, class = "sf")

ct_sf1 <- ct_sf %>% rowwise() %>% mutate(group = as.character(sample(LETTERS[1:4], 1)))

ggplot(ct_sf1) +
  geom_sf(fill = "gray95", color = "gray50", size = 0.5) +
  geom_sf(aes(fill = group),inherit.aes = F) +
  facet_wrap(~group) 

enter image description here

However when I use the following code, with ct_sf in first geom_sf and ct_sf1 in second geom_sf it works, not sure what could be causing the first code to not work.

ggplot() +
  geom_sf(data = ct_sf,fill = "gray95", color = "gray50", size = 0.5) +
  geom_sf(data = ct_sf1,aes(fill = group)) +
  facet_wrap(~group) 

enter image description here


Solution

  • In the first code, the second geom_sf overlaps the first one because it applied to the same data, then facet_wrap splits the data by the groups.

    In the second code, facet_wrap splits only the ct_sf1 object, and the first object is drawn on all facets.

    By the way, you can faster the groups generation without using rowwise:

    ct_sf1 <- ct_sf %>% 
        mutate(group = as.character(sample(LETTERS[1:4], nrow(.), replace = T)))