2

For some reason, I can't seem to be able to add correct proportion labels to a ggplot by using stat_count. The code below returns labels that display 100% for all categories, even though I'm using ..prop... Should I use something else instead of 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))

I know this can also be accomplished by calculating the percentage before feeding the data to ggplot (like below) but I have quite a bit of code which is using geom_bar and I would need to change all of it if I were to do it this way.

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))
2
  • which ggplot2 version are you using? Commented Aug 30, 2018 at 7:32
  • I just installed the latest ggplot2 version but I still have the same issue Commented Aug 30, 2018 at 8:14

1 Answer 1

10

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)

plot

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you, Z.Lin! Your solution works! Do you know why the default ..prop.. doesn't work (or what situations it was meant for)?
Based on my understanding, ..prop.. gives the groupwise proportion. By default stat_count considers each x-axis position separately, and fill = cut means each "cut" value (Fair / Good / etc.) is considered a distinct group. Thus each color-cut combination becomes its own group, with proportion = 100%.
Hey, great answer! Simple and understandable!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.