skeletor
skeletor

Reputation: 361

R ggplot: grouped boxplot using group-variable in facet

I'd like to have a grouped boxplot. The problem is that the y-variable has large differnces between the first n factor levels and the second m factor levels. Three solutions seem possible:

  1. Create two seperate graphs and combine them with a shared legend.
  2. Create two different y-axes in one graph
  3. Use facet grid.

Since 1. and 2. appear to be cumbersome, I thought I'd give 3. a shot. The problem is, that in each subplot all factor level show up. The example below illustrates the issue.

library(ggplot2)

mtcars$carb.bin <- mtcars$carb > 2
mtcars$hp[mtcars$carb > 2] <- 10*mtcars$hp[mtcars$carb > 2]

ggplot(mtcars, aes(carb, hp)) + geom_boxplot(aes(fill = factor(carb))) +
facet_wrap(carb.bin~ ., scales = "free")

Example

Upvotes: 0

Views: 1948

Answers (1)

doctorG
doctorG

Reputation: 1731

Your syntax for facet_wrap() is confusing ggplot2 (well, me anyway ;-) ) From ?facet_wrap:

facets: Either a formula or character vector. Use either a one sided formula, ‘~a + b’, or a character vector, ‘c("a", "b")’.

I get

ggplot(mtcars, aes(carb, hp)) + geom_boxplot(aes(fill = factor(carb))) + 
facet_wrap(carb.bin~., scales = "free")
#Error in layout_base(data, vars, drop = drop) : 
 # At least one layer must contain all variables used for facetting
#and no plot
ggplot(mtcars, aes(carb, hp)) + geom_boxplot(aes(fill = factor(carb))) +
facet_wrap(~carb.bin, scales = "free")

#produces desired plot, add arg ncol=1 to have one facet above the other

enter image description here

Note the syntax/order of terms for your facet_wrap() formula.

Upvotes: 2

Related Questions