R 从单元测试的“cowplot”中的组合图中提取单个图的详细信息

R 从单元测试的“cowplot”中的组合图中提取单个图的详细信息,r,ggplot2,testthat,cowplot,R,Ggplot2,Testthat,Cowplot,我正在尝试为使用cowplot::plot_grid()组合ggplot2绘图的函数编写单元测试。比如说, #设置 种子集(123) 图书馆(GG2) #创建基本图 p1我们可以这样做: p <- cowplot::plot_grid(p1, p2, labels = c("(i)", "(ii)")) fun <- function(p, what) { unlist(sapply(p$layers, function(x) { idx <- which(x$g

我正在尝试为使用
cowplot::plot_grid()
组合
ggplot2
绘图的函数编写单元测试。比如说,

#设置
种子集(123)
图书馆(GG2)
#创建基本图
p1我们可以这样做:

p <- cowplot::plot_grid(p1, p2, labels = c("(i)", "(ii)"))

fun <- function(p, what) {
  unlist(sapply(p$layers, function(x) {
    idx <- which(x$geom_params$grob$layout$name == what)
    x$geom_params$grob$grobs[[idx]]$children[[1]]$label
  }))
}
fun(p, "title")
# [1] "Dataset: mtcars" "Dataset: msleep"
fun(p, "subtitle")
# [1] "Source: `base` package"    "Source: `ggplot2` package"
然后根据其
名称选择正确的
grob
,然后查看,比如

str(p$layers[[1]]$geom_params$grob$grobs[[15]])
在那里很容易找到我们想要的

p$layers[[1]]$geom_params$grob$grobs[[15]]$children[[1]]$label
# [1] "Source: `base` package"

@毕竟,我怀疑能做得再短些。我添加了更多关于如何提取其他元素的细节。
p$layers[[1]]$geom_params$grob$grobs[[15]]$children[[1]]$label
# [1] "Source: `base` package"