2017-08-18 89 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