ggplot - facet by function output

2020-04-02 09:34发布

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.

标签: r facet ggplot2
1条回答
Animai°情兽
2楼-- · 2020-04-02 10:08

this sounds familiar to me, but I never managed to fix it - I think facet variable handling is just less powerful than aesthetic variable handling.

Addressing your root requirement - to ad-hoc facet an existing ggplot; note that you can replace wholesale the (master) data set of an existing R ggplot - for instance

myplot %+% transform(myplot$data, z=z%%2)
查看更多
登录 后发表回答