如何修改Raincloud图的Y轴以展示每组观测样本数量?
解决方案
核心思路是先统计每个物种的样本量,再将物种名称与样本量合并成新的Y轴刻度标签,具体有两种实现方式:
方法1:预处理数据生成带样本量的标签
先统计每个物种的样本数,生成包含样本量的新标签列,然后直接将该列作为Y轴映射变量:
library(dplyr) library(ggplot2) library(ggdist) # 统计每个物种的样本量并生成带样本量的标签 species_labels <- iris %>% count(Species) %>% mutate(label = paste(Species, paste0("(n=", n, ")"), sep = "\n")) # 合并数据并绘图 Rc <- iris %>% left_join(species_labels, by = "Species") %>% group_by(Species) %>% mutate(mean = mean(Petal.Length), se = sd(Petal.Length)/sqrt(length(Petal.Length))) %>% ungroup() %>% ggplot(aes(x = Petal.Length, y = label)) + stat_slab(aes(fill = Species)) + stat_dots(aes(color = Species), side = "bottom", shape = 16) + scale_fill_brewer(palette = "Set1", aesthetics = c("fill", "color")) + geom_errorbar(aes(xmin = mean - 1.96 * se, xmax = mean + 1.96 * se), width = 0.2) + stat_summary(fun = mean, geom = "point", shape = 16, size = 3.0) + theme_bw(base_size = 10) + theme(legend.position = "top") + labs(title = "Raincloud plot with ggdist", x = "Petal Length", y = "Species (Sample Size)") print(Rc)
方法2:通过scale_y_discrete动态替换标签
不需要修改原始数据,直接在绘图时通过scale_y_discrete的labels参数动态生成带样本量的标签:
library(dplyr) library(ggplot2) library(ggdist) # 提前统计每个物种的样本量 species_counts <- iris %>% count(Species) # 绘图并替换Y轴标签 Rc <- iris %>% group_by(Species) %>% mutate(mean = mean(Petal.Length), se = sd(Petal.Length)/sqrt(length(Petal.Length))) %>% ungroup() %>% ggplot(aes(x = Petal.Length, y = Species)) + stat_slab(aes(fill = Species)) + stat_dots(aes(color = Species), side = "bottom", shape = 16) + scale_fill_brewer(palette = "Set1", aesthetics = c("fill", "color")) + geom_errorbar(aes(xmin = mean - 1.96 * se, xmax = mean + 1.96 * se), width = 0.2) + stat_summary(fun = mean, geom = "point", shape = 16, size = 3.0) + # 动态生成带样本量的Y轴标签 scale_y_discrete( labels = function(species_name) { sample_size <- species_counts$n[species_counts$Species == species_name] paste(species_name, paste0("(n=", sample_size, ")"), sep = "\n") } ) + theme_bw(base_size = 10) + theme(legend.position = "top") + labs(title = "Raincloud plot with ggdist", x = "Petal Length", y = "Species (Sample Size)") print(Rc)
两种方法都能实现需求,方法1适合需要多次复用带样本量标签的场景,方法2更轻量化,不需要修改原始数据结构。
内容的提问来源于stack exchange,提问作者user21215346
相关产品推荐
相关产品推荐

