Reputation: 361
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:
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")
Upvotes: 0
Views: 1948
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
Note the syntax/order of terms for your facet_wrap() formula.
Upvotes: 2