r - 在 ggplot 中使分组的面大小相同,考虑每组的面数

标签 r ggplot2

我正在解决一个问题,我想根据一些分组变量创建许多图。其中一些群体有很多我想体现的值(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/

相关文章:

r - 在 ggplot2 中使面标签水平

R plot 除了参数?

r - 用于计算平均值和标准误差的笨拙代码

mysql - 如何从 R 中具有相似名称的 SQL 表中获取所有数据

r - 更改图例中值的顺序但保留颜色

r - 通过ggplot2绘制多个变量

r - 分类变量的三角图

r - 如何根据 R 中的类别计算列中值的数量?

r - 计算 R 数据框列中变量值的唯一组合

r - ggplot 指数平滑,在 exp 内调整参数