Rot*_*ail 9 plot r r-maptools rgdal
我试图从形状文件中读取并将多边形与公共标记ID合并.
library(rgdal)
library(maptools)
if (!require(gpclib)) install.packages("gpclib", type="source")
gpclibPermit()
usa <- readOGR(dsn = "./path_to_data/", layer="the_name_of_shape_file")
usaIDs <- usa$segment_ID
isTRUE(gpclibPermitStatus())
usaUnion <- unionSpatialPolygons(usa, usaIDs)
Run Code Online (Sandbox Code Playgroud)
当我尝试绘制合并的多边形时:
for(i in c(1:length(names(usaUnion)))){
print(i)
myPol <- usaUnion@polygons[[i]]@Polygons[[1]]@coords
polygon(myPol, pch = 2, cex = 0.3, col = i)
}
Run Code Online (Sandbox Code Playgroud)
所有合并的段看起来都很好,除了那些在密歇根州周围以非常奇怪的方式发生合并的那些段,这样特定段的结果区域只给出如下的小多边形.
i = 10
usaUnion@polygons[[i]]@Polygons[[1]]@coords
Run Code Online (Sandbox Code Playgroud)
输出:
[,1] [,2]
[1,] -88.62533 48.03317
[2,] -88.90155 47.96025
[3,] -89.02862 47.85066
[4,] -89.13988 47.82408
[5,] -89.19292 47.84461
[6,] -89.20179 47.88386
[7,] -89.15610 47.93923
[8,] -88.49753 48.17380
[9,] -88.62533 48.03317
Run Code Online (Sandbox Code Playgroud)
原来是一个北方小岛:
我怀疑问题是由于某种原因,该unionSpatialPolygons
功能不喜欢地理上分离的多边形[密歇根州的左侧和右侧],但我还没有找到解决方案.
我认为问题不在于unionSpatialPolygons
您的情节.具体来说,您只为每个ID 绘制第一个"子多边形".运行以下命令以验证出现了什么问题:
for(i in 1:length(names(usaUnion))){
print(length(usaUnion@polygons[[i]]@Polygons))
}
Run Code Online (Sandbox Code Playgroud)
对于其中的每一个,您只采用了第一个.
我使用以下代码获得了正确的多边形连接/绘图:
library(rgdal)
library(maptools)
library(plyr)
usa <- readOGR(dsn = "INSERT_YOUR_PATH", layer="light_shape")
# remove NAs
usa <- usa[!is.na(usa$segment_ID), ]
usaIDs <- usa$segment_ID
#get unique colors
set.seed(666)
unique_colors <- sample(grDevices::colors()[grep('gr(a|e)y|white', grDevices::colors(), invert = T)], 15)
colors <- plyr::mapvalues(
usaIDs,
from = as.numeric(sort(as.character(unique(usaIDs)))), #workaround to get correct color order
to = unique_colors
)
plot(usa, col = colors, main = "Original Map")
usaUnion <- unionSpatialPolygons(usa, usaIDs)
plot(usaUnion, col = unique_colors, main = "Joined Polygons")
Run Code Online (Sandbox Code Playgroud)