如何将标签添加到堆叠条形图

Posted

技术标签:

【中文标题】如何将标签添加到堆叠条形图【英文标题】:How to add labels to a stacked bar graph 【发布时间】:2022-01-21 07:14:48 【问题描述】:

我希望将数值添加到堆积条形图中每个堆栈的中间(代码如下)。我发现的大多数示例都针对一列中的信息,每当我尝试修改它时,都会遇到有关长度要求的错误。

DA <- data.frame(
  Imp=c("2015","2019"),
  "mismatch"=c(220,209),
  "match"=c(3465,3347),
  "NA"=c(501,630),
  check.names = FALSE)

DA %>%
  pivot_longer(-Imp) %>%
  ggplot(aes(x = Imp, y = value, fill = name)) + geom_col(position = "stack") + 
  scale_fill_manual(name=" ", values=c("aquamarine4", "orange", "coral")) +
  theme_light() +
  theme(legend.position = "bottom") +
  scale_y_continuous(expand = c(0,0)) +
  geom_text(aes(x=1, y=4300, label="Stretch it"), vjust=-1) +
  labs(y="Count", x="Imputed Genotypes") +
  geom_bar(stat = "identity", color="white", width = 1) 

【问题讨论】:

***.com/questions/70408301/…的延续 这能回答你的问题吗? Showing data values on stacked bar chart in ggplot2 【参考方案1】:

像这样?

library(tidyverse)

DA <- data.frame(
  Imp=c("2015","2019"),
  "mismatch"=c(220,209),
  "match"=c(3465,3347),
  "NA"=c(501,630),
  check.names = FALSE)

DA %>%
  pivot_longer(-Imp) %>%
  ggplot(aes(x = Imp, y = value, fill = name)) +
  geom_col(color = "white", lwd = 1,
           position = "stack", width = 0.75) + 
  scale_fill_manual(name="", values=c("aquamarine4", "orange", "coral")) +
  scale_y_continuous(expand = c(0,0),
                     limits = c(0, 4200)) +
  labs(y="Imputed Genotypes (Count)") +
  geom_text(aes(label = value), color = "white", size = 5, 
            position = position_stack(vjust = 0.5), 
            show.legend = FALSE) +
  theme_light(base_size = 18) +
  theme(legend.position = "right",
        axis.title.x = element_blank())

由reprex package (v2.0.1) 于 2021 年 12 月 19 日创建

【讨论】:

以上是关于如何将标签添加到堆叠条形图的主要内容,如果未能解决你的问题,请参考以下文章