根据第一个面板

时间:2016-09-23 19:40:19

标签: r sorting ggplot2 facet

是否可以根据第一个面板对ggplot2中的多面板图中的因子进行排序?第一个面板决定订单,其余面板遵循该订单。

以下是一个例子:

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)

这给了我这个情节:

enter image description here

现在,我想根据CLONE中的VALUE按降序排列YEAR X(从最高到最低),但仅限于控制(C面板) 。然后应该为T1T2T3维护此订单。通过查看上面的图表,我希望小组C排序为CLONE CBD(均为5),A和{{1} }。然后应该为剩余的面板复制此E的顺序。

1 个答案:

答案 0 :(得分:1)

在ggplot中没有简单的方法可以做到这一点,因为你必须重新排序CLONE 3个条件,TREAT,YEAR和VALUE,否则forcats::fct_reorder2可能是一个选项。 相反,从对应于YEAR =“X”的数据子集中提取CLONE的顺序, TREAT =“C”,并根据此子集重新定义整个数据集的因子水平。

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)

Barchart of CLONE ordered by a subpanel