1
votes

I am trying to make a grouped bar graph in R with percentages on the y-axis, but I want these percentages to be percentages of the variable grouped by, and not the variable on the x-axis. I explain further:

Using this code, I can make the following bar graph:

ggplot(data=test, aes(cat1))+
  geom_bar(aes(fill=as.factor(cat2), y = (..count..)/sum(..count..)), position="dodge") + 
  scale_y_continuous(labels=percent)

Bar Graph with Percentages

This graph does not display the percentages that I want. Here the percentages are of the total. I also do not want a proportional stacked bar graph where the bar for each cat1 value is 100%. What I want is a grouped bar graph, where the 5 bars for each cat2 value add to 100%. So in the image linked above, I would want all the red bars to add to 100%, all the blue bars to add to 100%, and all the green bars to add to 100%. What I am trying to do is show what percent of each cat2 value is in each of the cat1 values.

I've searched all over and I've only been able to find how to get total percentages, or percentages for each value on the x-axis. Thank you in advance for any help you can offer.

1

1 Answers

2
votes

Here is an approach

First some data:

set.seed(1)
df = data.frame(cat1 = sample(1:3, 300, c(0.2, 0.3, 0.5), replace = T),
                cat2 = sample(1:3, 300, c(0.3, 0.3, 0.4), replace = T))

your example graph with the generated data:

ggplot(data=df, aes(cat1))+
  geom_bar(aes(fill=as.factor(cat2), y = (..count..)/sum(..count..)), position="dodge") + 
  scale_y_continuous(labels=scales::percent_format())

enter image description here

grouped by fill:

library(tidyverse)
df %>%
  group_by(cat2, cat1) %>% #group by both variables
  summarise(n = n()) %>% #count members per group
  group_by(cat2) %>% #group just by the fill variable
  mutate(y = n/sum(n)) %>% #percent of each cat1 n per cat2 group
  ggplot()+
  geom_col(aes(y=y, x = cat1, fill = as.factor(cat2)), position="dodge")+
  scale_y_continuous(labels=scales::percent_format())

enter image description here