2

我有一个我想传递给 patchwork::wrap_plots 的地块列表:

library(tidyverse)
library(patchwork)

# plots with na
dummy_plot <- ggplot() + theme_void()
p <- ggplot(mtcars, aes(mpg, cyl)) + geom_point()
plots <- list(p, p, NA)
patchwork::wrap_plots(plots)

给出错误:

错误:只知道如何添加 ggplots 和/或 grobs

因此,我想预处理我的图列表,用上面的空白虚拟图替换任何 NA。

期望的结果:

plots <- list(p, p, NA)
... some magic r code here to replace NA with dummy plot ...
# now plots looks like this    
plots <- list(p, p, dummy_plot)

我现在可以毫无错误地通过包装图: 在此处输入图像描述

如何将列表中的 NA 实例替换为我的虚拟图?

4

1 回答 1

2

您可以循环plots并检查元素是否identicalNA. 如果是这样,请替换为dummy_plot

plots[sapply(plots, function(x) identical(x, NA))] <- list(dummy_plot)
patchwork::wrap_plots(plots)
# grid.rect(gp = gpar(fill = NA))

结果

在此处输入图像描述

于 2021-04-14T20:31:58.863 回答