This is my first time doing any sort of spatial data visualization in R, and I'm stuck on a particular issue. I would like to clip a spatial polygon (specified by a series of lat/long coordinates) according to a world map, such that any part of the polygon which overlaps with a map polygon is removed. Using what I have in the below code as an example, I want to clip the rectangular spatial polygon so that only oceanic portions of the polygon remain.
I've found examples of how to retain the intersection between two spatial polygons, but I want to do the opposite. Perhaps there is a way to define the intersection, then "subtract" that from the polygon I wish to clip?
This might be a really basic question, but any tips will be appreciated!
Specify lat/long data:
x_coord <- c(25, 25, 275, 275)
y_coord <- c(20, -50, -50, 20)
xy.mat <- cbind(x_coord, y_coord)
xy.mat
Convert to spatial polygons object:
library(sp)
poly = Polygon(xy.mat)
polys = Polygons(list(poly),1)
spatial.polys = SpatialPolygons(list(polys))
proj4string(spatial.polys) = CRS("+proj=longlat +datum=WGS84 +no_defs
+ellps=WGS84 +towgs84=0,0,0")
Convert to spatial polygons data frame and export as shapefile:
df = data.frame(f=99.9)
spatial.polys.df = SpatialPolygonsDataFrame(spatial.polys, df)
spatial.polys.df
library(GISTools)
library(rgdal)
writeOGR(obj=spatial.polys.df, dsn="tmp", layer="polygon",
driver="ESRI Shapefile")
Plot world map and add .shp file:
map("world", wrap=c(0,360), resolution=0, ylim=c(-60,60))
map.axes()
shp <- readOGR("polygon.shp")
plot(shp, add=TRUE, col="blue", border=FALSE)