rrastervis

Overlay continent outlines on levelplot in R


I'm trying to overlap continent outlines on a layerplot, and would like to lable the x and y axes with longitude and latitude values. At the moment I don't get an error but no outlines appear. I am wondering if that is because I'm not defining the lat and lon axes correctly?

library(rgdal)
library(rasterVis)
library(RColorBrewer)
library(ncdf4)
library(maptools)

f<-nc_open("cases5.nc")
cases<-ncvar_get(f,"cholera_cases")

sen<-getData('GADM', country='Senegal', level=1)

colr <- colorRampPalette(brewer.pal(11, 'RdYlBu'))

for (i in seq(1,1)){

name<-sprintf("plot_%03d.png",i)

png(name)
print(name)

p<-levelplot(cases, 
      margin=FALSE,                       # suppress marginal graphics
      colorkey=list(
        space='bottom',                   # plot legend at bottom
        labels=list(at=0:10, font=4)      # legend ticks and labels 
      ),    
      par.settings=list(
        axis.line=list(col='transparent') # suppress axes and legend outline
      ),
      scales=list(draw=FALSE),            # suppress axis labels
      col.regions=colr,                   # colour ramp
      at=seq(0, 10, len=101))
  +layer(sp.polygons(sen, fill="transparent"))

print(p)

dev.off()
}

An example netcdf datafile is available here:

http://clima-dods.ictp.it/Users/tompkins/stackoverflow/cases5.nc


Solution

  • I think you need to pass a RasterLayer object to levelplot:

    library(rgdal)
    library(rasterVis)
    library(RColorBrewer)
    library(ncdf4)
    library(maptools)
    library(raster)
    
    r <- raster("/Users/christopher/Downloads/cases5.nc")
    colr <- colorRampPalette(brewer.pal(11, 'RdYlBu'))
    
    p <- levelplot(
      r,
      margin = FALSE,
      colorkey = list(space = 'bottom',
                      labels = list(at = 0:10, font = 4)),
      par.settings = list(axis.line = list(col = 'black')),
      scales = list(draw = FALSE),
      col.regions = colr,
      at = seq(0, 10, len = 101)
    )
    
    sen <- getData('GADM', country = 'Senegal', level = 1)
    p + layer(sp.polygons(sen))
    

    enter image description here

    If you want to add the longitude and latitude remove scales = list(draw = FALSE) from your code.

    enter image description here