ggplot2-如何将比例标签添加到堆叠的比例条形图?

时间:2019-05-21 17:20:31

标签: r ggplot2 geom-bar geom-text

我有一个按如下方式创建的分组堆积比例条形图:

df <- data.frame(version = c("Version #1", "Version #2", "Version #1", "Version #2", "Version #1", "Version #2"),
                 result = c("good", "good", "ok", "ok", "bad", "bad"), 
                 amount = c(1608, 616, 2516, 979, 938, 266)) 

ggplot(df, aes(x=version,y=amount, fill=result, group = result)) + 
geom_bar(stat = "identity", position="fill") 

enter image description here

我的问题是,如何向比例图中添加比例标签。像这样:

enter image description here

2 个答案:

答案 0 :(得分:2)

借助ggstatsplot软件包的帮助,这很简单-

# data
df <- data.frame(version = c("Version #1", "Version #2", "Version #1", "Version #2", "Version #1", "Version #2"),
                 result = c("good", "good", "ok", "ok", "bad", "bad"), 
                 amount = c(1608, 616, 2516, 979, 938, 266)) 

# plot
ggstatsplot::ggbarstats(
  data = df,
  main = result,
  condition = version,
  counts = amount
) +
  ggplot2::ylab("amount")

reprex package(v0.3.0)于2019-05-21创建

如果您不想获得统计结果,只需设置results.subtitle = FALSE

答案 1 :(得分:1)

使用管道和常态:

library(tidyverse)

df %>%
  group_by(version) %>%
  mutate(label = gsub('^[0](\\.\\d{1,2}).*', '\\1', amount / sum(amount))) %>%
  ungroup() %>%
  ggplot(aes(x = version, y = amount, fill = result, label = label, vjust = 2)) + 
  geom_col(position = "fill", alpha = .5) +
  geom_text(position = 'fill') +
  scale_fill_brewer(palette = 'Set1') +
  ggthemes::theme_tufte() +
  theme(axis.title.x = element_blank(), axis.ticks = element_blank(),
        legend.title = element_blank())

enter image description here