R Notebook代码先输出空白图,如何消除该问题?
解决RStudio Notebook中生成中间空白图的问题
问题根源
sapply在处理ggplot对象时,会自动打印每个迭代生成的绘图对象,导致Notebook中出现多余的空白图。而purrr::map(或lapply)不会触发自动打印,能直接将所有绘图对象收集到列表中。
解决方法
将代码中的sapply替换为purrr::map,修改后的完整代码如下:
library(tidyverse) library(fable) myfit <- tsibbledata::global_economy |> filter(Code %in% c("CAF", "AUT")) %>% model(arima = ARIMA(Exports)) # 用purrr::map替代sapply,避免自动打印中间图 plot_list <- purrr::map(1:2, function(x) { myfit %>% slice(x) %>% feasts::gg_tsresiduals() + labs(title = x) }) gridExtra::grid.arrange(grobs = plot_list, layout_matrix = rbind(c(1,1), c(2,3), c(4,4), c(5,6)))
补充说明
如果不想引入purrr包,也可以用lapply替代sapply,效果相同:
plot_list <- lapply(1:2, function(x) { myfit %>% slice(x) %>% feasts::gg_tsresiduals() + labs(title = x) })
内容的提问来源于stack exchange,提问作者Mangiafoco
相关产品推荐
相关产品推荐

