按组对构面进行排序 [英] Sort facet by groups
本文介绍了按组对构面进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个看起来像这样的数据框
I have a data frame that looks like this
df <- data.frame(id=rep(c(1,5,2,6,4,3), each=5),
group=rep(c(1,2,2,2,1,1), each=5),
var1=runif(30))
我现在想使用 ggplot
绘制 var1
并通过 id
对该图进行分面,但是要按 group对该分面进行排序
(以及 group
中的 id
).我认为必须使 id
成为一个按 group
整齐地排列的级别的因子,但是我不知道如何优雅地完成此操作.
I now want to plot var1
using ggplot
and facet the plot by id
, but sort the facets by group
(and by id
within group
). I gather that I have to make id
a factor with levels that sort neatly by group
but I cannot figure out how to accomplish this elegantly.
推荐答案
# sort by group and id
df_sorted <- df[with(df, order(group, id)), ]
# reorder factor levels
df_sorted$id <- factor(df_sorted$id, levels=unique(df_sorted$id))
# plot something
ggplot(df_sorted, aes(var1)) + facet_wrap(~id) + geom_density()
这篇关于按组对构面进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文