2

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
  • do you have to use spplot? Commented Jan 26, 2016 at 8:18
  • No, maybe with ggplot. I have to get something like this google.com/… Commented Jan 26, 2016 at 8:25
  • So just a raster with a polygon overlaid? You don't want to colour the polygons? Commented Jan 26, 2016 at 8:29

3 Answers 3

3

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:

enter image description here

4
  • 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" Commented Jan 26, 2016 at 8:45
  • That sounds like a separate problem - can you make a reproducible example as a new question? Commented Jan 26, 2016 at 8:50
  • Yes, give me a moment. Commented Jan 26, 2016 at 8:52
  • Look, this is the question. Thanks for your help. gis.stackexchange.com/questions/178191/… Commented Jan 26, 2016 at 9:04
1

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

spplot

0

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

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.