使用stat_count时将百分比标签添加到ggplot

Vla*_* C. 2 r ggplot2

由于某些原因,我似乎无法使用来向ggplot添加正确的比例标签stat_count。下面的代码返回的标签显示所有类别的100%,即使我正在使用..prop..。我应该使用其他东西代替stat_count吗?

library(tidyverse)
diamonds %>% 
  ggplot(aes(color, fill=cut)) +
  geom_bar(position = 'fill') +
  stat_count(aes(label= scales::percent(..prop..)), 
             geom = 'text', position = position_fill(vjust = 0.5))
Run Code Online (Sandbox Code Playgroud)

我知道这也可以通过在将数据馈入之前计算百分比来实现ggplot(如下所示),但是我有很多正在使用的代码,geom_bar如果要这样做,则需要更改所有代码。

diamonds %>% 
  count(color, cut) %>% 
  group_by(color) %>% 
  mutate(pct=n/sum(n)) %>% 
  ggplot(aes(color, pct, fill=cut)) +
  geom_col(position = 'fill') +
  geom_text(aes(label=scales::percent(pct)), position = position_fill(vjust=0.5))
Run Code Online (Sandbox Code Playgroud)

Z.L*_*Lin 5

You can do the calculations within geom_label(), if you don't want to change the geom_bar part:

diamonds %>% 
  ggplot(aes(color, fill=cut)) +
  geom_bar(position = 'fill') +
  geom_text(data = . %>% 
              group_by(color, cut) %>%
              tally() %>%
              mutate(p = n / sum(n)) %>%
              ungroup(),
            aes(y = p, label = scales::percent(p)),
            position = position_stack(vjust = 0.5),
            show.legend = FALSE)
Run Code Online (Sandbox Code Playgroud)

情节