如何为ggplot堆叠柱状图选择性添加占比>5%的簇名标签
堆叠柱状图条件添加簇标签实现方法


实现思路
先计算每个簇在对应细胞亚型分组中的占比,绘图时通过条件判断仅显示占比>5%的簇标签,同时保证标签居中显示在对应堆叠块内。
完整代码
首先进行数据预处理,计算分组占比:
library(dplyr) library(ggplot2) # 新增占比计算列 plot_data <- cluster.count %>% group_by(Cell_subtype) %>% mutate(total_count = sum(count1), cluster_pct = count1 / total_count) %>% ungroup()
再绘制带条件标签的堆叠柱状图:
plot_data %>% ggplot(aes(x = Cell_subtype, y = count1, fill = seurat_clusters)) + geom_bar(stat = "identity", position = "fill") + # 添加条件显示的簇标签 geom_text(aes(label = ifelse(cluster_pct > 0.05, as.character(seurat_clusters), "")), position = position_fill(vjust = 0.5), # 标签居中对齐对应堆叠块 size = 3.5, color = "white") # 可根据填充色调整文字颜色提升可读性
参数调整说明
- 若需要显示簇的全称而非编号,将
as.character(seurat_clusters)替换为你的簇名列名即可 - 可根据出图尺寸调整
size参数修改标签字号 - 如果堆叠块填充色偏浅,可将
color改为黑色提升辨识度
内容的提问来源于stack exchange,提问作者Hh Xu
相关产品推荐
相关产品推荐

