使用带有 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]])
最佳答案
感谢@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/