title: ggplot graphing of proportions of observations within categories
body: <p>I am looking for advice on better ways to plot the proportion of observations in various categories.</p>
  
  <p>I have a dataframe that looks something like this:</p>
  
  <pre><code>cat1 &lt;- c("high", "low", "high", "high", "high", "low", "low", "low", "high", "low", "low")
  cat2 &lt;- c("1-young", "3-old", "2-middle-aged", "3-old", "2-middle-aged", "2-middle-aged", "1-young", "1-young", "3-old", "3-old", "1-young")
  df &lt;- as.data.frame(cbind(cat1, cat2))
  </code></pre>
  
  <p>In the example here, I want to plot the proportion <em>of each age group</em> that have the value "high", and the proportion <em>of each age group</em> that have the value "low". More generally, I want to plot, <em>for each value of category 2</em>, the percent of observations that fall into each of the levels of category 1.  </p>
  
  <p>The following code produces the right result, but only by manually counting and dividing before plotting. Is there a good way to do this on the fly within ggplot?</p>
  
  <pre><code>library(plyr)
  count1 &lt;- count(df, vars=c("cat1", "cat2"))
  count2 &lt;- count(df, "cat2")
  
  count1$totals &lt;- count2$freq
  count1$pct &lt;- count1$freq / count1$totals
  
  ggplot(data = count1, aes(x=cat2, y=pct))+
  facet_wrap(~cat1)+
  geom_bar()
  </code></pre>
  
  <p><a href="https://stackoverflow.com/questions/3695497/ggplot-showing-instead-of-counts-in-charts-of-categorical-variables">This previous stackoverflow question</a> offers something similar, with the following code:</p>
  
  <pre><code>ggplot(mydataf, aes(x = foo)) + 
  geom_bar(aes(y = (..count..)/sum(..count..)))
  </code></pre>
  
  <p>But I do not want "sum(..count..)" - which gives the sum of the count of <em>all</em> the bins - in the denominator; rather, I want the sum of the count of each of the "cat2" categories.  I have also studied the <a href="http://had.co.nz/ggplot2/stat_bin.html" rel="noreferrer">stat_bin</a> documentation. </p>
  
  <p>I would be grateful for any tips and suggestions on how to make this work.</p>