Ok. So, I am learning and made a very similar question when I hadn't learnt what a Spatial Polygons Data Frame was about 10 days ago: Select raster in ggplot near coastline.
Now, I have discovered the magic of SPDF and choropleth maps and have in essence the same question but with different types of files. I am still wrapping my head around S4 objects and I can't figure out how to subset certain mini-polygons MUNICIPI
from my data set.
To the point!
Context:
I have a SPDF that contains these data:
Aim:
I would like to subset all MUNICIPI
that are within a certain distance from the coast. Let's say 20km as @urbandatascientist set in his answer to my first question and create a choropleth map of, for example, upper_trees
with the subsetted MUNICIPI
.
From the Select raster in ggplot near coastline post I also have the list.of.polygon.boundaries
that we'll substract MUNICIPI
coordinates from.
Once I subset the coastal MUNICIPI
, I'm hoping the map will look something like the green shaded region here. I have also tried to make sure that coordinates are in the same between list.of.polygon.boundaries
.
Any clues or ideas would be greatly appreciated!
So far, here's my chloropleth map for the entire region using upper_trees
as an example:
tm_shape(catasense2)+
tm_fill(col="upper_trees",n=8,style="quantile")+
tm_layout(legend.outside =TRUE)
Overview
Similar to the answer for Select raster in ggplot near coastline, the solution involves the following steps:
Calculating the coordinates for the boundaries of the Balearic (Iberian Sea) and Western Basin portions of the shape file for the western part of the Mediterranean Sea.
Calculating the centroids of each polygon in
MUNICIPI
from the OP's link to her Google Drive folder, which contains a .zip file of the shape file.Calculate the distance between the first two points and subset
MUNICIPI
to show the polygons whose distance from their centroid to the Western Basin is less than or equal to 20 kilometers.Filtering the Coordinates of the Western Basin
Rather than calculating the distance of each centroid to each coordinate pair within
western.basin.polygon.coordinates
, I only included coordinates withinwestern.basin.polygon.coordinates
whose latitudinal point was in between (inclusive) of the eastern coast of Catalonia.For reference, I use the latitudinal points of Peniscola, Catalonia and Cerbere, France. By only keeping the coordinate pairs that lay along the eastern coast of Catalonia, the distance calculation between
western.basin.polygon.coordinates
and each centroid inMUNICIPI
completes in about ~4 minutes.I then stored the indices of the polygons within
MUNICIPI
whose centroid distances were less than or equal to 20 kilometers inless.than.or.equal.to.max.km
- a logical vector of TRUE/FALSE values. Using a leaflet map, I show how I subsetMUNICIPI
to only visualize those polygons that contain TRUE values withinless.than.or.equal.to.max.km
.Session Info