You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为ggplot2的facet_wrap标签添加分组样本量统计

解决方案

方法1:提前生成带样本量的分组标签

在数据预处理阶段统计每个conservation_fct分组的样本量,直接把因子标签替换成包含样本量的形式,后续分面时直接使用该因子即可:

library(dplyr)
library(forcats)
library(ggplot2)

d <- msleep %>% 
    mutate(conservation_fct = fct_lump_n(conservation, 2)) %>%
    # 按分组统计样本量并合并到原数据
    group_by(conservation_fct) %>%
    mutate(group_n = n()) %>%
    ungroup() %>%
    # 重新设置因子标签,拼接原标签与样本量
    mutate(conservation_fct = fct_relabel(conservation_fct, 
                                          ~paste0(.x, " (n=", unique(group_n[conservation_fct == .x]), ")")))

ggplot(d, aes(x = sleep_total, y = awake)) + 
  geom_point() + 
  facet_wrap(~ conservation_fct)

方法2:自定义labeller函数

如果不想修改原因子,可先统计各分组样本量,再写一个灵活的labeller函数动态拼接标签:

library(dplyr)
library(forcats)
library(ggplot2)

d <- msleep %>% 
    mutate(conservation_fct = fct_lump_n(conservation, 2))

# 生成 分组名=样本量 的命名向量
group_counts <- d %>%
    count(conservation_fct) %>%
    tibble::deframe()

# 自定义分面标签函数
sample_size_labeller <- function(variable, value) {
    lapply(value, function(x) {
        paste0(x, " (n=", group_counts[as.character(x)], ")")
    })
}

ggplot(d, aes(x = sleep_total, y = awake)) + 
  geom_point() + 
  facet_wrap(~ conservation_fct, labeller = sample_size_labeller)

两种方法都无需硬编码分组名称,不管fct_lump_n保留多少个分组,都能自动适配生成带样本量的分面标签。

内容的提问来源于stack exchange,提问作者C.Robin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 08:14:57