ggplot - facet by function output

試著忘記壹切 提交于 2019-12-04 03:09:52

问题


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.


回答1:


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)


来源:https://stackoverflow.com/questions/12271844/ggplot-facet-by-function-output

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!