Search code examples
rplotrasterlattice

Add text out of levelplot panel area


I want to add text out of plot area in levelplot. In the following example, I need the text in somewhere in the pointed location.

library (raster)
library(rasterVis)

f <- system.file("external/test.grd", package="raster")
r <- raster(f)
levelplot(r) 

I tried mtext function with no success. Any suggestions?

mtext("text", side=3, line=0)

enter image description here


Solution

  • tldr;

    You can annotate the plot using lower-level grid graphical functions. In this case, do something like:

    library(grid)
    seekViewport("plot_01.legend.top.vp")
    grid.text("Hello", x=0, y=unit(1,"npc") + unit(0.4, "lines"), just=c("left", "bottom"),
              gp=gpar(cex=1.6))
    

    rasterVis and other lattice-based packages use the grid graphical system, not the base graphical system of which mtext() is a part.

    Here, using grid, is how I'd go about adding text at a position 0.4 lines above the upper-left corner of the viewport (a technical grid term) in which that upper margin plot is printed.

    • First, find the name of the relevant viewport.

      library(grid)
      levelplot(r)
      grid.ls(viewport=TRUE, grobs=FALSE)  ## Prints out a listing of all viewports in plot
      

      A quick scan of the listing returned by grid.ls() turns up a viewport named plot_01.legend.top.vp, which looks like a promising candidate. If you'd like to check whether it's the correct one, you can plot a rectangle around it with something like the following (which uses the full path to the viewport):

      grid.rect(vp = "plot_01.toplevel.vp::plot_01.legend.top.vp",
                gp = gpar(col = "red"))
      
    • Then, using grid's terrifically flexible coordinate system, place the desired text just above the upper left corner of that viewport.

      ll <- seekViewport("plot_01.legend.top.vp")
      grid.text("Hello", x = 0, y = unit(1,"npc") + unit(0.4, "lines"), 
                just = c("left", "bottom"),
                gp = gpar(cex=1.6))
      upViewport(ll)  ## steps back up to viewport from which seekViewport was called
      

    enter image description here