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

3

6

I am trying to use levelplot to plot a simple Digital Elevation Model (DEM).

Here is my code:

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)

The plot ends up looking like this:

levelplot

What I cannot figure out is how to increase the space between the colorkey and the x-axis such that the colorkey does not cover the x-axis label.

Lunisolar answered 25/4, 2015 at 19:30 Comment(0)
S
7

Add the following:

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

Test example:

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)

levelplot

Solatium answered 25/4, 2015 at 20:35 Comment(0)
B
2

A quick fix would be to add a new line to your x-label, as follows: xlab="Easting(m)\n". This will add a blank line between the x-label and the legend.

Bream answered 25/4, 2015 at 19:40 Comment(0)
M
2

Another option would be to define grid viewports and insert the colorkey manually using draw.colorkey. Based on the solution suggested by @rcs, the code would then roughly look as follows.

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()

enter image description here

Myelencephalon answered 26/1, 2016 at 8:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.