用虚拟图替换 ggplots 列表中的 NA
Replace NAs in a list of ggplots with a dummy plot
我有一个要传递给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)
给出错误:
Error: Only know how to add ggplots and/or 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 实例替换为我的虚拟图?
您可以遍历 plots
并检查元素是否为 identical
到 NA
。如果是这样,请替换为 dummy_plot
plots[sapply(plots, function(x) identical(x, NA))] <- list(dummy_plot)
patchwork::wrap_plots(plots)
# grid.rect(gp = gpar(fill = NA))
结果
我有一个要传递给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)
给出错误:
Error: Only know how to add ggplots and/or 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 实例替换为我的虚拟图?
您可以遍历 plots
并检查元素是否为 identical
到 NA
。如果是这样,请替换为 dummy_plot
plots[sapply(plots, function(x) identical(x, NA))] <- list(dummy_plot)
patchwork::wrap_plots(plots)
# grid.rect(gp = gpar(fill = NA))
结果