通过R中的世界地图剪辑空间多边形

时间:2018-03-13 22:17:54

标签: r gis geospatial spatial

这是我第一次在R中进行任何类型的空间数据可视化,而我仍然坚持一个特定的问题。我想根据世界地图剪切空间多边形(由一系列纬度/经度坐标指定),以便移除与地图多边形重叠的多边形的任何部分。使用我在下面的代码中作为示例,我想剪切矩形空间多边形,以便只保留多边形的海洋部分。

我找到了如何保留两个空间多边形之间交集的示例,但我想做相反的事情。也许有一种方法来定义交叉点,然后"减去"我希望剪辑多边形?

这可能是一个非常基本的问题,但任何提示都将不胜感激!

指定纬度/经度数据:

x_coord <- c(25, 25, 275, 275)
y_coord <- c(20, -50, -50, 20)
xy.mat <- cbind(x_coord, y_coord)
xy.mat

转换为空间多边形对象:

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")

转换为空间多边形数据框并导出为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")

绘制世界地图并添加.shp文件:

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)

2 个答案:

答案 0 :(得分:4)

这是一个始终保持sf的解决方案(我不知道sp),并说明从头开始构建sf对象。 st_difference创建您想要的几何图形,然后可以使用基本图方法或ggplot的开发版本geom_sf来完成绘图。我使用了来自mapsrnaturalearth的地图数据,您可以根据自己的具体情况进行调整。不幸的是,缠绕日期线有点挑剔。

library(tidyverse)
library(sf)
#> Linking to GEOS 3.6.1, GDAL 2.2.0, proj.4 4.9.3
library(rnaturalearth)
library(maps)
#> 
#> Attaching package: 'maps'
#> The following object is masked from 'package:purrr':
#> 
#>     map

x_coord <- c(25, 25, 275, 275)
y_coord <- c(20, -50, -50, 20)
polygon <-  cbind(x_coord, y_coord) %>%
  st_linestring() %>%
  st_cast("POLYGON") %>%
  st_sfc(crs = 4326, check_ring_dir = TRUE) %>%
  st_sf() %>%
  st_wrap_dateline(options = c("WRAPDATELINE=YES", "DATELINEOFFSET=180"))

land <- rnaturalearth::ne_countries(returnclass = "sf") %>%
  st_union()
ocean <- st_difference(polygon, land)
#> although coordinates are longitude/latitude, st_difference assumes that they are planar

plot(st_geometry(land))
plot(st_geometry(polygon), add = TRUE)
plot(st_geometry(ocean), add = TRUE, col = "blue")

ggplot() +
  theme_bw() +
  borders("world") +
  geom_sf(data = ocean)

reprex package(v0.2.0)创建于2018-03-13。

答案 1 :(得分:2)

如果我正确理解了你想要的东西,可以使用sf和st_union()`使用st_difference()包。

根据您的代码,您可以执行此操作。

# world data
data("wrld_simpl", package = 'maptools')

# load sf package
library('sf')

# coerce sp object to sf
world <- st_as_sf(wrld_simpl)
rectangle <- st_as_sf(spatial.polys)

# difference between world polygons and the rectangle
difference <- st_difference(rectangle, st_union(world))

# coerce back to sp
difference <- as(difference, 'Spatial')

# plot the result
plot(difference)