在 R 中使用 facet wrap 格式化 500 多个图的最佳方法? [包括图像和代码]

Best way to format 500+ plots using facet wrap in R? [images & code included]

我正在尝试显示 890 个供应商每周(x 轴)的销售额(y 轴)。我想使用 facet wrap 显示此数据,以快速查看供应商在哪些地方出现了销售高峰。我的 RStudio 控制台中的绘图看起来是这样的。这是有道理的,因为在此处渲染绘图并不是最佳视图,但是即使它需要多页 PDF,我如何才能将绘图正确地格式化为 PDF。绘图代码

ggplot(Holiday_Spike_Table, aes(x = FSCL_WK, y = SLS))+ 
  geom_col()+
  facet_wrap(~MVNDR_NM)

为什么不将所有情节单独插入一个 pdf 中并完全摆脱 facet_wrap。

可重现的例子:

library(ggplot2)
library(stringi)

## generate dummy data
df <- data.frame(x=sample(1:10000, 1000, replace=TRUE),y=sample(1:100000, 1000, replace=TRUE))
df$id <- stri_rand_strings(n = nrow(df)/10, length = 4, pattern = "[A-Za-z0-9]")

以下给出了与您的相似的情节

ggplot(data = df,aes(x=x,y=y)) + geom_point() + geom_smooth() + facet_wrap(~id)

完全摆脱 facet_wrap 并将绘图刷新为单个 pdf

pdf("pathtopdf.pdf", onefile = TRUE)
for (i in unique(df$id)) {
  plot(ggplot(df[df$id==i,], aes(x = x, y = x)) + geom_point() + geom_smooth()) 
}
dev.off()

以下是制作多个页面的方法 - 每个页面有 5x5 个供应商。

我将对 890 个供应商使用一些虚拟数据。

library("tidyverse")

df <- data.frame(
  vendor = rep(seq_len(890), each = 30) ,
  x = rep.int(seq_len(30), 890),
  y = runif(890 * 30),
  group = (rep(seq_len(890), each = 30) - 1) %/% 25
)

分成 25 个供应商小组。每个地块都有一个 5x5 的小平面。

plots <- 
  df %>%
  group_by(group) %>%
  group_map(function(g, ...) ggplot(g, aes(x, y)) + geom_line() + facet_wrap(~vendor, ncol = 5))

保存以便每个图都有自己的页面。

ggsave("plots.pdf", gridExtra::marrangeGrob(plots, nrow = 1, ncol = 1))