2013-03-04 83 views
0

我想合併gadm數據中的一些區域,然後繪製地圖。到目前爲止,我有以下幾點:使用spplot合併多邊形和繪圖()

#install.packages("sp",dependencies=TRUE) 
#install.packages("RColorBrewer",dependencies=TRUE) 
#install.packages("maptools",dependencies=TRUE) 
library(sp) 
library(maptools) 
#library(RColorBrewer) 

# get spatial data 
con <- url("http://gadm.org/data/rda/CZE_adm2.RData") 
print(load(con)) 
close(con) 

IDs <- gadm$ID_2 
IDs[IDs %in% c(11500:11521)] <- "11500" 
gadm_new <- unionSpatialPolygons(gadm, IDs) 

# plot map 
spplot(gadm_new, "NAME_2", col.regions=col, main="Test",colorkey = FALSE, lwd=.4, col="white") 

然而這會導致錯誤:

Error in function (classes, fdef, mtable) : 
    unable to find an inherited method for function "spplot", for signature "SpatialPolygons" 

現在我不知道該怎麼都不可能解決這個錯誤。

回答

2

我不確定你要在這裏做什麼。

錯誤是由於使用spplot來繪製具有屬性的空間對象(即關聯數據)的事實。您的gadm對象屬於類SpatialPolygonsDataFrame,因此它定義了可通過插槽[email protected]訪問的多邊形和關聯數據。當您使用UnionSpatialPolygons,你只能得到一個SpatialPolygons類對象,它可以與plot繪製,但不能與spplot

IDs <- gadm$ID_2 
IDs[IDs %in% c(11500:11521)] <- "11500" 
gadm_new <- unionSpatialPolygons(gadm, IDs) 
plot(gadm_new) 

如果你想使用spplot,你要合併的相關數據手動,就像合併你的多邊形一樣,然後建立一個SpatialPolygonsDataFrame。做到這一點的方法之一是:

gadm_new <- gadm 
## Change IDs 
gadm_new$ID_2[gadm_new$ID_2 %in% c(11500:11521)] <- "11500" 
## Merge Polygons 
gadm_new.sp <- unionSpatialPolygons(gadm_new, gadm_new$ID_2) 
## Merge data 
gadm_new.data <- unique([email protected][,c("ID_2", "ENGTYPE_2")]) 
## Rownames of the associated data frame must be the same as polygons IDs 
rownames(gadm_new.data) <- gadm_new.data$ID_2 
## Build the new SpatialPolygonsDataFrame 
gadm_new <- SpatialPolygonsDataFrame(gadm_new.sp, gadm_new.data) 

然後你可以使用spplot繪製的地圖與相關屬性:

spplot(gadm_new, "ENGTYPE_2", main="Test", lwd=.4, col="white") 

請注意,這裏我只用了ENGTYPE_2您的數據變量,而不是NAME_2變量,因爲我沒有看到表示變量的點,其中每個值似乎對每個多邊形都是唯一的。

+0

謝謝,這是我第一次嘗試使用R來達到這個目的,而且你的答案真的很棒! – 2013-03-04 13:29:21