r - 在循环中将基本图形转换为等效的网格

标签 r loops plot

使用带有 gridGraphics 包 ( here ) 的解决方案将基本图一个一个地转换为它们的等效网格,没有任何问题。但是,当我尝试将其放入循环中时,我没有得到预期的结果。这是一个例子:

library(gridGraphics) 

### Make a list of 3 base plots -----
p <- vector(mode = "list", length = 3)

for (i in 1:3){
  plot(1:5^i)
  p[[i]] <- recordPlot()
}

### Attempt to convert each base plot to its grid equivalent -----
grobs <- vector(mode = "list", length = 3)

for (i in 1:3){
  plot.new() # clean up device
  p[[i]] # redraw
  # Echo graphics output using grid graphics
  grid.echo()
  # Creates a gTree object from the current grid display list
  a_gTree <- grid.grab()
  grobs[[i]] <- editGrob(grob = a_gTree, 
                         vp = viewport(width = unit(5, "cm"),
                                       height = unit(5, "cm"),
                                       angle = 90)) # rotates 90 dg
}

如果我在循环中为每个步骤运行代码块,我会得到我需要的东西,但是当我一次运行循环时,所有的 grobs 似乎什么都不显示。我觉得我缺少了一些明显的东西......

这是一个期望的输出(通过逐步运行获得):

cowplot::plot_grid(grobs[[1]], 
                   grobs[[2]], 
                   grobs[[3]])

enter image description here

最佳答案

感谢@user20650 指出 print() 的用法在循环中,所以使用 print(p[[i]])而不是 p[[i]] .或者更好的是,我更喜欢他的优雅建议,即使用 a_gTree <- grid.grabExpr(grid.echo(p[[i]])) 来节省一些行.在哪里grid.grabExpr捕获表达式的输出而不绘制任何内容。还有 plot.new()似乎是可选的。

for (i in 1:3){
  # Grab grid output
  a_gTree <- grid.grabExpr(grid.echo(p[[i]]))
  # Edit/modify the grob
  grobs[[i]] <- editGrob(grob = a_gTree, 
                         vp = viewport(width = unit(5, "cm"),
                                       height = unit(5, "cm"),
                                       angle = 90)) # rotates 90 dg
}

关于r - 在循环中将基本图形转换为等效的网格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49982582/

相关文章:

java - 需要帮助在 java 中循环我的 try 和 catch 语句

python - iPython notebook - 在子图次要 y 轴上设置 ylim

matlab - 如何在matlab中添加条形图的三个图例?

r - 如何删除基于两列的所有重复行?

r - k表示聚类结果存储以备后用

r - ggplot中的分层轴?

r - 从数据框中子集特定行和最后一行

java - 将列表从 Java 返回到 Freemarker

arrays - 我有舍入错误吗? Perl

python - 如何在 Pandas 中的 "day period"上覆盖数据以进行绘图