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

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

Heres how to make multiple pages – each with 5×5 vendors.

Ill use some dummy data with 890 vendors.

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
)

Split into groups of 25 vedors. Each plot has a 5×5 facet.

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

Save so that each plot has its own page.

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

enter

Why not plug all plots individually in one single pdf and get rid of facet_wrap completely.

Reproducible example:

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

Following gives a similar plot as yours

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

Getting rid of facet_wrap completely and flushing the plots to a single 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()

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

Leave a Reply

Your email address will not be published.