ggplot2:将标签添加到百分比图(不是位置=填充,而是填充)

ggplot2: add labels to percentage plot (not position=fill, but just fill)

我想将百分比标签添加到百分比条形图

我找到了 position="fill" () and also here (How to draw stacked bars in ggplot2 that show percentages based on group?) 的解决方案,但是,我想保留每个组的相对频率。

这是一个示例图:

# library
library(ggplot2)

# data  
df <- data.frame(group=c("A","A","A","A","B","B","B","C","C"),
                   anon=c("yes","no","no","no","yes","yes","no","no","no"))

# percentage barplot
  ggplot(df, aes(group),fill=anon) + 
    geom_bar(aes(y = (..count..)/sum(..count..),fill=anon)) + 
    scale_y_continuous(labels=scales::percent) +
    ylab("relative frequencies")

reprex package (v0.3.0)

于 2020-04-19 创建

现在我想为每个条形的每个红色和绿色部分添加百分比标签,以便我得到 "relative-relative"(例如,对于 A 组 "yes" 为 25%)值。 如何才能做到这一点?我必须为此更改我的 df 还是在 ggplot 函数

中以某种方式可能

一种可能的解决方案是在ggplot2之外计算比例,这里我使用dplyr来计算那些不同的比例:

library(dplyr)

df_calculated <- df %>% count(group, anon) %>%
  mutate(Percent_col = n / sum(n)) %>%
  group_by(group) %>%
  mutate(Percent = n/sum(n))

# A tibble: 5 x 5
# Groups:   group [3]
  group anon      n Percent_col Percent
  <fct> <fct> <int>       <dbl>   <dbl>
1 A     no        3       0.333   0.75 
2 A     yes       1       0.111   0.25 
3 B     no        1       0.111   0.333
4 B     yes       2       0.222   0.667
5 C     no        2       0.222   1    

然后使用geom_col代替geom_bar绘制条形图,geom_text添加每个比例的文本标签:

library(dplyr)
library(ggplot2)

ggplot(df_calculated, aes(x = group, y = Percent_col, fill = anon))+
  geom_col()+
  scale_y_continuous(labels=scales::percent) +
  ylab("relative frequencies")+
  geom_text(aes(label = scales::percent(Percent)), position = position_stack(0.5))+
  geom_text(inherit.aes = FALSE, 
            data = df_calculated %>% 
              group_by(group) %>% 
              summarise(Sum = sum(Percent_col)),
            aes(label = scales::percent(Sum), 
                y = Sum, x = group), vjust = -0.5)

它是否回答了您的问题?