gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 02:53:07 25 4
gpt4 key购买 nike

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

我已阅读?facet_wrap帮助文件,并且也在谷歌上搜索了这个主题,但效果有限。合而为一SO post , facet_wrap()据说“返回一个对称的图矩阵”,但我没有找到任何可以解释默认行为到底是什么的东西。

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

Set of plots with increasing number of facets

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

问题

  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)

以下是计算出的行/列数:

#   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

关于r - ggplot2::facet_wrap() 的默认面板布局?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60104268/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com