带有purrr::walk的嵌套循环留下空的绘图
以下代码生成一个绘图网格:带有purrr::walk的嵌套循环留下空的绘图,r,purrr,R,Purrr,以下代码生成一个绘图网格: library(tidyverse) library(grid) library(patchwork) exdata <- diamonds %>% group_by(cut) %>% nest %>% crossing(dummy = 1:3) %>% crossing(cohort = LETTERS[1:3]) %>% mutate(plots = map(.x = data, ~ ggplot
library(tidyverse)
library(grid)
library(patchwork)
exdata <- diamonds %>%
group_by(cut) %>%
nest %>%
crossing(dummy = 1:3) %>%
crossing(cohort = LETTERS[1:3]) %>%
mutate(plots = map(.x = data, ~ ggplot(.x, aes(x = x, y = y)) + geom_point()))
# vars for plot grid
mod <- 'Fair'
colsn <- length(unique(exdata$dummy))
rowsn <- length(exdata$cohort %>% unique)
# create plots
wrap_plots(plotlist = exdata %>% filter(cut == mod) %>% pull(plots), ncol = colsn, nrow = rowsn) + plot_annotation(title = " ")
# add some text across columns
walk2(seq(0.165,0.835, length.out = colsn), unique(exdata$dummy), ~ grid.draw(textGrob(.y, x = .x, y = 0.98, rot = 0)))
库(tidyverse)
图书馆(网格)
图书馆(拼凑)
exdata%
分组依据(切割)%>%
嵌套%>%
交叉(假人=1:3)%>%
交叉(队列=字母[1:3])%>%
变异(绘图=地图(.x=数据,~ggplot(.x,aes(x=x,y=y))+geom_点()
#绘图网格的变量
mod%pull(绘图),ncol=colsn,nrow=rowsn)+绘图注释(title=”“)
#跨列添加一些文本
walk2(seq(0.165,0.835,length.out=colsn),unique(exdata$dummy),~grid.draw(textGrob(.y,x=.x,y=0.98,rot=0)))
看起来像这样:
在那个代码块中,我有一个变量mod%as.vector
步行(mods,功能(.x){
换行图(plotlist=exdata%%>%filter(cut=.x)%%>%pull(plots),ncol=colsn,nrow=rowsn)+图注释(title=”“)
walk2(seq(0.165,0.835,length.out=colsn),unique(exdata$dummy),~grid.draw(textGrob(.y,x=.x,y=0.98,rot=0)))
})
这段代码运行时似乎没有错误,但没有返回所有绘图。网格本身是,只是没有绘图:
如何运行嵌套的漫游循环为每种类型的切割生成一个网格图?只需将绘图包装在打印语句中即可解决此问题
walk(mods, function(.x) {
print(wrap_plots(plotlist = exdata %>% filter(cut == .x) %>% pull(plots), ncol = colsn, nrow = rowsn) + plot_annotation(title = " "))
walk2(seq(0.165,0.835, length.out = colsn), unique(exdata$dummy), ~ grid.draw(textGrob(.y, x = .x, y = 0.98, rot = 0)))
})
尝试在要遍历的表达式中的绘图上显式调用“print”?谢谢@CaptainHat,在print中嵌套wrap\u绘图确实解决了我的问题!
walk(mods, function(.x) {
print(wrap_plots(plotlist = exdata %>% filter(cut == .x) %>% pull(plots), ncol = colsn, nrow = rowsn) + plot_annotation(title = " "))
walk2(seq(0.165,0.835, length.out = colsn), unique(exdata$dummy), ~ grid.draw(textGrob(.y, x = .x, y = 0.98, rot = 0)))
})