How is the binning done in stat_summary_bin in ggplot2?

Viewed 473

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 stat_summary_bin(fun.y="mean"). 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.

Can anyone help me figure out how the binning in stat_summary_bin is done? I need to figure out if this is a reliable form of bin-scattering that I can use...

library(tidyverse)
library(mltools)
#> 
#> Attaching package: 'mltools'
#> The following object is masked from 'package:tidyr':
#> 
#>     replace_na
x = runif(1000, 0, 10)
y = x + rnorm(1000, 0.5, 2)
plot(x,y)

df <- data.frame(x = x, y = y)

p <- df %>%
  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 <-  mltools::bin_data(df$x, bins=20, binType = "explicit")
df_binned <- df %>%
  group_by(x_bin) %>%
  mutate(
    x_binned = mean(x),
    y_binned = mean(y)
  ) %>%
  ungroup()

p <- 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 <- cut(df$x, xbreaks, include.lowest = T)
df_binned <- df_binned %>%
  group_by(x_bin_2) %>%
  mutate(
    x_binned2 = mean(x),
    y_binned2 = mean(y)
  ) %>%
  ungroup()

p <- p + geom_point(aes(x = df_binned$x_binned2, y = df_binned$y_binned2, color = "2nd manual bin"), size = 2.5)
p

Created on 2018-09-09 by the reprex package (v0.2.0).

0 Answers
Related