Patrick
Patrick

Reputation: 1631

ggplot normalize a group histogram by group

How to normalize a ggplot group histogram per group?

Example:

library(data.table)
library(ggplot2)

# Test data.
test <- data.table(id=1:100, cat=c(rep(c("A", "B", "A", "A", "B"), 20))
                 , grp=paste0("G", c(rep(1:2,50))))
test[, catGrp := paste0(cat, grp)]

# Normalized histogram of cat by grp.
# It is normalized over all grp.
# I want it normalized by grp.
ggplot(test, aes(x=cat, group=grp, fill=grp))
  + geom_histogram(aes(y=..count../sum(..count..)), position=position_dodge())

Result I get:

I would like to get the same histogram as this one but with sum for each group = 1 -- or levels would be 0.6 & 0.4 instead of 0.3 & 0.2.

What is the simplest way to accomplish? Thanks.

Upvotes: 1

Views: 1524

Answers (1)

matt_k
matt_k

Reputation: 4489

tab <- as.data.frame(prop.table(table(test$cat, test$grp), 2))
ggplot(tab, aes(y = Freq,  x = Var1, fill = Var2)) + 
       geom_bar(stat = "identity", position = position_dodge())

Upvotes: 1

Related Questions