0

I have a shapefile with various attributes. I want to plot the shapefile using `spplot'.

I first read the shapefile

A <- readOGR('myshapefile.shp') 

I am using the following command:

p <- spplot(A, c('lulc', 'lulc_2', 'lulc_3', 
             'lulc_4', 'lulc_5', 'lulc_6', 'lulc_7'), 
        col.regions=myColors, 
        col='transparent', 
        names.attr = c(1998, 1999, 2002, 2003, 2009, 2014, 2017))

enter image description here

Each of the fields / attributes contains 4 values, say 1, 2, 3, 4 and correspondingly need to be labelled A, B, C, D in the legend, along with the color key. How to achieve this? For example, I have put the image of the legend only.

Small update:

I tried to modify the spplot command to:

p <- spplot(A, c('lulc', 'lulc_2', 'lulc_3', 
             'lulc_4', 'lulc_5', 'lulc_6', 'lulc_7'), 
        col.regions=myColors, 
        col='transparent', 
        names.attr = c(1998, 1999, 2002, 2003, 2009, 2014, 2017),
        as.table = T,
        colorkey = list(
          right = list( # see ?levelplot in package trellis, argument colorkey:
            fun = draw.colorkey, 
            args = list(
              key = list(
                at = c(1,2,3,4), # colour breaks
                col = myColors, # colours
                labels = list(
                  at = c(1,2,3,4), 
                  labels = c('A', 'B', 'C', 'D')
                )
              )
            )
          )
        ))

Even then this is not working.

(see https://www.rdocumentation.org/packages/sp/versions/1.3-1/topics/spplot)

  • Your code is not reproducible, can you add the output of spplot()? – rcs Nov 14 '18 at 8:44
0

I waited for long for an answer to the question I posted. I concluded that perhaps it is a bad idea to use spplot for this work. The base plot package in R does the work, but is too lengthy.

myColors <- c('blue', 'green', 'yellow', 'red') 
par(mfrow=c(3,3),mar=c(1,1,3,1))
theColors <- myColors[A$lulc]
plot(A, col = theColors, border = NA,main='1998')
theColors <- myColors[A$lulc_2]
plot(A, col = theColors, border = NA,main='1999')
theColors <- myColors[A$lulc_3]
plot(A, col = theColors, border = NA,main='2002')
theColors <- myColors[A$lulc_4]
plot(A, col = theColors, border = NA,main='2003')
theColors <- myColors[A$lulc_5]
plot(A, col = theColors, border = NA,main='2009')
theColors <- myColors[A$lulc_6]
plot(A, col = theColors, border = NA,main='2014')
theColors <- myColors[A$lulc_7]
plot(A, col = theColors, border = NA,main='2017')
plot.new() 
par(xpd=T)
legend('center',inset = 0,
       legend = c('A', 'B', 'C', 'D'), 
       fill=myColors, cex=2, horiz = F)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.