title: ggplot: percentile lines by group automation
body: <p>I've found the <code>dplyr</code> <code>%&gt;%</code> operator helpful with simple ggplot2 transformations (without resorting to <code>ggproto</code>, which is required for <a href="http://docs.ggplot2.org/dev/vignettes/extending-ggplot2.html" rel="nofollow noreferrer">ggplot2 extensions</a>), e.g.</p>
  
  <pre class="lang-r prettyprint-override"><code>library(ggplot2)
  library(scales)
  library(dplyr)
  
  gg.histo.pct.by.group &lt;- function(g, ...) {
    g + 
      geom_histogram(aes(y=unlist(lapply(unique(..group..), function(grp) ..count..[..group..==grp] / sum(..count..[..group..==grp])))), ...) +
      scale_y_continuous(labels = percent) + 
      ylab("% of total count by group")
  }
  
  data = diamonds %&gt;% select(carat, color) %&gt;% filter(color %in% c('H', 'D'))
  
  g = ggplot(data, aes(carat, fill=color)) %&gt;% 
    gg.histo.pct.by.group(binwidth=0.5, position="dodge")
  </code></pre>
  
  <p>It's common to add some percentile lines with labels to these types of graphs, e.g.,</p>
  
  <p><a href="https://i.stack.imgur.com/GSvgU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GSvgU.png" alt="R plot"></a></p>
  
  <p>One cut'n'paste way of doing this is</p>
  
  <pre class="lang-r prettyprint-override"><code>facts = data %&gt;% 
    group_by(color) %&gt;% 
    summarize(
      p50=quantile(carat, 0.5, na.rm=T), 
      p90=quantile(carat, 0.9, na.rm=T)
    )
  
  ymax = ggplot_build(g)$panel$ranges[[1]]$y.range[2]
  
  g +
    geom_vline(data=facts, aes(xintercept=p50, color=color), linetype="dashed", size=1) +
    geom_vline(data=facts, aes(xintercept=p90, color=color), linetype="dashed", size=1) +
    geom_text(data=facts, aes(x=p50, label=paste("p50=", p50), y=ymax, color=color), vjust=1.5, hjust=1, size=4, angle=90) +
    geom_text(data=facts, aes(x=p90, label=paste("p90=", p90), y=ymax, color=color), vjust=1.5, hjust=1, size=4, angle=90)
  </code></pre>
  
  <p>I'd love to encapsulate this into something like <code>g %&gt;% gg.percentile.x(c(.5, .9))</code> but I haven't been able to find a good way to combine the use of <code>aes_</code> or <code>aes_string</code> with the discovery of the grouping columns in the graph object in order to calculate the percentiles correctly. I'd appreciate some help with that.</p>