You need to enable JavaScript to run this app. 如何为ggplot堆叠柱状图选择性添加占比>5%的簇名标签
优惠活动
大模型
产品
解决方案
定价
更多

如何为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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 07:36:05