簡體   English   中英

在R中按世界地圖裁剪空間多邊形

[英]Clip spatial polygon by world map in 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創建所需的幾何圖形,然后可以使用基本繪圖方法或具有geom_sfggplot開發版本進行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軟件包 (v0.2.0)創建於2018-03-13。

如果我正確理解了您想要的內容,則可以使用st_difference()和st_union()使用sf包來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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM