I am trying to create a scatterplot with binned x-axis for binary data. When I use geom_point with binary y, the plot is pretty useless (see figure 1). As shown in figure 2, I want to bin the data based on the values of the x-axis and then plot the avg x and avg y within each bin using geom_point (mapping the the number of obs in each bin to the size of the point). I can do this by aggregating the data but I was wondering whether ggplot can do it directly. I played around with stat_bindot etc. but wasn’t able to find a solution. Any ideas? Below is some code.
Thanks!
# simulate data
n=1000
y=rbinom(n,1,0.5)
x=runif(n)
data=data.frame(x,y)
# figure 1 - geom_point with binary data, pretty useless!
ggplot(data,aes(x=x,y=y)) + geom_point() + ylim(0,1)
# let's create an aggregated dataset with bins
bin=cut(data$x,seq(0,1,0.05))
# I am sure the aggregation can be done in a better way...
data.bin=aggregate(data,list(bin),function(x) { return(c(mean(x),length(x)))})
# figure 2 - geom_point with binned x-axis, much nicer!
ggplot(data.bin,aes(x=x[,1],y=y[,1],size=x[,2])) + geom_point() + ylim(0,1)
Figures 1 and 2:


As @Kohske said, there is no direct way to do that in
ggplot2; you have to pre-summarize the data and pass that toggplot. Your approach works, but I would have done it slightly differently, using theplyrpackage instead ofaggregate.The advantage, in my opinion, is that you get a simple data frame with better names this way, rather than a data frame where some columns are matrices. But that is probably a matter of personal style than correctness.