簡體   English   中英

在多頁pdf中繪制多個ggplots(每頁一個或多個圖)

[英]plotting multiple ggplots in a several page pdf (one or several plots per page)

我正在嘗試生成一個類似儀表板的 pdf(每個物種一頁),其中包含 3 個不同的圖(每個物種),我想將此輸出保存為 pdf。 我已經嘗試了幾個想法,reprex 取自鏈接,從長遠來看,它似乎應該適用於我所需要的。 但我無法讓它工作

組成一些數據和圖表

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

我錯過了什么?

最終的解決方案實際上非常簡單......

### 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")

這個版本實際上可以讓您完全控制繪圖大小並使用整個頁面!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM