使用ggplot和marrangeGrob在多个页面上显示多个图形

时间:2017-07-24 10:01:53

标签: r ggplot2 plyr gridextra

虽然这可能是重复的,但我想知道我的问题的解决方案。我试图运行问题Multiple graphs over multiple pages using ggplot中的代码,但我不知道数据是如何构建的,因此无法运行它。 我想绘制多个图形并以pdf格式在多个页面上打印。我用mtcars试了一下:

library(ggplot2)
library(reshape2)
library(plyr)
library(gridExtra)

mtcars2 = melt(mtcars, id.vars='mpg')
mtcars2$group[mtcars2$variable  %in% c("cyl", "disp", "hp", "drat")] <- "A"
mtcars2$group[mtcars2$variable  %in% c("wt", "qsec", "vs", "am")] <- "B"
mtcars2$group[mtcars2$variable  %in% c("gear", "cyl")] <- "C"


p = ggplot(mtcars2) +
  geom_jitter(aes(value,mpg, colour=variable)) + 
  geom_smooth(aes(value,mpg, colour=variable), method="lm", se=FALSE) +
  scale_y_continuous(limits = c(0, 60))+
  labs(x = "Percentage cover (%)", y = "Number of individuals (N)")

plots = dlply(mtcars2, "group", `%+%`, e1 = p)
ml = do.call(marrangeGrob, c(plots, list(nrow=2, ncol=2)))
ggsave("multipage.pdf", ml)

产生错误Error in (function (grobs, ncol, nrow, ..., top = quote(paste("page", : argument "grobs" is missing, with no default。如何运行此脚本?

2 个答案:

答案 0 :(得分:2)

而不是之前版本的gridExtra中所需的do.call(),请尝试marrangeGrob(grobs = plots, nrow=2, ncol=2)

答案 1 :(得分:1)

您可以使用 ggplus 包:

https://github.com/guiastrennec/ggplus

我特别觉得比使用ArrageGrobs / gridExtra更容易;它会自动将各个方面放在几页中。

由于您将初始图表保存为“p”,因此您的代码将如下所示:

# Plot on multiple pages
facet_multiple(plot = p, 
           facets = 'group', #**** 
           ncol = 2, 
           nrow = 1)