Does anybody know how to plot with "spplot" fuction two elements of diferents classes?. One element from "SpatialPolygonDataFrame" class and other from "raster" class.
3 Answers
You can do this quite easily with base graphics, I don't see a real need for spplot or ggplot:
Sample data: Spain and a random raster:
require(raster)
es = getData("GADM", country="ESP",level=1)
es =es[-14,] # drop canary islands
r = raster(extent(es),ncol=200,nrow=200)
r[]=runif(200*200)
Plot the raster and add the polygons - the alternative clips the raster to the Spanish polygons using the mask function:
plot(r) # or try: plot(mask(r,es))
plot(es, add=TRUE)
Here's the clipped version:
-
Thanks! But the problem is when I try to plot a SpatialPolygonDataFrame element with raster or SpatialGridDataFrame. I always get an error like this: "Error in
[[<-.data.frame(*tmp*, i, value = c(52.6195687909829, 52.6845097109409, : replacement has 64 rows, data has 672"Camilo Andres– Camilo Andres2016-01-26 08:45:37 +00:00Commented Jan 26, 2016 at 8:45 -
That sounds like a separate problem - can you make a reproducible example as a new question?Spacedman– Spacedman2016-01-26 08:50:31 +00:00Commented Jan 26, 2016 at 8:50
-
Yes, give me a moment.Camilo Andres– Camilo Andres2016-01-26 08:52:06 +00:00Commented Jan 26, 2016 at 8:52
-
Look, this is the question. Thanks for your help. gis.stackexchange.com/questions/178191/…Camilo Andres– Camilo Andres2016-01-26 09:04:38 +00:00Commented Jan 26, 2016 at 9:04
If you want to stick with spplot, you could e.g. use layer from latticeExtra to add 'Spatial*' objects to an existing plot. Based on the code provided by @Spacedman, this would look as follows.
## load package
library(latticeExtra)
## plot raster and add polygons
spplot(r, scales = list(draw = TRUE),
col.regions = terrain.colors(100), at = seq(0, 1, .01)) +
layer(sp.polygons(es, lwd = 2))
Using only ssplot with sp.layout, without latticeExtra gives the same result:
## Define how the polygon should appear
borders <- list("sp.polygons", es, fill = "transparent", col = 'black', first = FALSE)
## plot both raster and polygon
spplot(r,
sp.layout = borders,
col.regions = terrain.colors(100), at = seq(0, 1, .01),
scales = list(draw = TRUE))



spplot?