Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using geom_boxplot with facet_grid and free_y

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

like image 312
Hamy Avatar asked Jul 31 '14 15:07

Hamy


1 Answers

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

like image 106
MrFlick Avatar answered Oct 11 '22 08:10

MrFlick