Is it possible to reorder only the facets of facet_wrap, without reordering the underlying factor levels?

早过忘川 提交于 2019-12-12 10:38:48

问题


Sample data frame:

df <- data.frame(x=rep(1:10,4),y=rnorm(40),Case=rep(c("B","L","BC","R"),each=10))

I can plot each time series in its own facet with:

ggplot(df,aes(x=x,y=y,color=Case)) + geom_line()+facet_wrap(~Case,nr=2,nc=2)

Now, suppose I want to change the facet order to (starting from top-left and going to bottom-right along rows) "L","B","R","BC". The usual suggestion here on SO is to do this. However, if I reorder the levels of factor Case, also the colors of the curves will be changed. Is it possible to reorder the facets, without changing also the order of the curve colors? I know it sounds like a weird question. The problem is that my report is a work in progress, and in a older version of the report, which I already showed to coworkers & management, there were multiple plots more or less like this (with no facet_wrap):

ggplot(df,aes(x=x,y=y,color=Case)) + geom_line()

In other words, by now people are used to associate the "B" to the red color. If I reorder, "L" will be red, "B" green, and so on. I can already hear the complaints...any way out of this one?


回答1:


Just copy the data into a new column with the order you want. Use the new column for faceting, the old column for the the color.

df$facet = factor(df$Case, levels = c("L", "B", "R", "BC"))

ggplot(df, aes(x = x, y = y, color = Case)) + 
    geom_line() + 
    facet_wrap(~facet, nr = 2)


来源:https://stackoverflow.com/questions/38834814/is-it-possible-to-reorder-only-the-facets-of-facet-wrap-without-reordering-the

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