【问题标题】:Arrange multiple ggplots from a list on multiple pages with specified page breaks从具有指定分页符的多个页面上的列表中排列多个 ggplots
【发布时间】:2018-01-26 13:21:14
【问题描述】:

我正在尝试从列表中获取图表并输出多页 pdf。我可以使用 gridExtra:marrangeGrob 轻松做到这一点,但是我在将分页符放置在正确的位置时遇到了问题。我的数据以 7 个为一组,所以我想要 4 页,每页有两个图,然后在第 7 个图之后休息,第 8 个从新页面开始(如第 14、21 等之后)。

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

我查看了ggplot list of plots to one pdf with different page layouts,但我不想单独设置每个页面,因为它们太多了(一旦我有了初始页面,我也可能想更改为每页 3 或 4 个,并且不想重新工作。

我使用 diamonds 数据框做了一个示例,假设我想拆分页面,以便来自两个不同清晰度的图不在同一页面上

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(list(list(data = list(carat = c(0.32, 1.01, 0.43, 1.22, ) 中的错误: “gList”中只允许使用“grobs”

有什么想法吗?

【问题讨论】:

  • 暂定建议,因为我不知道您的实际数据集,但是可以在每组数据上使用facet_wrap 吗?您可以将数据子集并将所有 7 个(或任何数字)绘制为 1 个 ggplot 对象,然后将每个图保存到 1 页。
  • 哈哈,我从 facet_wrap/facet_grid 开始,但我希望每个情节都有一个副标题和标题(不是所有在我分解它的方面)并且不知道该怎么做那。不过,这样做可能最终会更容易

标签: r ggplot2 gridextra


【解决方案1】:

试试这个,

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()

【讨论】:

  • 谢谢!这主要是有效的。 layout_matrix 似乎不适用于 marrangeGrob (仅适用于arrangeGrob),但我使用了 ppl
  • 我正在使用可以将 layout_matrix 传递给 marrangeGrob 的开发版本。标题你可以试试marrangeGrob(..., top = quote(paste("page", g, "of", length(spl) * pages )))
  • 啊,好吧,我会坚持我目前的版本。这给了我正确的总页数,但不是它最多的单个页面(重复 48 个中的 1:4),我尝试通过列表修复计数,但似乎没有工作。不用强调,页码没什么大不了的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-26
  • 1970-01-01
相关资源
最近更新 更多