I'm trying to understand the default behavior of ggplot2::facet_wrap()
, in terms of how the panel layout is decided as the number of facets increases.
I've read the ?facet_wrap
help file, and also googled this topic with limited success. In one SO post, facet_wrap()
was said to "return a symmetrical matrix of plots", but I did not find anything that explained what exactly the default behavior would be.
So next I made a series of plots which had increasing numbers of facets (code shown further down).
The pattern in the image makes it seem like facet_wrap()
tries to "make a square"...
Questions
- Is that correct? Does
facet_wrap
try to render the facet panels so in totality they are most like a square, in terms of the number of elements in the rows and columns? - If not, what is it actually doing? Do graphical parameters factor in?
Code that made the plot
# load libraries
library(ggplot2)
library(ggpubr)
# plotting function
facetPlots <- function(facets, groups = 8){
# sample data
df <- data.frame(Group = sample(LETTERS[1:groups], 1000, replace = T),
Value = sample(1:10000, 1000, replace = T),
Facet = factor(sample(1:facets, 1000, replace = T)))
# get means
df <- aggregate(list(Value = df$Value),
list(Group = df$Group, Facet = df$Facet), mean)
# plot
p1 <- ggplot(df, aes(x= Group, y= Value, fill = Group))+
geom_bar(stat="identity", show.legend = FALSE)+
facet_wrap(. ~ Facet) +
theme_bw()+
theme(strip.text.x = element_text(size = 6,
margin = margin(.1, 0, .1, 0, "cm")),
axis.text.x=element_blank(),
axis.ticks=element_blank(),
axis.title.x=element_blank(),
axis.text.y=element_blank(),
axis.title.y=element_blank(),
plot.margin = unit(c(3,3,3,3), "pt"))
p1
}
# apply function to list
plot_list <- lapply(c(1:25), facetPlots)
# unify into single plot
plot <- ggpubr::ggarrange(plotlist = plot_list)