0

Can someone please help me with adding percentages to the following barplot?

library(ggplot2)
library(dplyr)
n <- 10000

test <- data.frame(value = sample(1:3, size = n, replace = TRUE),
                   grp = sample(c("A", "B", "C"), size = n, replace = TRUE),
                   item = sample(c("Item1", "Item2", "Item3", "Item4", "Item5", "Item6"), size = n, replace = TRUE)) %>%
  mutate(value = as.factor(value))
                   
test %>%
  ggplot(aes(x = grp, fill = value, group = value)) + 
    geom_bar(position = 'fill') +
    facet_wrap(item ~., ncol = 2) +
    coord_flip() +
    scale_fill_manual(values = c("green", "yellow", "red"))
Mikael Jagan
  • 9,012
  • 2
  • 17
  • 48
D. Studer
  • 1,711
  • 1
  • 16
  • 35

1 Answers1

1

The linked answer is similar but only viable for 2 groups. Following the rabbit hole here is a solution for more than 2 from https://rstudio-pubs-static.s3.amazonaws.com/329677_8f579b9e46284caeb9d3a72b7fdb7ac3.html

test %>%
  ggplot(aes(x = grp, fill = value, group = value)) + 
  geom_bar(position = 'fill') +
  facet_wrap(item ~., ncol = 2) +
  coord_flip() +
  scale_fill_manual(values = c("green", "yellow", "red")) +
  geom_text(aes(label=scales::percent(after_stat(count)/sum(after_stat(count)))),
            stat='count',position=position_fill(vjust=0.5))

enter image description here

Update per comment to add to 100:

# create new data
percentData <- test %>% group_by(grp) %>% count(value) %>%
  mutate(ratio=scales::percent(n/sum(n)))
percentData


test %>%
  ggplot(aes(x = grp, fill = value, group = value)) + 
  geom_bar(position = 'fill') +
  facet_wrap(item ~., ncol = 2) +
  coord_flip() +
  scale_fill_manual(values = c("green", "yellow", "red")) +
  geom_text(data=percentData, aes(y=n,label=ratio),
            position=position_fill(vjust=0.5))

Code from linked site. enter image description here

dandrews
  • 967
  • 5
  • 18
  • 1
    But the percentages should sum up to 100% in each line (group and item), so there seems to be something wrong in your answer. For example: Item 1, Group C: red: 20%, yellow: 60%, red: 20% – D. Studer Mar 15 '23 at 11:32
  • Go to the linked site the other options including that one are just down another few inches, I'll work on it but the answer is there – dandrews Mar 15 '23 at 11:36
  • 1
    Please regard the updated plot code with the sum to 100 now – dandrews Mar 15 '23 at 11:47