I'm unsure how to facet by a function of the data in the data
element of a ggplot
object. In the following toy example, what I want to do is something like this:
df <- data.frame(x=1:8, y=runif(8), z=8:1)
ggplot(df, aes(x=x, y=y)) + geom_point() + facet_wrap( ~ (z %% 2))
But that gives the error: Error in layout_base(data, vars, drop = drop) : At least one layer must contain all variables used for facetting
.
I can achieve the desired result by transforming the data frame:
ggplot(transform(df, z=z%%2), aes(x=x, y=y)) + geom_point() + facet_wrap( ~ z)
but often it's desirable to not use such a transformation, for instance if I've already been given a ggplot
object and I want to add some ad-hoc faceting to it.