カテゴリ別の相対度数をggplotで棒グラフにする

例えば

qplot(color, data=diamonds, facets= ~cut)

とやると、以下のように因子別の度数を出してくれる。

f:id:ritchiekotzen:20150701210059p:plain

しかし、度数ではなく相対度数が欲しかった(facet間で比べたいので)。
簡単そうだが、やり方見つけるのに半日かかった…

d <- as.data.frame(prop.table(table(diamonds[,c("cut", "color")]), margin= 1))
ggplot(data=d) + aes(color, Freq) + facet_wrap(~ cut) + geom_bar(stat= "identity")

f:id:ritchiekotzen:20150701210938p:plain

やった!

ちなみに、color に相当する変数が数値でヒストグラムを出す場合は、

qplot(data=diamonds, facets= ~cut) + aes(x= color, y= ..density..)

で出るっぽい。