Build multiple shp files on a graph using spplot in R

I have 3 shp files representing the house, room and beds of the house respectively. I need to plot them on a graph using R so that they all overlap with each other. I know that in the plot function I can use line to build new lines on top of an existing chart, is there something equivalent in spplot ? Thanks.

+8
r plot ggplot2 gis
source share
2 answers

You can use the sp.layout argument in spplot . Alternatively, you can use ggplot2. Sample example code (untested):

 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 data columns are ggplot2 to graphical scales on a graph. In this case, x is the x-coordinate, y is the y-coordinate, group is a column in the data.frame shp file that indicates which polygon a belongs to, and col is the color of the polygon. The geom_path geometry geom_path , which draws a series of lines based on input. An alternative is to use geom_poly , which also supports polygon padding.

0
source share

Here is one approach using the nifty layer() function from the Extra lattice package:

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

Alternatively, you can achieve the same result with the spplot() sp.layout= . (Specifying first=FALSE ensures that the β€œroof” and β€œdoor” will be displayed after / above the gray square, indicated as spplot() first argument.)

 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))) 
+17
source share

All Articles