2012-04-04 30 views
8

我有3個shp文件分別代表房子,房間和房子的牀位。我需要使用R將它們繪製在圖上,以便它們都相互重疊。我知道在plot函數中,我可以使用line在現有圖上繪製新的線條,是否有任何相當於spplot的東西?謝謝。在R中使用spplot繪製多個shp文件

+0

你需要什麼方面的基本情節你不能做的spplot?使用sp對象只需繪製第一個對象,然後使用add = TRUE來疊加其他對象。爲什麼要將混合物帶入混合物? – Spacedman 2012-04-04 06:55:50

回答

0

可以使用sp.layout論點spplot。或者,您可以使用ggplot2。一些示例代碼(未測試):

library(ggplot2) 
shp1_data.frame = fortify(shp1) 
shp1_data.frame$id = "shp1" 
shp2_data.frame = fortify(shp2) 
shp2_data.frame$id = "shp2" 
shp = rbind(shp1_data.frame, shp2_data.frame) 

ggplot(aes(x = x, y = y, group = group, col = id), data = shp) + geom_path() 

ggplot2,在數據列被連接到在圖中的圖形尺度。在這種情況下,x是x座標,y是y座標,group是data.frame shp中指定點屬於哪個多邊形的列,col是多邊形的顏色。我使用的幾何是geom_path,它根據多邊形輸入data.frame繪製一系列線條。另一種方法是使用geom_poly,它也支持填充多邊形。

17

這裏有一個方法,用漂亮的layer()函數從latticeExtra包:

# (1) Load required libraries 
library(sp) 
library(rgeos)  # For its readWKT() function 
library(latticeExtra) # For layer() 

# (2) Prepare some example data 
sp1 = readWKT("POLYGON((0 0,1 0,1 1,0 1,0 0))") 
sp2 = readWKT("POLYGON((0 1,0.5 1.5,1 1,0 1))") 
sp3 = readWKT("POLYGON((0.5 0,0.5 0.5,0.75 0.5,0.75 0, 0.5 0))") 

# spplot provides "Plot methods for spatial data with attributes", 
# so at least the first object plotted needs a (dummy) data.frame attached to it. 
spdf1 <- SpatialPolygonsDataFrame(sp1, data=data.frame(1), match.ID=1) 

# (3) Plot several layers in a single panel 
spplot(spdf1, xlim=c(-0.5, 2), ylim=c(-0.5, 2), 
     col.regions="grey90", colorkey=FALSE) + 
layer(sp.polygons(sp2, fill="saddlebrown")) + 
layer(sp.polygons(sp3, fill="yellow")) 

enter image description here

或者,您可以通過實現spplot()sp.layout=參數相同的結果。 (指定first=FALSE確保了「屋頂」和「門」將被標繪後/給出爲spplot()的第一個參數的灰色方塊的上方。)

spplot(spdf1, xlim=c(-0.5, 2), ylim=c(-0.5, 2), 
     col.regions="grey90", colorkey=FALSE, 
     sp.layout = list(list(sp2, fill="saddlebrown", first=FALSE), 
         list(sp3, fill="yellow", first=FALSE)))