在R中通过世界贴图裁剪空间多边形 [英] Clip spatial polygon by world map in R

查看:0
本文介绍了在R中通过世界贴图裁剪空间多边形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我第一次在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)

推荐答案

这里是一个始终停留在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。

这篇关于在R中通过世界贴图裁剪空间多边形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆