Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot: relative frequencies of two groups

Tags:

r

ggplot2

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) 

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

like image 207
Andrew Avatar asked Jun 04 '12 20:06

Andrew


1 Answers

here's another way

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) 
like image 94
Matthew Plourde Avatar answered Oct 07 '22 10:10

Matthew Plourde