根据第一个面板在ggplot2中的多面板图中的排序因子 [英] Sorting factors in multipanel plot in ggplot2 according to the first panel

查看:126
本文介绍了根据第一个面板在ggplot2中的多面板图中的排序因子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以根据第一个面板在ggplot2中的多面板图中对因子进行排序?第一个面板确定顺序,其余面板遵循该顺序.

Is it possible to sort factors in a multipanel plot in ggplot2 according to the first panel? The first panel decides the order and the remaining panels follow that order.

这里是一个例子:

require(ggplot2)
set.seed(36)
xx<-data.frame(YEAR=rep(c("X","Y"), each=20),
               CLONE=rep(c("A","B","C","D","E"), each=4, 2),
               TREAT=rep(c("T1","T2","T3","C"), 10),
               VALUE=sample(c(1:10), 40, replace=T))

ggplot(xx, aes(x=CLONE, y=VALUE, fill=YEAR)) + 
  geom_bar(stat="identity", position="dodge") +
  facet_wrap(~TREAT)

哪个给我这个情节:

现在,我想基于YEAR X中的VALUE以降序(从最高到最低)对CLONE进行排序,但仅针对控件(C面板).然后应为T1T2T3保持此顺序.通过查看上面的图,我希望将面板C排序为CLONE CBD(均为5),AE.然后应将CLONE的顺序复制到其余面板.

Now I would like to sort CLONE based on the VALUE in YEAR X in a descending order (highest to lowest) but only for the Control (C panel). This order should then be maintained for T1, T2, and T3. By looking at the plot above, I want panel C sorted as CLONE C, B or D (both are 5), A and E. This order of CLONE should then be replicated for the remaining panels.

推荐答案

在ggplot中没有简单的方法来正确执行此操作,因为您必须通过以下方式对CLONE重新排序 3个条件,即TREAT,YEAR和VALUE,否则可以选择forcats::fct_reorder2. 而是从与YEAR ="X"相对应的数据子集中提取CLONE的顺序, TREAT ="C",然后根据此子集为整个数据集重新定义因子水平.

There's no easy way to do this right in ggplot since you have to reorder CLONE by 3 conditions, TREAT, YEAR and VALUE, otherwise forcats::fct_reorder2 could have been an option. Instead, extract the order of CLONE from the subset of data corresponding to YEAR = "X", TREAT = "C", and re-define your factor levels for the whole data set based on this subset.

library("ggplot2")
library("dplyr")
set.seed(36)

xx <- data.frame(YEAR = rep(c("X","Y"), each = 20),
           CLONE = rep(c("A","B","C","D","E"), each = 4, 2),
           TREAT = rep(c("T1","T2","T3","C"), 10),
           VALUE = sample(c(1:10), 40, replace = TRUE), stringsAsFactors = FALSE)

clone_order <- xx %>% subset(TREAT == "C"  & YEAR == "X") %>%
  arrange(-VALUE) %>% select(CLONE) %>% unlist()

xx <- xx %>% mutate(CLONE = factor(CLONE, levels = clone_order))

ggplot(xx, aes(x = CLONE, y = VALUE, fill = YEAR)) + 
  geom_bar(stat = "identity", position = "dodge") +
  facet_wrap(~TREAT)

给予

这篇关于根据第一个面板在ggplot2中的多面板图中的排序因子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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