5

This question has been asked a few times, but I've read them all and cannot find an answer.

df <- data.frame(f1=factor(rbinom(100, 1, 0.45), label=c("m","w")), 
                 f2=factor(rbinom(100, 1, 0.45), label=c("young","old")),
                 boxthis=rnorm(100))
ggplot(aes(y=boxthis, x=f2), data=df) 
  + geom_boxplot() 
  + facet_grid(~f1, scales="free")

This generates the plot below, but the y axis is shared across the facet column. In my real data, this is a problem as each factor in f1 needs a widely different axis range. Is there some trick to getting free to work here?

plot

I have found that free works as expected when making the facet vertical, as shown below, but this clearly looks horrid compared to making the facet horizontal

ggplot(aes(y=boxthis, x=f2), data=df) 
  + geom_boxplot() 
  + facet_grid(f1~., scales="free")

plot2

Community
  • 1
  • 1
Hamy
  • 20,662
  • 15
  • 74
  • 102
  • 3
    Why not just using `facet_wrap` instead of `facet_grid`? – David Arenburg Jul 31 '14 at 15:08
  • @DavidArenburg - it works!! I've love to give you credit, would you post an answer? Also if you have any idea why wrap works and grid doesn't it would be good to know. I've never used `facet_wrap` before – Hamy Jul 31 '14 at 15:13

1 Answers1

6

I'll go ahead and post @DavidArenburg's answer here to close out the question. You should use facet_wrap rather than facet_grid

df <- data.frame(f1=factor(rbinom(100, 1, 0.35), label=c("m","w")), 
                 f2=factor(rbinom(100, 1, 0.65), label=c("young","old")),
                 boxthis=rnorm(100))
ggplot(aes(y=boxthis, x=f2), data=df) +
  geom_boxplot() +
  facet_wrap(~f1, scales="free")

Basically facet_grid tries to align everything nicely so that variable levels are the same across rows and columns in a rectangular layout and it's easy to compare across plots. facet_wrap isn't as picky and will just wrap plots into a an arbitrary number of rows and columns. That't why the latter allows you to specify nrows and ncols and the former does not (it uses the number of levels in the conditioning factor)

enter image description here

MrFlick
  • 195,160
  • 17
  • 277
  • 295