是否可以仅对facet_wrap的各个方面进行重新排序,而无需对基础因子级别进行重新排序? [英] Is it possible to reorder only the facets of facet_wrap, without reordering the underlying factor levels?

查看:70
本文介绍了是否可以仅对facet_wrap的各个方面进行重新排序,而无需对基础因子级别进行重新排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

样本数据框:

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)

现在,假设我想将构面顺序更改为(从行的左上角开始,到行的右下角)"L","B","R","BC".关于SO的通常建议是执行 this .但是,如果我重新排序因子Case的水平,曲线的颜色也会改变.是否可以在不更改曲线颜色顺序的情况下重新排列构面?我知道这听起来像个奇怪的问题.问题在于我的报告是一项正在进行的工作,并且是该报告的较旧版本,我已经向同事和同事展示了该报告.管理中,或多或少有多个这样的地块(没有facet_wrap):

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()

换句话说,到目前为止,人们已经习惯于将"B"与红色相关联.如果我重新排序,"L"将为红色,"B"将为绿色,依此类推.我已经可以听到抱怨了……从这个方法中可以解决吗?

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?

推荐答案

只需按照所需顺序将数据复制到新列中即可.使用新列作为方面,使用旧列作为颜色.

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)

这篇关于是否可以仅对facet_wrap的各个方面进行重新排序,而无需对基础因子级别进行重新排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆