[R-sig-Geo] Include multiple SpatialPolygons objects in legend of spplot

Matt Strimas-Mackey strimas at zoology.ubc.ca
Tue Mar 31 22:28:39 CEST 2015


Hi,

I have two shapefiles: one with polygons of plantations and another
with polygons of protected areas. There are multiple types of
plantations and multiple types of parks. I am able to plot both of
these shapefiles on one map with spplot by including the second SPDF
object in the sp.layout parameter of spplot. The legend looks great
for the first SPDF object, but the polygons passed to sp.layout are
not included in the legend. Is there some way to do this, i.e. have a
legend that accounts for multiple spatial objects? I know I could
union them together, but I'd like to avoid this workaround if
possible.

In addition, is there a way to alter the legend labels for a
categorical legend? I know how to do this using the colorkey parameter
with continuous legends, but can't figure out how to apply this to
factor variables. For example, if my attributes are codes like 'NP'
and 'SP', could I instead label the legend 'National Park' and 'State
Park'.

Simplified example below. Thanks!

library(sp)
library(raster)
# Make some fake data
# 2 SPDF objects each with one factor attribute
# Plantations
plantation <- union(union(as(extent(0, 0.5, 1, 1.5), 'SpatialPolygons'),
             as(extent(2.5, 3, 0, 1), 'SpatialPolygons')),
             as(extent(1, 1.5, 1, 2), 'SpatialPolygons'))
plantation <- SpatialPolygonsDataFrame(plantation,
                        data.frame(field=c('Timber','Rubber',
'Acacia')), match.ID=F)

# Protected Areas
protected <- union(as(extent(0, 1, 0, 1), 'SpatialPolygons'),
             as(extent(1.5, 2, 0.5, 2), 'SpatialPolygons'))
protected <- SpatialPolygonsDataFrame(protected,
                        data.frame(field=c('NP','SP')), match.ID=F)

# Plot
l <- list('sp.polygons', protected, col='transparent', fill='green')
spplot(plantation, sp.layout=l, scales=list(draw=T))
# I want to add the protected areas to the legend



More information about the R-sig-Geo mailing list