Search code examples
rbar-chartstacked-bar-chart

Stacked barplot with two categories in R


I am trying to create a stacked barplot in R to visualize differences in two groups.

My dataset looks like this:

A User
ABC Male
DEF Female
GHI Female
XYZ Female
JKL Male
ABC Male
XYZ Male
XYZ Female

I would like the User to be on the x-axis, the count or percentage of A on the y-axis, and the categories of A to be the stacks or the fill or the different groups.

Edit:

ggplot(data, aes(x=User, fill = A)) + 
  geom_bar(position = "fill") + 
  scale_fill_brewer(palette = "BrBG") + 
  labs(y = "Percent") 

Is there a way to show the percent labels on the stacks?


Solution

  • You can calculate percentage first, then use those values to add as labels in geom_text.

    library(tidyverse)
    
    df %>%
      count(User, A) %>%
      group_by(User) %>%
      mutate(pct = n / sum(n)) %>%
      ggplot(aes(x = User, y = pct, fill = A)) +
      geom_col(width = 0.7) +
      geom_text(aes(label = paste0(round(pct * 100), '%')),
                position = position_stack(vjust = 0.5)) +
      scale_fill_brewer(palette = "BrBG") + 
      labs(y = "Percent")
    

    Output

    enter image description here

    Data

    df <- structure(list(A = c("ABC", "DEF", "GHI", "XYZ", "JKL", "ABC", 
    "XYZ", "XYZ"), User = c("Male", "Female", "Female", "Female", 
    "Male", "Male", "Male", "Female")), class = "data.frame", row.names = c(NA, 
    -8L))