我正在解决一个问题,我想根据一些分组变量创建许多图。其中一些群体有很多我想体现的值(value)观,而另一些群体只有很少的值(value)观。我想将所有面显示为相同大小。
在这个reprex中,8个圆柱组只有2个小平面,而其他组有3个。我希望8个圆柱组中的2个小平面与其他组中的小平面大小相同,并且第三个缺失小平面的空间正好留空。
library(tidyverse)
for(i in unique(mtcars$cyl)){
sub_data <- filter(mtcars, cyl == i)
p <- ggplot(sub_data, aes(wt, drat)) +
geom_point() +
facet_wrap(~gear) +
labs(title = paste(i, "cyl"))
print(p)
}
最佳答案
一个选项是ggh4x::facet_manual
,它允许向绘图添加空白面板。对于每个图,您可以指定一个设计
,该设计可以用空白面板填充,以便每个图具有相同数量的面板。
library(ggplot2)
library(dplyr)
library(ggh4x)
# Maximum number of panels
nmax <- max(tapply(mtcars$gear, mtcars$cyl, n_distinct))
for(i in unique(mtcars$cyl)){
sub_data <- filter(mtcars, cyl == i)
# Number of panels for plot i
ngear <- n_distinct(sub_data$gear)
# Create design
design = paste(c(LETTERS[seq(ngear)], rep("#", nmax - ngear)), collapse = "")
print(design)
p <- ggplot(sub_data, aes(wt, drat)) +
geom_point() +
facet_manual(~gear, design = design, trim_blank = FALSE) +
labs(title = paste(i, "cyl"))
print(p)
}
#> [1] "ABC"
#> [1] "ABC"
#> [1] "AB#"
关于r - 在 ggplot 中使分组的面大小相同,考虑每组的面数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71474000/