ggplot按组标准化组直方图

时间:2014-02-18 00:47:29

标签: r ggplot2

如何规范每组的ggplot组直方图?

示例:

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())

结果我得到:

我想获得与此相同的直方图,但是每组的总和= 1 - 或者水平将是0.6&amp; 0.4而不是0.3&amp; 0.2。

最简单的方法是什么?感谢。

1 个答案:

答案 0 :(得分:1)

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())