【问题标题】:Default panel layout of ggplot2::facet_wrap()?ggplot2::facet_wrap() 的默认面板布局?
【发布时间】:2020-05-23 01:09:35
【问题描述】:

我正在尝试了解ggplot2::facet_wrap() 的默认行为,即随着构面数量的增加如何决定面板布局。

我已经阅读了?facet_wrap 帮助文件,并且还在谷歌上搜索了这个主题,但成功率有限。在一个SO post 中,facet_wrap() 据说“返回一个对称的图矩阵”,但我没有找到任何可以解释默认行为的确切内容。

接下来我制作了一系列图,这些图的面数越来越多(代码在下方显示)。

图片中的图案看起来像是facet_wrap() 试图“制作一个正方形”...

问题

  1. 正确吗? facet_wrap 是否尝试渲染刻面 面板,所以总的来说,它们最像一个正方形,就 行和列中的元素数?
  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)  

【问题讨论】:

  • 不看 ggplot 代码,如果它默认使用 grDevices::n2mfrow 之类的东西我不会感到惊讶(尽管它似乎从行而不是列切换)

标签: r ggplot2 facet-wrap


【解决方案1】:

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

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)

这里是计算出来的行数/列数:

#   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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-27
    • 2016-06-14
    相关资源
    最近更新 更多