0

I am using the sf library to plot aggregate data and I would like to restrict my polygons to the borders of another set of polygons.

The image below is what I have

two inconsistent borders

I'm new to sf so I apologize if I am not using the right terminology but I would like to "constrain" the image to the grey borders while retaining all of it's contents. Is there a clean way to do this? In other words, dropping everything outside the borders.

Would it be easier to define new polygons in df_map or format the image itself within the ggplot call? I would prefer the latter but, if the former, how would this be done.

The code I can share on how the above to generate the above figure is as follows:

library(tidyverse)
library(sf)
library(ggplot2)


ggplot() + 
  geom_sf(data = df_map, aes(fill = yellow_or_red), color = NA) +
  geom_sf(data = grey_borders, fill = NA, lwd = 1) +
  scale_fill_gradientn(breaks = seq(0, 1250, 250), 
                       colors =  brewer.pal(length(seq(0, 1250, 250)), 
                                            "YlOrRd")) +
  theme(legend.title = element_blank()) + 
  theme(axis.title = element_blank(),
        panel.grid.major = element_blank(), 
        panel.grid.minor = element_blank(),
        panel.background = element_blank(), 
        axis.text = element_blank(),
        axis.line = element_blank(),
        axis.ticks = element_blank())
JRR
  • 578
  • 5
  • 21
  • 1
    [This](https://stackoverflow.com/a/60663346/5977215) seems like a related question / answer that may help. – SymbolixAU Jan 11 '21 at 02:47

1 Answers1

0

This was much easier than anticipated. sf::st_intersection() is intended for this exact purpose.

library(tidyverse)
library(sf)
library(ggplot2)

df <- df_map %>% st_intersection(grey_borders)
ggplot() + 
  geom_sf(data = df, aes(fill = yellow_or_red), color = NA) +
  geom_sf(data = grey_borders, fill = NA, lwd = 1) +
  scale_fill_gradientn(breaks = seq(0, 1250, 250), 
                       colors =  brewer.pal(length(seq(0, 1250, 250)), 
                                            "YlOrRd")) +
  theme(legend.title = element_blank()) + 
  theme(axis.title = element_blank(),
        panel.grid.major = element_blank(), 
        panel.grid.minor = element_blank(),
        panel.background = element_blank(), 
        axis.text = element_blank(),
        axis.line = element_blank(),
        axis.ticks = element_blank()) 
JRR
  • 578
  • 5
  • 21