Arrange odd number of plots using rasterVis and gridExtra

I am trying to plot a panel with seven rasters using the levelplot function of the rasterVis package, combined with gridExtra 's grid.arrange .

I almost get what I need by using the following code:

# load required packages
library(rasterVis)
library(gridExtra)

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

# create plots
p1 <- levelplot(r, xlab=NULL, ylab=NULL, margin=FALSE)
p2 <- levelplot(r*2, xlab=NULL, ylab=NULL, margin=FALSE,colorkey=FALSE)

# put plots in list
p.list <- list(p1,p2,p2,p2,p2,p2,p2)

# create layout
lay <- rbind(c(1,1,1),
             c(2,3,4),
             c(5,6,7))

# arrange plots
grid.arrange(grobs=p.list, layout_matrix=lay)

which yields this figure:

在这里输入图像描述

However, there are some things I still need to improve:

  • How to decrease the blank space between the plots in the bottom rows?
  • How to add a single, combined legend for the six bottom rasters, preferentially put to the bottom of the figure?
  • Is this possible to achieve using rasterVis and gridExtra ? Is there any other approach that can be used?


    The white space is a combination of lattice margin settings, but also the plots having a fixed aspect ratio (they can't be too close unless the device itself has a compatible aspect ratio).

    With regards the legend, you could use draw.colorkey() , but from what I can tell you need to manually ensure that the colours match by passing them explicitly to both plots and the key.

    # load required packages
    library(rasterVis)
    library(gridExtra)
    
    # load sample raster
    f <- system.file("external/test.grd", package="raster")
    r <- raster(f)
    
    my_theme <- rasterTheme(region = blues9)
    
    # create plots
    p1 <- levelplot(r, xlab=NULL, ylab=NULL, margin=FALSE, par.settings = my_theme)
    leg <- p1$legend$right$args$key
    p1$legend <- list()
    p2 <- levelplot(r*2, xlab=NULL, ylab=NULL, margin=FALSE,colorkey=FALSE, par.settings = my_theme)
    
    # put plots in list
    p.list <- list(p1,p2,p2,p2,p2,p2,p2)
    
    # create layout
    lay <- rbind(c(NA,1,NA),
                 c(2,3,4),
                 c(5,6,7),
                 c(8,8,8))
    
    leg$col <- my_theme$regions$col
    legGrob <- draw.colorkey(key = leg, vp = grid::viewport(height=0.5))
    # arrange plots
    grid.arrange(grobs=c(p.list, list(legGrob)), layout_matrix=lay,
                 vp = grid::viewport(width=0.7,height=1))
    

    (needless to say, facetting seems the better option by a wide margin)

    在这里输入图像描述

    链接地址: http://www.djcxy.com/p/68932.html

    上一篇: 在IPython中重新加载子模块

    下一篇: 使用rasterVis和gridExtra排列奇数个图