将图例标签添加到 ggplot 的条形图

时间:2021-06-27 18:01:21

标签: r ggplot2 bar-chart

我想将簇名称添加到 ggplot 中的堆叠条形图中。

enter image description here

如您所见,一些簇的分数非常小,并且每个条中有许多簇。这使得查看哪些集群具有挑战性,尤其是在相似颜色之间。 理想情况下,我想用它的名字有选择地标记一些大的分数(或簇), 假设百分比 > 5% 时,显示其集群名称。

例如,在示例“naive CD8 T”中,我想标记集群 4 和 5,如下所示:

enter image description here

cluster.count %>% 
  ggplot(aes(x=Cell_subtype,y=count1, fill= seurat_clusters)) +
  geom_bar(stat="identity", position = 'fill')

1 个答案:

答案 0 :(得分:3)

这可以像这样实现:

  1. 我没有使用 position="fill",而是通过 group_by + mutate
  2. 手动计算百分比
  3. 然后可以通过 geom_text 轻松添加标签,您可以在其中使用 ifelse 仅显示具有所需最小频率或比例的标签。

使用一些随机示例数据试试这个:

library(ggplot2)
library(dplyr)

set.seed(42)
cluster.count <- data.frame(
  Cell_subtype = sample(LETTERS[1:4], 60, replace = TRUE),
  seurat_clusters = sample(0:16, 60, replace = TRUE)
)
cluster.count <- count(cluster.count, Cell_subtype, seurat_clusters, name = "count1")
cluster.count <- mutate(cluster.count, seurat_clusters = factor(seurat_clusters))

cluster.count %>% 
  group_by(Cell_subtype) %>% 
  mutate(pct = count1 / sum(count1)) %>% 
  ggplot(aes(x=Cell_subtype,y=pct, fill= seurat_clusters)) +
  geom_col() +
  geom_text(aes(label = ifelse(pct > .1, as.character(seurat_clusters), "")), position = position_stack(vjust = .5))