statsguyz
statsguyz

Reputation: 459

R: ggplot2 Barplot for binomial outcome

I'd like to create a barplot with ggplot2 that plots the percentage for a binomial outcome. Here is the data that I have:

IndividualID         Pass               Group
001                  Yes                Group1
002                  Yes                Group1
003                  No                 Group1
004                  Yes                Group2
005                  No                 Group2
006                  No                 Group2
007                  Yes                Group3
008                  Yes                Group3
009                  Yes                Group3

Ideally I'd like to create something similar to this plot (created from a different data set):

enter image description here

Edit: I have tried the following with no luck.

p<-ggplot(data=data, aes(x=Group, y=Pass)) +
  geom_bar(stat="identity", position = 'fill', fill="steelblue")+
  scale_y_continuous(labels = scales::percent)

Upvotes: 0

Views: 1649

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388797

There must be a direct way to do this in ggplot but here is one way preparing the data before plotting.

library(dplyr)
library(ggplot2)

df %>%
  count(Group, Pass) %>%
  group_by(Group) %>%
  mutate(n = n/sum(n) * 100) %>%
  ggplot() + aes(Group, n, fill = Pass, label = paste0(round(n, 2), "%")) + 
  geom_col() +
  geom_text(position=position_stack(0.5))

enter image description here

data

df <- structure(list(IndividualID = 1:9, Pass = structure(c(2L, 2L, 
1L, 2L, 1L, 1L, 2L, 2L, 2L), .Label = c("No", "Yes"), class = "factor"), 
Group = structure(c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L), .Label = c("Group1", 
"Group2", "Group3"), class = "factor")), class = "data.frame",row.names = c(NA,-9L))

Upvotes: 4

Related Questions