ggplot2::facet_wrap() 的默认面板布局?

Default panel layout of ggplot2::facet_wrap()?

我正在尝试了解 ggplot2::facet_wrap() 的默认行为,即面板布局随着分面数量的增加而确定的方式。

我已阅读 ?facet_wrap 帮助文件,并在谷歌上搜索了该主题,但收效甚微。在一个 SO post 中,facet_wrap() 被认为是 "return a symmetrical matrix of plots",但我没有找到任何解释默认行为的确切内容。

所以接下来我制作了一系列具有越来越多方面的图(代码显示在下方)。

图片中的图案让人觉得 facet_wrap() 试图 "make a square"...

问题

  1. 对吗? facet_wrap 是否尝试渲染 facet 面板所以总体上它们最像一个正方形,就 行和列中的元素数量?
  2. 如果不是,它实际上在做什么?是否考虑图形参数?

制作情节的代码

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

默认行数和列数的计算方式如下:

ncol <- ceiling(sqrt(n))
nrow <- ceiling(n/ncol)

显然,facet_wrap 倾向于更宽的网格,因为“大多数显示器大致是矩形的”(根据文档)。因此,列数将大于或等于行数。

以你的例子为例:

n <- c(1:25)

ncol <- ceiling(sqrt(n))
nrow <- ceiling(n/ncol)

data.frame(n, ncol, nrow)

这里是rows/cols的计算数字:

#   n   ncol   nrow
#   1      1      1
#   2      2      1
#   3      2      2
#   4      2      2
#   5      3      2
#   6      3      2
#   7      3      3
#   8      3      3
#   9      3      3
#  10      4      3
#  11      4      3
#  12      4      3
#  13      4      4
#  14      4      4
#  15      4      4
#  16      4      4
#  17      5      4
#  18      5      4
#  19      5      4
#  20      5      4
#  21      5      5
#  22      5      5
#  23      5      5
#  24      5      5
#  25      5      5