【问题标题】:plotting multiple ggplots in a several page pdf (one or several plots per page)在多页pdf中绘制多个ggplots(每页一个或多个图)
【发布时间】:2021-12-19 10:35:33
【问题描述】:

我正在尝试生成一个类似于仪表板的 pdf(每个物种一页),其中包含 3 个不同的图(每个物种),我想将此输出另存为 pdf。我尝试了几个想法,reprex 取自 this 链接,从长远来看,它似乎应该适用于我需要的东西。但我无法让它工作

编造一些数据和图表

df = data.frame(x = seq(1:30), y = rnorm(30), z = runif(30, 1, 10))

# Example plots
p.1 = ggplot(df, aes(x = x, y = y)) +
  geom_point()
p.2 = ggplot(df, aes(x = x, y = z)) +
  geom_point()
p.3 = ggplot(df, aes(x = y, y = z)) +
  geom_point()
p.4 = ggplot(df, aes(x = y)) +
  geom_histogram()

plots.list = list(p.1, p.2, p.3, p.4)  # Make a list of plots

我的愚蠢解决方案工作正常(即循环遍历每个物种,然后将它们打印成 pdf,然后关闭 pdf)除了事实上,情节并没有使用整个空间这看起来很愚蠢;-)。

pdf("myname.pdf", paper="a4r")
for (i in 1:length(plot.list)){print(plot.list[[i]])}
dev.off()

所以这是reprex的其余部分

原版

# Generate plots to be saved to pdf, warning the argument to marrangeGrob
# have to be passed using do.call
# nrow (ncol) gives the number of rows (columns) of plots per page
# nrow and ncol have to be specificed inside a list
# Here, we'll obtain 2 plots in rows by page
plots = do.call(marrangeGrob, c(plots.list, list(nrow = 2, ncol = 1)))

# To save to file, here on A4 paper
ggsave("multipage_plot.pdf", plots, width = 21, height = 29.7, units = "cm")

Error in `$<-.data.frame`(`*tmp*`, "wrapvp", value = list(x = 0.5, y = 0.5,  : 
  replacement has 33 rows, data has 30

我错过了什么?

【问题讨论】:

  • 你有没有想过用 RMarkdown 代替 Rscripts?在那里,您可以轻松地混合代码、书面文本和图像。您还可以使用参数 fig.height 和 fig.width 编辑图像的大小
  • 您在寻找this吗?
  • @Edo:是的,但这也不是我想要的。实际上,我确实使用 RMarkdown 只是为了能够拥有单独的代码块并以更好的格式做笔记,很好的建议!
  • @Rui Barradas:不完全是,因为这仅指定了每页的绘图数量,但并未真正指定它们的排列。

标签: r pdf ggplot2 plot


【解决方案1】:

最后解决方案其实很简单……

### create a layout matrix (nrow and ncol will do the trick too, but you have less options)

layout_mat<-rbind(c(1,1,2),
                  c(1,1,3))

plots<-marrangeGrob(plot.list, layout_matrix=layout_mat)


ggsave( filename="mypdf.pdf", plots, width=29.7, height=21, units="cm")

这个版本实际上让您可以完全控制绘图大小并使用整个页面!

【讨论】:

    猜你喜欢
    • 2012-08-27
    • 1970-01-01
    • 2017-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多