2017-08-18 83 views
0

我试图从列表中获取图并输出多页pdf。我可以使用gridExtra轻松完成这个任务:marrangeGrob但是我在正确的位置获得分页符的问题。我的数据是7组,因此我希望每页有4个页面,每个页面有两个图表,然后在第7个图表开始后,第8个图表开始新页面(如第14,第21个等)。从指定分页符的多个页面的列表中排列多个ggplots

我的列表包含(目前84个ggplots,可能会在未来更多)

我看着ggplot list of plots to one pdf with different page layouts但我不希望有单独设置每个页面有那么多的人(我也可能想要更改为每页3或4,一旦我有最初的,不想重新工作。

我做了一个使用钻石数据框的例子,假设我想拆分页面如此从两个不同clarities的阴谋不在同一页

egsplitdf <- diamonds %>% distinct(color, clarity) %>% arrange(clarity) 
egPlotfun <- function(i, filterdf){ 
    dat = filter(diamonds, color == filterdf[["color"]][i] & clarity == 
     filterdf[["clarity"]][i]) 
    ggplot(dat, aes(x= x, y = y))+ 
     geom_point()+ 
     labs(title = paste(filterdf[["clarity"]][i], filterdf[["color"]][i])) 
} 

egPlots <- lapply(1:56, egPlotfun,filterdf = egsplitdf) 
ArrangedPlots <- marrangeGrob(egPlots, nrow = 2, ncol = 1) 
ggsave("egNotsplit.pdf", ArrangedPlots, height = 10,width = 7) 

但这恰恰有地块连续经过7等 我也试图分裂我的地块进入

plotseq <- lapply(0:8,function(x) seq(from = (x*7+1), length.out = 7)) 
ListofPlots <- lapply(plotseq, function(x) lapply(x, egPlotfun, filterdf = egsplitdf)) 
testSplit <-marrangeGrob(ListofPlots , nrow = 2, ncol = 1) 
ggsave("TrySplit.pdf", testSplit, height = 10,width = 7) 

列表没有休息,但是这给: “错误为Glist(名单(名单(数据=列表(carat = c(0.32,1.01,0.43,1.22,: 只有'grobs'允许在“gList”中)

任何想法?

+0

暂定建议,因为我不知道你的实际数据集,但它是可以使用'facet_wrap'对每一组数据?您可以对数据进行子集合并将全部7个(或任何数字可能)绘制为1个ggplot对象,然后将每个绘图保存为1页。 –

+0

哈哈,我从一个facet_wrap/facet_grid开始,但我希望每个情节都有一个字幕和标题(并不是所有的方面都是我分手的),并且不能指出如何做到这一点。可能最终以这种方式做起来更容易 – user2738526

回答

0

试试这个,

enter image description here

library(gridExtra) 
library(ggplot2) 

pl <- lapply(1:84, function(i) ggplot() + ggtitle(i)) 

spl <- split(pl, (seq_along(pl)-1) %/% 7) 
ppl <- lapply(spl, function(g) marrangeGrob(grobs = g, layout_matrix = matrix(c(1,2)))) 

pdf("test.pdf") 
print(ppl) 
dev.off() 
+0

谢谢!这大部分工作。 layout_matrix似乎并不适用于marrangeGrob(只安排了Grob),但我使用了ppl < - lapply(spl,function(g)marrangeGrob(grobs = g,nrow = 2,ncol = 1))。我希望能得到正确的页码(重复1到4),但我可以没有它,除非你有任何鬼鬼祟祟的建议? – user2738526

+0

我正在使用dev版本,其中layout_matrix可以传递给marrangeGrob。对于标题,你可以尝试'marrangeGrob(...,top = quote(paste(“page”,g,“of,length(spl)* pages)))' – baptiste

+0

啊,好的,我会坚持我现在有版本。这给了我正确的总页数,但没有达到哪个单独的页面(重复48个中的1:4),我尝试摆弄通过列表修复计数,但似乎没有工作。没有压力的页码是没有什么大不了的。 – user2738526