简体   繁体   中英

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?

情节

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

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)

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM