Add text from the area of ​​the levelplot panel

I want to add text from the graph area to levelplot. In the following example, I need text somewhere in the specified location.

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

I tried the mtext function without success. Any suggestions?

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

enter image description here

+5
source share
1 answer

TL; DR;

You can annotate a graph using the lower-level graphical grid 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 grids using the grid graphics system, not the base graphics system from which mtext() is part.

Here, using the grid , I'm going to add text at the position of 0.4 line above the upper left corner of the viewport (technical grid ).) In which this graph of the top edge is printed.

  • First find the name of the corresponding viewport.

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

    A quick look at the list returned by grid.ls() brings up a window called plot_01.legend.top.vp , which looks like a promising candidate. If you want to check if this is correct, you can build 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 a grid with a terribly flexible coordinate system, place the desired text just above the upper left corner of this 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

+8
source

All Articles