将n ggplots排列成下三角矩阵形状

Tyl*_*ker 11 r ggplot2

我有n个ggplot对象,它们总是有正确的数字来制作一个矩阵的下三角形(没有对角线).我该如何按此顺序排列:

1
2 3
4 5 6
7 8 9 10
Run Code Online (Sandbox Code Playgroud)

形成一个网格(这里n = 10)?

这是制作n个图的数据,以及我如何看待我的n = 6.

n <- sample(1:4, 1)
N <- sum(n:1)

library(ggplot2)
theplot <- ggplot(mtcars, aes(mpg, hp)) + geom_point()
plots <- lapply(1:N, function(i) theplot)
plots <- mapply(function(x, y) x + ggtitle(y), plots, 
    paste("PLOT", seq_along(plots)), SIMPLIFY=FALSE)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

我怀疑gridExtra这里可能有用,但有空白窗格.我愿意接受基础或增加包装的想法.

bap*_*ste 12

您可以将矩阵布局传递给grid.arrange,

library(ggplot2)
library(gridExtra)
plots <- lapply(1:10, function(id) ggplot() + ggtitle(id))

m <- matrix(NA, 4, 4)
m[lower.tri(m, diag = T)] <- 1:10
grid.arrange(grobs = plots, layout_matrix = m)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


Jos*_*ien 9

这是一个相当轻松的方法,不应该太难概括:

library(gridExtra) ## for grid.arrange()
ng <- nullGrob()
grid.arrange(plots[[1]], ng,         ng,
             plots[[2]], plots[[3]], ng,
             plots[[4]], plots[[5]], plots[[6]])
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


Gre*_*gor 7

wq::layOutgrid.arrange看起来太复杂时,我是安排ggplots 的粉丝(虽然Josh表明它在这里工作得很好).如果您使用新设备,则无需担心漏洞.

layOut已从wq包中删除,因此我在此处包含代码,重命名为lay_out.在使用示例之后,它位于底部.

lay_out(list(plots[[1]], 1, 1), # each arg is list(plot, row(s), column(s))
       list(plots[[2]], 2, 1),
       list(plots[[3]], 2, 2))
Run Code Online (Sandbox Code Playgroud)

布局1

它的主要优势在于你有不同大小的地块.

lay_out(list(plots[[1]], 1, 1:3), 
        list(plots[[2]], 2, 1),
        list(plots[[3]], 2, 2),
        list(plots[[4]], 3, 1:2),
        list(plots[[5]], 2:3, 3))
Run Code Online (Sandbox Code Playgroud)

布局2

我认为你可以做的任何事情layOut都可以通过嵌套grid.arrangearrangeGrob调用完成,但通常更容易思考这种方式.

#' Arranging ggplots
#' 
#' Provides a \code{layout}-like interface for arranging ggplots of different 
#' sizes.
#' 
#' @param ... Each argument should be of the form \code{list(plot, rows, 
#' columns)}, where \code{plot} is a ggplot (or similar), and \code{rows} and 
#' \code{columns} are consecutive sequences indicating the row and column 
#' numbers for \code{plot} to span.
#' 
#' @author Alan D. Jassby and James E. Cloern (originally from the \code{wq} 
#' package).
#' 
#' @examples
#' \dontrun{
#' gg <- ggplot(mtcars, aes(x = hp, y = mpg)) + geom_point()
#' layOut(list(gg, 1:2, 1:3),
#'        list(gg, 3, 1:2),
#'        list(gg, 3, 3))
#' }
#' 
#' @export
lay_out <- function(...) {

    x <- list(...)
    n <- max(sapply(x, function(x) max(x[[2]])))
    p <- max(sapply(x, function(x) max(x[[3]])))
    grid::pushViewport(grid::viewport(layout = grid::grid.layout(n, p)))    

    for (i in seq_len(length(x))) {
        print(x[[i]][[1]],
              vp = grid::viewport(layout.pos.row = x[[i]][[2]], 
                                  layout.pos.col = x[[i]][[3]]))
    }
}
Run Code Online (Sandbox Code Playgroud)