When plotting a mixture of continuous and factor rasters with rasterVis::levelplot
using print(..., more=TRUE)
, the height and width of the panels is inconsistent. This seems to be due to differences in the width of the colorkey (legend), and the colorkey's tick labels.
For example:
library(raster)
library(rasterVis)
r1 <- raster(matrix(runif(100), 10))
r2 <- as.factor(raster(matrix(rbinom(100, 1, 0.8), 10)))
levels(r2)[[1]]$name <- c('gray', 'lightblue')
p1 <- levelplot(r1, margin=FALSE, scales=list(draw=FALSE),
at=seq(0, 1, length.out=100))
p2 <- levelplot(r2, scales=list(draw=FALSE),
col.regions=c('gray90', 'lightblue'))
print(p1, split=c(1, 1, 1, 2), more=TRUE)
print(p2, split=c(1, 2, 1, 2))
Is there a way to modify the trellis graphical parameters (e.g., layout widths/heights?) to achieve consistently sized plots, such that it looks more like the layout used when plotting a RasterStack?
Or is there an alternative way of combining these rasters, which would scale to layouts with multiple columns as well as multiple rows? (Other plotting frameworks are fine, but base plot doesn't readily support factor rasters.)
You can use ?c.trellis
function from the latticeExtra
package.
library(latticeExtra)
c(p1, p2, layout = c(1, 2), merge.legends = TRUE)
However, in your case the legend overlaps slightly. If the order of the plots is not relevant you can instead use
c(p2, p1, layout = c(1, 2), merge.legends = TRUE)
Alternatively you can add some space to your first plot as follows.
p1 <- levelplot(r1, margin=FALSE, scales=list(draw=FALSE),
at=seq(0, 1, length.out=100),
par.settings = rasterTheme(layout.widths = list(key.right = 1.5)))
c(p1, p2, layout = c(1, 2), merge.legends = TRUE)