1

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?

Sunderam Dubey
  • 1
  • 11
  • 20
  • 40
user2845095
  • 465
  • 2
  • 9

2 Answers2

1

You may try

library(ggplot2)
library(dplyr)
df %>%
  group_by(User) %>%
  count(A) %>%
  ggplot(aes(x = User, y = n, fill = A)) +
  geom_col()

enter image description here

Park
  • 14,771
  • 6
  • 10
  • 29
  • I tried this and it worked: 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? – user2845095 Jun 15 '22 at 06:21
1

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))
AndrewGB
  • 16,126
  • 5
  • 18
  • 49