Search code examples
rlevelplot

How to add box layer using levelplot in R?


I would like to add some boxes with special extent to my plot.

Example

     gh <- raster()
     gh[] <- 1:ncell(gh)
     SP <- spsample(Spatial(bbox=bbox(gh)), 10, type="random")

Then plot them

  levelplot(gh, col.regions = rev(terrain.colors(255)), cuts=254, margin=FALSE) +
  layer(sp.points(SP, col = "red"))

this plots a map with several crosses in it but I need to plot a box with spacial extent:

     extent(gh) = extent(c(xmn=-180,xmx=180,ymn=-90,ymx=90))
      e6 <- extent( 2  , 8 , 45   , 51  )

enter image description here

I wan to add e6 to the plot and put the number2 inside the box.Any hint please


Solution

  • Convert the Extent object into a SpatialPolygons, and extract its centroid with coordinates:

    library("raster")
    library("sp")
    library("rasterVis")
    
    gh <- raster()
    gh[] <- 1:ncell(gh)
    SP <- spsample(Spatial(bbox=bbox(gh)), 10, type="random")
    
    e6 <- extent( 2, 8, 45, 51)
    e6pol <- as(e6, 'SpatialPolygons')
    centroid <- coordinates(e6pol)
    
    levelplot(gh, col.regions = rev(terrain.colors(255)), cuts=254, margin=FALSE) +
        layer({sp.points(SP, col = "red")
               sp.polygons(e6pol)
               panel.text(centroid[,1], centroid[,2], '2')
               })
    

    result