Search code examples
rggplot2facet-grid

Using ggplot, how do I use multiple bin widths on a single facet


I would like to make a 2x2 facet_grid (using geom_bin2d) in ggplot where I can specify independently the bin widths by facet row or column.

Here is sample data:

x=runif(100,0,100)
y=runif(100,0,100)
topStrings=c("t1","t2")
sideStrings=c("s1","s2")
d=data.frame(cbind(x,y,top=sample(topStrings,100,replace=T),side=sample(sideStrings,100,replace=T)))

This will generate 100 rows of (x,y) tuples, each categorized twice (an s, and a t). Some have suggested that you can simply call geom_bin2d over each subset of the data and assign a bin width, like so:

ggplot(d, aes(x=x,y=y))+
    geom_bin2d(data=subset(d, side="s1"), binwidth = c(10,10))+
    geom_bin2d(data=subset(d, side="s2"), binwidth = c(10,1))+
    facet_grid(side~top,scales="free_y")

This should, according to my brain, show the top row (s1) with a larger bin than the bottom on (s2). But it doesn't seem to work. It seems that the whole plot just shows the maximum bin size. Any advice on how to do this?

Thanks


Solution

  • I side-stepped the problem by using stat_bin2d() instead. I'm not sure of all of the differences, but here you specify the bin count rather than the bin width. I'm ok having bin count constant throughout.