I am newish to R and very new to GIS plotting on R with sf and ggplot2 packages. I have a dataset "comuni" containing all communes in Italy (similar to counties) and one of all motorways in Italy called "only_motorway". I know that I can use certain regions as a cookie cutter and keep only the motorways that are contained within such regions using st_intersection() function. However, I would like to do the inverse where, given I have a shapefile of the A3 motorway, I would like to keep only those communes that are crossed by that specific motorway.
I've tried using st_intersection function in the following way:
only_motorway_A3 <- only_motorway %>%
filter(ref == "A3")
comuni_A3 <- st_intersection(only_motorway_A3,comuni)
ggplot()
geom_sf(data = comuni_A3,
color = "black", size = 0.1, fill = "black")
geom_sf(data = only_motorway_A3, size = 0.15, color = "green")
coord_sf(crs = 32632)
theme_void()
But the results is the picture below:
ie both only_motorway_A3 and comuni_A3 have the same geometry column and they both plot the highway line. What I wanted to plot instead was the highway line (in green) from only_motoway_A3 and all around it the communes crossed by it (in black) from comuni_A3. I hope it is clear and thank you in advance for your help!
CodePudding user response:
Consider a sf::st_join()
call, using first your polygons and secondly your line string objects, with parameter left
set to false.
It will perform an inner (filtering) spatial join of the two objects. Only those polygons (the first argument) that contain a motorway will be retained.