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?

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")

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)

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With