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

人盡茶涼 提交于 2021-02-10 17:48:00

问题


I am trying to display sales (y-axis) week over week (x-axis) for 890 vendors. I want to display this data using a facet wrap to quickly see where vendors are having a spike in sales. The plot in my RStudio console looks as such. This Makes sense, as rendering the plot here isnt the best view, however how can I properly format my plots onto a PDF even if it requires multiple pages of PDFs. Code for plot

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


回答1:


Here's how to make multiple pages - each with 5x5 vendors.

I'll 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 5x5 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))




回答2:


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


来源:https://stackoverflow.com/questions/64030818/best-way-to-format-500-plots-using-facet-wrap-in-r-images-code-included

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!