title: How is the binning done in stat_summary_bin in ggplot2?
body: <p>I'm trying to add some custom features to a bin-scatter plot using ggplot2. The original way that I was doing the bin-scatter was with <code>stat_summary_bin(fun.y="mean")</code>. This seems to produce a reasonable binning, but when I try to reproduce it by binning manually, I keep getting slightly different results -- especially at the right tail.</p>
  
  <p>Can anyone help me figure out how the binning in <code>stat_summary_bin</code> is done? I need to figure out if this is a reliable form of bin-scattering that I can use...</p>
  
  
  
  <pre class="lang-r prettyprint-override"><code>library(tidyverse)
  library(mltools)
  #&gt; 
  #&gt; Attaching package: 'mltools'
  #&gt; The following object is masked from 'package:tidyr':
  #&gt; 
  #&gt;     replace_na
  x = runif(1000, 0, 10)
  y = x + rnorm(1000, 0.5, 2)
  plot(x,y)
  
  df &lt;- data.frame(x = x, y = y)
  
  p &lt;- df %&gt;%
    ggplot(aes(x = x, y = y)) +
    stat_summary_bin(aes(color ="stat summary"),fun.y = "mean", size = 2.5, geom="point", bins=20)
  p
  
  ## Attempt 1 at binning
  df$x_bin &lt;-  mltools::bin_data(df$x, bins=20, binType = "explicit")
  df_binned &lt;- df %&gt;%
    group_by(x_bin) %&gt;%
    mutate(
      x_binned = mean(x),
      y_binned = mean(y)
    ) %&gt;%
    ungroup()
  
  p &lt;- p + geom_point(aes(x = df_binned$x_binned, y = df_binned$y_binned, color = "manual bin"), size = 2.5)
  p
  
  ## Attempt 2 at binning
  xbreaks = quantile(df$x, probs = seq(0,1,0.05))
  df_binned$x_bin_2 &lt;- cut(df$x, xbreaks, include.lowest = T)
  df_binned &lt;- df_binned %&gt;%
    group_by(x_bin_2) %&gt;%
    mutate(
      x_binned2 = mean(x),
      y_binned2 = mean(y)
    ) %&gt;%
    ungroup()
  
  p &lt;- p + geom_point(aes(x = df_binned$x_binned2, y = df_binned$y_binned2, color = "2nd manual bin"), size = 2.5)
  p
  </code></pre>
  
  <p>Created on 2018-09-09 by the <a href="http://reprex.tidyverse.org" rel="nofollow noreferrer">reprex
  package</a> (v0.2.0).</p>