There are lots of questions on how to arrange ggplots in a grid using loops. However, I can't piece together what I'm after.
I want to plot an arbitrary number of equally sized graphs in a loop. Crucially, I want to use facet_wrap
AND pre split the data into groups (explained why below). Here is an example:
df <- mtcars
df$car <- rownames(df)
ucar <- unique(df$car)
# Split data into groups of n (6's here)
split6s <- split(ucar, ceiling(seq_along(ucar)/6))
p <- list()
# For each group of 6, plot something (mpg vs wt) faceted by group (car)
for(i in 1 :length(split6s)){
# Subset for group
temp <- subset(df, car %in% split6s[[i]])
# Save plot forcing facet with 1 row
p[[i]] <- ggplot(temp, aes(mpg, wt)) + geom_point() +
facet_wrap(~car, nrow = 1)
}
p[[5]]
p[[6]]
Desired p[[6]]
I want to do this so that I can standardize the size of some graphs in rmarkdown
but use facets instead of just grobbing individual plots together.