levelplot:如何在 colorkey 和 x 轴标签之间添加 space

levelplot: how to add space between colorkey and x-axis label

我正在尝试使用 levelplot 绘制一个简单的数字高程模型 (DEM)。

这是我的代码:

r1 = raster("ned10dem.tif")
e = extent(460000,480000,4555000,4567500)
rr1 = crop(r1,e)
p = levelplot(rr1, scales=list(x=list(at=seq(450000,480000,4000))),
              margin=F, cuts=200,
              col.regions = terrain.colors(350,alpha=1), 
              colorkey=list(space="bottom"),
              xlab="Easting(m)", ylab="Northing(m)")
plot(p)

情节最终看起来像这样:

我想不通的是如何增加 colorkey 和 x 轴之间的 space,使 colorkey 不覆盖 x 轴标签。

一个快速解决方法是在您的 x-label 中添加一个新行,如下所示:xlab="Easting(m)\n"。这将在 x 标签和图例之间添加一个空行。

添加以下内容:

par.settings = list(layout.heights=list(xlab.key.padding=1))

测试示例:

x <- seq(pi/4, 5*pi, length.out=100)
y <- seq(pi/4, 5*pi, length.out=100)
r <- as.vector(sqrt(outer(x^2, y^2, "+")))
grid <- expand.grid(x=x, y=y)
grid$z <- cos(r^2) * exp(-r/(pi^3))
p <- levelplot(z~x+y, data=grid,
               margin=F, cuts=200,
               par.settings=list(layout.heights=list(xlab.key.padding=1)),
               col.regions=terrain.colors(350, alpha=1), 
               colorkey=list(space="bottom"),
               xlab="Easting(m)", ylab="Northing(m)")
print(p)

另一种选择是定义 网格 视口并使用 draw.colorkey 手动插入色键。根据 @rcs 建议的解决方案,代码大致如下所示。

library(grid)

## breaks and colors
at <- seq(-1.1, 1.1, .01)
cols <- terrain.colors(350)

## create plot
p <- levelplot(z ~ x + y, data = grid, at = at,
               col.regions = cols, colorkey = FALSE,
               xlab = list("Easting (m)", cex = .8), 
               ylab = list("Northing (m)", cex = .8))

## start png device
png("~/plot.png", width = 8, height = 9, units = "cm", res = 150)

## insert plot
grid.newpage()
vp_fig <- viewport(x = 0, y = .1, width = 1, height = .9, 
                   just = c("left", "bottom"))
pushViewport(vp_fig)
print(p, newpage = FALSE)

## insert colorkey
downViewport(trellis.vpname("figure"))
vp_key <- viewport(x = .5, y = -.4)
pushViewport(vp_key)
draw.colorkey(key = list(col = cols, at = at, width = .6, height = .6, 
                         space = "bottom"), draw = TRUE)
dev.off()