【问题标题】:Sequential plotting of ggplots similar to par(mfrow = ...)?ggplots 的顺序绘图类似于 par(mfrow = ...)?
【发布时间】:2017-07-17 06:57:29
【问题描述】:

有没有办法以交互方式和顺序将更多 ggplots 添加到绘图窗口,类似于在 base 中您可以使用 par(mfrow = ...) 添加更多绘图。例如。 (for循环模拟顺序输入的绘图命令):

par(mfrow = c(4, 1))

for (i in 1:4) {
    plot(tmp_df$x, tmp_df$y)
}

依次生成下图的第一行到最后一行:

而对ggplot 执行相同操作只会在绘图窗口中打印一个绘图:

par(mfrow = c(4, 1))

for (i in 1:4) {
    plot(ggplot(tmp_df, aes(x, y)) +
        geom_point())

}

我已经知道如何使用gridExtra::grid.arrange来排列ggplots的列表,例如:

tmp_list <- list()
for (i in 1:4) {
    tmp_list[[length(tmp_list) + 1]] <-
        ggplot(tmp_df, aes(x, y)) +
        geom_point()

}

gridExtra::grid.arrange(grobs = tmp_list, nrow = 4)

【问题讨论】:

    标签: r plot ggplot2


    【解决方案1】:

    您当然可以一次添加一个绘图,例如通过制作网格布局并在特定视口中顺序绘制,

    library(grid)
    library(ggplot2)
    
    gl <- replicate(4, ggplot(), F)
    
    par <- function(mfrow = c(2,2)) pushViewport(viewport(layout = grid.layout(mfrow[1], mfrow[2])))
    print.gg <- function(x) {
      rc <- which(matrix(1:4, 2, 2) == ii, arr.ind = TRUE)
      ggplot2:::print.ggplot(x, vp=viewport(layout.pos.row = rc[1,1], layout.pos.col = rc[1,2]))
      ii <<- (ii+1)%%4
    }
    
    grid.newpage()
    par()
    for(ii in seq_along(gl))
      print(gl[[ii]])
    

    【讨论】:

    • 网格图形的一个核心概念是图形对象 (grobs) 不应该假定它们拥有整个设备,而是尝试在单独的视口中与其他元素一起玩得很好。从这个意义上说,将 ggplot 放置在分割布局中并不那么简单,因为网格视口比基本布局更通用,因此需要更详细的参数。
    【解决方案2】:

    这是一个带有 gtable 布局的版本,用于跟踪占用的单元格,

    library(grid)
    library(ggplot2)
    library(gtable)
    
    
    par <- function(mfrow=c(2,2)) {
      nr <- mfrow[1]; nc <- mfrow[2]
      .g_layout <<- gtable(widths = unit(rep(1/nc, nc), "npc"), heights = unit(rep(1/nr, nr), "npc"))
    }
    
    print.gg <- function(x) {
      ntot <- prod(dim(.g_layout))
      ii <- (length(.g_layout) + 1) %% (ntot+1)
      rc <- which(matrix(seq_len(ntot), nrow = nrow(.g_layout), ncol = ncol(.g_layout)) == ii, arr.ind = TRUE)
      .g_layout <<- gtable::gtable_add_grob(.g_layout, ggplotGrob(x), t = rc[1,1], l = rc[1,2])
      grid.newpage()
      grid.draw(.g_layout)
    }
    
    
    gl <- replicate(4, ggplot(), F)
    
    par()
    for(ii in seq_along(gl))
      print(gl[[ii]])
    

    【讨论】:

    • 这些会覆盖基础par中的功能吗?
    • 是的,使用不同的名称可能是个好主意。 rm(par); rm(print.gg) 将从您的会话中安全地删除它们。
    猜你喜欢
    • 1970-01-01
    • 2020-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多