web-dev-qa-db-ja.com

ポイントが複数のポリゴン/穴で構成される空間オブジェクト内にあるかどうかを確認します

クラス「polygons」の11589個のオブジェクトを持つSpatialPolygonsDataFrameがあります。これらのオブジェクトのうち10699は、正確に1つのポリゴンで構成されていますが、残りのオブジェクトは複数のポリゴン(2〜22)で構成されています。

のオブジェクトが複数のポリゴンで構成されている場合、次の3つのシナリオが考えられます。

  1. これらの追加のポリゴンは、クラス「ポリゴン」のオブジェクトの最初のポリゴンによって記述される地理的アラの「穴」を記述する場合があります。
  2. これらの追加のポリゴンは、追加の地理的領域を表す場合があります。つまり、領域の形状は非常に複雑で、複数のパーツを組み合わせて記述されます。
  3. 場合によっては、1)と2)の両方が混在している可能性があります。

Stackoverflowは、このような空間オブジェクトを適切にプロットするのに役立ちました( 複数のポリゴンで定義された空間領域をプロット )。

ただし、ポイント(経度/緯度で定義)がポリゴン内にあるかどうかを判断する方法については、まだ回答できません。

以下は私のコードです。 spパッケージの関数point.in.polygonを適用しようとしましたが、複数のポリゴン/穴で構成されるそのようなオブジェクトを処理する方法が見つかりませんでした。

# Load packages
# ---------------------------------------------------------------------------
library(maptools)
library(rgdal)
library(rgeos)
library(ggplot2)
library(sp) 


# Get data
# ---------------------------------------------------------------------------
# Download shape information from the internet
URL <- "http://www.geodatenzentrum.de/auftrag1/archiv/vektor/vg250_ebenen/2012/vg250_2012-01-01.utm32s.shape.ebenen.Zip"
td <- tempdir()
setwd(td)
temp <- tempfile(fileext = ".Zip")
download.file(URL, temp)
unzip(temp)

# Get shape file
shp <- file.path(tempdir(),"vg250_0101.utm32s.shape.ebenen/vg250_ebenen/vg250_gem.shp")

# Read in shape file
map <- readShapeSpatial(shp, proj4string = CRS("+init=epsg:25832"))

# Transform the geocoding from UTM to Longitude/Latitude
map <- spTransform(map, CRS("+proj=longlat +datum=WGS84"))


# Pick an geographic area which consists of multiple polygons
# ---------------------------------------------------------------------------
# Output a frequency table of areas with N polygons 
nPolys <- sapply(map@polygons, function(x)length(x@Polygons))

# Get geographic area with the most polygons
polygon.with.max.polygons <- which(nPolys==max(nPolys))

# Get shape for the geographic area with the most polygons
Poly.coords <- map[which(nPolys==max(nPolys)),]


# Plot
# ---------------------------------------------------------------------------
# Plot region without Google maps (ggplot2) 
plot(Poly.coords,  col="lightgreen")


# Find if a point is in a polygon 
# ---------------------------------------------------------------------------
# Define points 
points_of_interest <- data.frame(long=c(10.5,10.51,10.15,10.4), 
                     lat =c(51.85,51.72,51.81,51.7),
                     id  =c("A","B","C","D"), stringsAsFactors=F)

# Plot points
points(points_of_interest$long, points_of_interest$lat, pch=19)

enter image description here

17
majom

これは、rgeosパッケージのgContains(...)を使用して簡単に行うことができます。

_gContains(sp1,sp2)
_

sp2がsp1に含まれているかどうかに応じて論理を返します。唯一のニュアンスは、sp2がSpatialPointsオブジェクトである必要があり、sp1と同じ射影を持つ必要があるということです。これを行うには、次のようなことを行います。

_point <- data.frame(lon=10.2, lat=51.7)
sp2   <- SpatialPoints(point,proj4string=CRS(proj4string(sp1)))
gContains(sp1,sp2)
_

これは、前の質問への回答に基づいた実用的な例です。

_library(rgdal)   # for readOGR(...)
library(rgeos)   # for gContains(...)
library(ggplot2)

setwd("< directory with all your files >")
map <- readOGR(dsn=".", layer="vg250_gem", p4s="+init=epsg:25832")
map <- spTransform(map, CRS("+proj=longlat +datum=WGS84"))

nPolys <- sapply(map@polygons, function(x)length(x@Polygons))
region <- map[which(nPolys==max(nPolys)),]

region.df <- fortify(region)
points <- data.frame(long=c(10.5,10.51,10.15,10.4), 
                     lat =c(51.85,51.72,51.81,51.7),
                     id  =c("A","B","C","D"), stringsAsFactors=F)

ggplot(region.df, aes(x=long,y=lat,group=group))+
  geom_polygon(fill="lightgreen")+
  geom_path(colour="grey50")+
  geom_point(data=points,aes(x=long,y=lat,group=NULL, color=id), size=4)+
  coord_fixed()
_

ここで、ポイントAはメインポリゴンにあり、ポイントBは湖(穴)にあり、ポイントCは島にあり、ポイントDは完全に領域の外側にあります。したがって、このコードはgContains(...)を使用してすべてのポイントをチェックします

_sapply(1:4,function(i)
  list(id=points[i,]$id,
       gContains(region,SpatialPoints(points[i,1:2],proj4string=CRS(proj4string(region))))))
#    [,1] [,2]  [,3] [,4] 
# id "A"  "B"   "C"  "D"  
#    TRUE FALSE TRUE FALSE
_
19
jlhoward

「ポリゴンの点」ルーチンを使用できますが、これはRのマルチポリゴンの場合(実際には少し奇妙だと思います)を処理するようにまだ適切に設計されていないため、それぞれを循環する必要があります。複数のポリゴン。ここでの秘訣は、奇数のポリゴンの内部にいる場合、マルチポリゴンの内部にいるということです。偶数のポリゴンの内側にいる場合は、実際には形状の外側にあります。

光線交差を使用するポリゴンテストのポイントは、すべての頂点を元のpoint.in.polygonテストに渡すことを確認するだけで、すでにこれを処理できるはずですが、Rがどのメカニズムを使用しているかわからないので、上記の偶数/奇数のアドバイスのみを提供できます。

私もこのコードを見つけましたが、それが役立つかどうかはわかりません:

require(sp)
require(rgdal)
require(maps)

# read in bear data, and turn it into a SpatialPointsDataFrame
bears <- read.csv("bear-sightings.csv")
coordinates(bears) <- c("longitude", "latitude")

# read in National Parks polygons
parks <- readOGR(".", "10m_us_parks_area")

# tell R that bear coordinates are in the same lat/lon reference system
# as the parks data -- BUT ONLY BECAUSE WE KNOW THIS IS THE CASE!
proj4string(bears) <- proj4string(parks)

# combine is.na() with over() to do the containment test; note that we
# need to "demote" parks to a SpatialPolygons object first
inside.park <- !is.na(over(bears, as(parks, "SpatialPolygons")))

# what fraction of sightings were inside a park?
mean(inside.park)
## [1] 0.1720648

# use 'over' again, this time with parks as a SpatialPolygonsDataFrame
# object, to determine which park (if any) contains each sighting, and
# store the park name as an attribute of the bears data
bears$park <- over(bears, parks)$Unit_Name

# draw a map big enough to encompass all points (but don't actually plot
# the points yet), then add in park boundaries superimposed upon a map
# of the United States
plot(coordinates(bears), type="n")
map("world", region="usa", add=TRUE)
plot(parks, border="green", add=TRUE)
legend("topright", cex=0.85,
    c("Bear in park", "Bear not in park", "Park boundary"),
    pch=c(16, 1, NA), lty=c(NA, NA, 1),
    col=c("red", "grey", "green"), bty="n")
title(expression(paste(italic("Ursus arctos"),
    " sightings with respect to national parks")))

# now plot bear points with separate colors inside and outside of parks
points(bears[!inside.park, ], pch=1, col="gray")
points(bears[inside.park, ], pch=16, col="red")

# write the augmented bears dataset to CSV
write.csv(bears, "bears-by-park.csv", row.names=FALSE)

# ...or create a shapefile from the points
writeOGR(bears, ".", "bears-by-park", driver="ESRI Shapefile")
5
Ted