2012-06-04 22 views
6

我想要一個這樣的情節,除了每個方面總和爲100%。此時組M爲0.05 + 0.25 = 0.30而不是0.20 + 0.80 = 1.00。ggplot:兩組的相對頻率

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 ..給出更壞的結果。)

+0

這裏提供的答案是正確的方法。 ..density ..方法提供了許多其他答案, http://stackoverflow.com/questions/10064080/plot-relative-frequencies-with-dodged-bar-plots-in-ggplot2,http:// stackoverflow。 com/questions/17368223/ggplot2-multi-group-histogram-with-in-group-proportionortions-even-frequency,http://stackoverflow.com/questions/3695497/ggplot-showing-instead-of-counts-分類變量圖表產生不同程度不正確的值。 – russellpierce

回答

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") 
+0

這是正確的。我希望得到一個更簡單的答案,看起來像是一種相對常見的圖表。 :) – Andrew

+0

@andrew - 我這樣做*很多*。製作自己的'geom'相對容易,這對於ggplot2的內置工具來說是一個很好的補充。 – Chase

+0

@Chase我可能是錯誤的,但我認爲它不僅僅是一個新的geom,因爲(我認爲)美學被映射到變量之前。所以我認爲這可能是一個設計功能方式上游的幾何。 – joran

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

多麼可愛的黑客! – joran

+0

我喜歡這是短暫的,但是當我嘗試從facet切換到position = dodge時,所有組的高度總和爲100%(而不是在組內) – Andrew

+0

我希望我可以多加註意。 – Eduardo