简体   繁体   English

ggplot2 - 如何在堆叠比例条形图中添加比例标签?

[英]ggplot2 - How do I add proportion labels to stacked proportion barplot?

I have a grouped stacked proportion barplot that I created like this: 我有一个像这样创建的分组堆叠比例条形图:

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") 

在此输入图像描述

My questions is, how can I add proportion labels to the plot. 我的问题是,如何在情节中添加比例标签。 Something like this: 像这样的东西:

在此输入图像描述

This is straightforward to do with the help of ggstatsplot package- 这很简单,在ggstatsplot的帮助下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")

Created on 2019-05-21 by the reprex package (v0.3.0) reprex包创建于2019-05-21(v0.3.0)

If you don't want statistical results, just set results.subtitle = FALSE . 如果您不想要统计结果,只需设置results.subtitle = FALSE

With pipes and usuals: 有管道和通常:

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())

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM