ggplot:两组的相对频率

时间:2012-06-04 20:45:58

标签: r ggplot2

我想要一个这样的情节,除了每个方面总和达到100%。现在组M是0.05 + 0.25 = 0.30而不是0.20 + 0.80 = 1.00。

df <- rbind(
    data.frame(gender=c(rep('M',5)), outcome=c(rep('1',4),'0')),
    data.frame(gender=c(rep('F',10)), outcome=c(rep('1',7),rep('0',3)))
)

df

ggplot(df, aes(outcome)) +
    geom_bar(aes(y = (..count..)/sum(..count..))) +
    facet_wrap(~gender, nrow=2, ncol=1) 

(使用y = ..density ..会产生更糟糕的结果。)

2 个答案:

答案 0 :(得分:16)

这是另一种方式

ggplot(df, aes(outcome)) +
    geom_bar(aes(y = ..count.. / sapply(PANEL, FUN=function(x) sum(count[PANEL == x])))) +
    facet_wrap(~gender, nrow=2, ncol=1) 

答案 1 :(得分:9)

我通常只需预先计算 ggplot2 以外的值并使用stat = "identity"来执行此操作:

df1 <- melt(ddply(df,.(gender),function(x){prop.table(table(x$outcome))}),id.vars = 1)

ggplot(df1, aes(x = variable,y = value)) +
    facet_wrap(~gender, nrow=2, ncol=1) +
    geom_bar(stat = "identity")