ggplot:两组的相对频率 [英] ggplot: relative frequencies of two groups

查看:175
本文介绍了ggplot:两组的相对频率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want a plot like this except that each facet sums to 100%. Right now group M is 0.05+0.25=0.30 instead of 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 ..给出了更糟糕的结果。)

(Using y = ..density.. gives worse results.)

推荐答案

我通常只需预先计算 ggplot2 以外的值,然后使用 stat =identity

I usually do this by simply precalculating the values outside of ggplot2 and using 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")

这篇关于ggplot:两组的相对频率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆