2012-04-04 10 views
8

Ho 3 file shp che rappresentano rispettivamente la casa, la stanza e i letti di una casa. Ho bisogno di tracciarli su un grafico usando R in modo che si sovrappongano l'uno con l'altro. So che nella funzione plot, posso usare line per tracciare nuove righe sulla trama esistente, c'è qualcosa di equivalente in spplot? Grazie.traccia un file shp multiplo su un grafico utilizzando spplot in R

+0

Quale aspetto di spplot non è possibile fare con il diagramma di base di cui hai bisogno? Con gli oggetti sp basta tracciare il primo, quindi tracciare con add = TRUE per sovrapporre gli altri. Perché portare spplot nel mix? – Spacedman

risposta

0

È possibile utilizzare l'argomento sp.layout in spplot. In alternativa, puoi utilizzare ggplot2. Qualche esempio di codice (non testato):

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() 

In ggplot2, colonne nei dati sono legati a scale grafiche nella trama. In questo caso x è la coordinata x, è la coordinata y, group è una colonna nello shp data.frame che specifica a quale poligono un punto appartiene e col è il colore del poligono. La geometria che ho usato è geom_path, che disegna una serie di linee basate sull'ingresso poligono data.frame. Un'alternativa è usare geom_poly, che supporta anche il riempimento del poligono.

17

Ecco un approccio, utilizzando la funzione nifty layer() dal pacchetto 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

In alternativa, è possibile ottenere lo stesso risultato tramite sp.layout= argomento spplot() s'. (Specificando first=FALSE assicura che il 'tetto' e 'porta' vengono stampati dopo/sopra il quadrato grigio data come primo argomento spplot() s'.)

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)))