【问题标题】:Add text out of levelplot panel area在 levelplot 面板区域之外添加文本
【发布时间】:2015-12-16 02:45:17
【问题描述】:

我想在 levelplot 的绘图区域之外添加文本。在下面的示例中,我需要在指定位置的某处放置文本。

library (raster)
library(rasterVis)

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

我尝试了 mtext 函数但没有成功。有什么建议吗?

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

【问题讨论】:

    标签: r plot raster lattice


    【解决方案1】:

    tldr;

    您可以使用较低级别的 grid 图形函数对绘图进行注释。在这种情况下,请执行以下操作:

    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 和其他基于 lattice 的软件包使用 grid 图形系统,而不是 mtext() 所属的基本图形系统.

    在这里,使用 grid,我将如何在视口左上角上方 0.4 行的位置添加文本(一个技术 grid 术语) 在其中打印上边距图。

    • 首先,找到相关视口的名称。

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

      快速扫描grid.ls() 返回的列表会出现一个名为plot_01.legend.top.vp 的视口,这看起来像是一个很有前途的候选者。如果您想检查它是否正确,可以在其周围绘制一个矩形,如下所示(使用视口的完整路径):

      grid.rect(vp = "plot_01.toplevel.vp::plot_01.legend.top.vp",
                gp = gpar(col = "red"))
      
    • 然后,使用 grid 极其灵活的坐标系,将所需的文本放置在该视口左上角的正上方。

      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
      

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多