2017-03-01 48 views
1

我有一個數據幀:標準化條形圖

df<-data.frame(Pet=rep(c("Dog", "Cat", "Bird"), c(5,10,15)), Gen=rep(c("M", "F", "M", "F", "M", "F"), c(3,5,12,5,3,2))) 

正如我想象的男性的頻率/女各動物我得到這個圖:

ggplot(df, aes(Pet, group=Gen, fill=Gen)) + geom_bar(position="dodge", width=.5) 

如何使一個圖表,會有相同高度的女性酒吧和相對高度與相應女性酒吧的男性酒吧?

事情是這樣的: Something like this

回答

1

一個簡單的解決將是首先標準化數據,然後做的情節:

t = table(df) 
as.data.frame.table(t/t[,'F']) %>% 
    ggplot(aes(x=Pet, y=Freq, group=Gen, fill=Gen)) + 
    geom_bar(position="dodge", width=.5, stat="identity") 

enter image description here